كيفية تحويل ورقة عمل Excel إلى PDF باستخدام .NET

كيفية تحويل ورقة عمل Excel إلى PDF باستخدام .NET

يظهر هذا المقال كيفية تحويل ملفات Excel إلى PDF مع ترتيب صفحة واحدة لكل ورقة باستخدام Aspose.Cells LowCode PDF Converter في تطبيقات .NET. يوفر محول PDF نهجًا متسارعين لتحويل أوراق إكسيل إلى مستندات PDF مصممة بشكل احترافي دون الحاجة إلى ترميز واسع أو معرفة عميقة بالهياكل الداخلية لـ Excel.

مشكلة العالم الحقيقي

غالبًا ما يحتاج المحللون الماليون إلى تحويل نماذج Excel المالية متعددة الورق إلى تقارير PDF القياسية حيث تظهر كل ورقة عمل على صفحتها الخاصة لتسهيل مراجعة الطباعة. إما أن تجمع أساليب التحويل التقليدية جميع البيانات على الصفحات المستمرة أو تتطلب المعالجة اليدوية لكل ورق.

نظرة عامة على الحل

باستخدام Aspose.Cells LowCode PDF Converter ، يمكننا حل هذا التحدي بفعالية مع الحد الأدنى من الرمز.هذا الحل مثالي للمهنيين الماليين ومطورين التقارير والمحللين التجاريين الذين يحتاجون إلى إنتاج تقريرات PDF المهنية في حين الحفاظ على الانفصال المنطقي لوحات العمل من مصادر بيانات Excel الخاصة بهم.

المتطلبات

قبل تنفيذ الحل، تأكد من أن لديك:

  • Visual Studio 2019 أو أحدث
  • .NET 6.0 أو أعلى (متوافق مع إطار .Net 4.6.2+)
  • Aspose.Cells للحزمة .NET المثبتة من خلال NuGet
  • الفهم الأساسي للبرمجة C#
PM> Install-Package Aspose.Cells

تنفيذ خطوة بخطوة

الخطوة 1: تثبيت وتكوين Aspose.Cells

إضافة حزمة Aspose.Cells إلى مشروعك وتشمل المساحات الاسمية اللازمة:

using Aspose.Cells;
using Aspose.Cells.LowCode;
using Aspose.Cells.Rendering;
using System;
using System.IO;

الخطوة 2: إعداد بيانات الإدخال الخاصة بك

تأكد من أن ملف المصدر يحتوي على ورقة عمل متعددة تريد تحويلها إلى صفحات منفصلة في PDF:

// Define the path to your Excel file
string excelFilePath = "financial-report-template.xlsx";

// Ensure the file exists
if (!File.Exists(excelFilePath))
{
    throw new FileNotFoundException("The specified Excel file was not found.", excelFilePath);
}

// Create output directory if it doesn't exist
string outputDirectory = "result";
if (!Directory.Exists(outputDirectory))
{
    Directory.CreateDirectory(outputDirectory);
}

الخطوة 3: إعداد خيارات PDF Converter

قم بتعيين خيارات عملية PDF Converter ، وتحديد إعداد صفحة واحدة لكل ورقة:

// Create the LowCode load options for the source file
LowCodeLoadOptions loadOptions = new LowCodeLoadOptions();
loadOptions.InputFile = excelFilePath;

// Create the LowCode PDF save options
LowCodePdfSaveOptions pdfSaveOptions = new LowCodePdfSaveOptions();

// Configure PDF-specific settings
PdfSaveOptions pdfOptions = new PdfSaveOptions();
pdfOptions.OnePagePerSheet = true;  // This is the key setting for our requirement

// Optionally set additional PDF options
pdfOptions.Compliance = PdfCompliance.PdfA1b;  // For archival compliance if needed
pdfOptions.AllColumnsInOnePagePerSheet = true; // Ensure all columns fit on one page

// Apply the PDF options to our save options
pdfSaveOptions.PdfOptions = pdfOptions;

// Set the output file path
string outputFilePath = Path.Combine(outputDirectory, "FinancialReport.pdf");
pdfSaveOptions.OutputFile = outputFilePath;

الخطوة 4: تنفيذ عملية تحويل PDF

قم بتشغيل عملية PDF Converter باستخدام الخيارات المحددة:

try
{
    // Process the conversion using the LowCode PDF Converter
    PdfConverter.Process(loadOptions, pdfSaveOptions);
    
    Console.WriteLine($"Conversion completed successfully. PDF saved to: {outputFilePath}");
}
catch (Exception ex)
{
    Console.WriteLine($"Error during conversion: {ex.Message}");
    // Log the exception or handle it according to your application's requirements
}

الخطوة الخامسة: قم بتجهيز النتيجة

بعد التحويل، قد ترغب في فتح PDF أو مزيد من معالجتها:

// Check if the output file was created
if (File.Exists(outputFilePath))
{
    // Open the file using the default PDF viewer (optional)
    try
    {
        System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
        {
            FileName = outputFilePath,
            UseShellExecute = true
        });
    }
    catch (Exception ex)
    {
        Console.WriteLine($"The file was created but could not be opened: {ex.Message}");
    }
}
else
{
    Console.WriteLine("The output file was not created.");
}

الخطوة 6: تنفيذ خطأ التعامل

إضافة المعالجة الصحيحة للخطأ لضمان عمل قوي:

try
{
    // Create the load options
    LowCodeLoadOptions loadOptions = new LowCodeLoadOptions();
    
    // Verify input file exists before assigning
    if (!File.Exists(excelFilePath))
    {
        throw new FileNotFoundException("Input Excel file not found", excelFilePath);
    }
    
    loadOptions.InputFile = excelFilePath;
    
    // Create and configure PDF save options
    LowCodePdfSaveOptions pdfSaveOptions = new LowCodePdfSaveOptions();
    PdfSaveOptions pdfOptions = new PdfSaveOptions();
    pdfOptions.OnePagePerSheet = true;
    pdfSaveOptions.PdfOptions = pdfOptions;
    pdfSaveOptions.OutputFile = outputFilePath;
    
    // Execute conversion
    PdfConverter.Process(loadOptions, pdfSaveOptions);
    
    // Verify output was created
    if (!File.Exists(outputFilePath))
    {
        throw new Exception("PDF conversion completed but output file was not created");
    }
    
    Console.WriteLine("Conversion successful!");
}
catch (CellsException cellsEx)
{
    // Handle Aspose.Cells specific exceptions
    Console.WriteLine($"Aspose.Cells error: {cellsEx.Message}");
    // Consider logging the exception or custom handling based on cellsEx.Code
}
catch (IOException ioEx)
{
    // Handle file IO exceptions
    Console.WriteLine($"File operation error: {ioEx.Message}");
}
catch (Exception ex)
{
    // Handle other exceptions
    Console.WriteLine($"General error: {ex.Message}");
}

الخطوة السابعة: تحسين الأداء

انظر هذه التقنيات التحسينية لبيئات الإنتاج:

  • استخدم MemoryStream لمعالجة الحجم العالي:
// For high-volume processing, using memory streams can be more efficient
using (MemoryStream outputStream = new MemoryStream())
{
    // Configure save options to use memory stream
    LowCodePdfSaveOptions pdfSaveOptions = new LowCodePdfSaveOptions();
    pdfSaveOptions.OutputStream = outputStream;
    pdfSaveOptions.PdfOptions = new PdfSaveOptions { OnePagePerSheet = true };
    
    // Process the conversion
    PdfConverter.Process(loadOptions, pdfSaveOptions);
    
    // Now you can use the stream as needed (save to file, send via network, etc.)
    outputStream.Position = 0;
    using (FileStream fileStream = File.Create(outputFilePath))
    {
        outputStream.CopyTo(fileStream);
    }
}
  • لعملية معالجة الحزمة، وإعادة استخدام الكائنات عند الإمكان:
// Create PDF options once and reuse
PdfSaveOptions pdfOptions = new PdfSaveOptions { OnePagePerSheet = true };

// Process multiple files
foreach (string excelFile in Directory.GetFiles("input-directory", "*.xlsx"))
{
    LowCodeLoadOptions loadOptions = new LowCodeLoadOptions { InputFile = excelFile };
    LowCodePdfSaveOptions saveOptions = new LowCodePdfSaveOptions
    {
        PdfOptions = pdfOptions,
        OutputFile = Path.Combine("output-directory", Path.GetFileNameWithoutExtension(excelFile) + ".pdf")
    };
    
    PdfConverter.Process(loadOptions, saveOptions);
}

الخطوة 8: نموذج التنفيذ الكامل

وهنا مثال عمل كامل يثبت العملية بأكملها:

using Aspose.Cells;
using Aspose.Cells.LowCode;
using Aspose.Cells.Rendering;
using System;
using System.IO;

namespace ExcelToPdfConverter
{
    class Program
    {
        static void Main(string[] args)
        {
            // Define input and output paths
            string inputDirectory = "input-files";
            string outputDirectory = "result";
            string excelFilePath = Path.Combine(inputDirectory, "financial-report.xlsx");
            
            // Ensure directories exist
            Directory.CreateDirectory(outputDirectory);
            
            try
            {
                Console.WriteLine($"Converting {excelFilePath} to PDF...");
                
                // Simple one-line approach (less customization)
                string quickOutputPath = Path.Combine(outputDirectory, "QuickOutput.pdf");
                PdfConverter.Process(excelFilePath, quickOutputPath);
                Console.WriteLine($"Basic conversion completed: {quickOutputPath}");
                
                // Advanced approach with custom options
                // Setup load options
                LowCodeLoadOptions loadOptions = new LowCodeLoadOptions
                {
                    InputFile = excelFilePath
                };
                
                // Setup PDF save options with specific settings
                LowCodePdfSaveOptions pdfSaveOptions = new LowCodePdfSaveOptions();
                PdfSaveOptions pdfOptions = new PdfSaveOptions
                {
                    OnePagePerSheet = true,
                    Compliance = PdfCompliance.PdfA1b,
                    PrintingPageType = PrintingPageType.ActualSize
                };
                pdfSaveOptions.PdfOptions = pdfOptions;
                
                string customOutputPath = Path.Combine(outputDirectory, "CustomOutput.pdf");
                pdfSaveOptions.OutputFile = customOutputPath;
                
                // Execute the conversion
                PdfConverter.Process(loadOptions, pdfSaveOptions);
                Console.WriteLine($"Advanced conversion completed: {customOutputPath}");
                
                // Batch processing example
                BatchProcessExcelFiles(inputDirectory, outputDirectory);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
            
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
        
        static void BatchProcessExcelFiles(string inputDir, string outputDir)
        {
            // Get all Excel files
            string[] excelFiles = Directory.GetFiles(inputDir, "*.xlsx");
            
            if (excelFiles.Length == 0)
            {
                Console.WriteLine("No Excel files found for batch processing.");
                return;
            }
            
            // Create reusable PDF options
            PdfSaveOptions pdfOptions = new PdfSaveOptions
            {
                OnePagePerSheet = true
            };
            
            Console.WriteLine($"Batch processing {excelFiles.Length} files...");
            
            foreach (string file in excelFiles)
            {
                try
                {
                    string fileName = Path.GetFileNameWithoutExtension(file);
                    string outputPath = Path.Combine(outputDir, $"{fileName}.pdf");
                    
                    // Configure options
                    LowCodeLoadOptions loadOptions = new LowCodeLoadOptions
                    {
                        InputFile = file
                    };
                    
                    LowCodePdfSaveOptions saveOptions = new LowCodePdfSaveOptions
                    {
                        PdfOptions = pdfOptions,
                        OutputFile = outputPath
                    };
                    
                    // Process conversion
                    PdfConverter.Process(loadOptions, saveOptions);
                    Console.WriteLine($"Converted: {Path.GetFileName(file)} -> {Path.GetFileName(outputPath)}");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error processing {Path.GetFileName(file)}: {ex.Message}");
                }
            }
            
            Console.WriteLine("Batch processing completed.");
        }
    }
}

استخدام الحالات والتطبيقات

أنظمة الإبلاغ المؤسسي

يمكن للمؤسسات المالية تلقائيًا إنتاج تقارير PDF المعيارية من نماذج بيانات Excel. تظهر كل ورقة عمل تحتوي على مقياسات مالية مختلفة (أوراق التوازن، وتصريحات الدخل، والتوقعات في تدفق النقد) على صفحتها الخاصة، مع الحفاظ على انفصال واضح للبيانات مع ضمان تنسيق متسق بين جميع التقاريم.

وثيقة الامتثال التنظيمي

يمكن للمؤسسات التي تحتاج إلى تقديم البيانات المالية أو التشغيلية القياسية إلى الهيئات التنظيمية تحويل بياناتها القائمة على Excel إلى تنسيقات PDF متوافقة.يضمن خيار صفحة واحدة لكل ورقة أن كل نموذج تنظيمي أو مجموعة بيانات يحافظ على سلامتها وتصميمها المناسب عند تقديمها إلكترونياً أو مطبوعة، مما يقلل من مخاطر الامتثال الناجمة عن أخطاء التصميم.

نظام توزيع التقارير التلقائي

يمكن لقطاعات المبيعات أو التشغيل تنفيذ أنظمة أوتوماتيكية حيث يتم تحويل بيانات Excel بانتظام إلى ملفات PDF المهنية لتوزيعها للعملاء أو أصحاب المصلحة الداخليين.يضمن تنسيق صفحة واحدة لكل ورقة أن المستلمين يحصلون على وثائق منظمة بشكل جيد حيث تظهر كل وحدة عمل أو خط منتج أو فترة زمنية على صفحتها الخاصة لتسهيل الملاحة والتحليل.

التحديات والحلول المشتركة

التحدي الأول: توسيع ورقة العمل الكبيرة عبر حدود الصفحات

الحل: تعديل خيارات PDF للتعامل مع ورقات العمل الكبيرة عن طريق تغيير إعدادات التوسع:

PdfSaveOptions pdfOptions = new PdfSaveOptions();
pdfOptions.OnePagePerSheet = true;
pdfOptions.AllColumnsInOnePagePerSheet = false; // Let large sheets span multiple pages horizontally
pdfOptions.WidthFitToPagesCount = 2; // Allow up to 2 pages for width if needed

التحدي 2: العناوين المخصصة والأقدام التي لا تظهر في PDF

الحلول: إدخال الرؤوس والأقدام المخصصة في إصدار PDF:

PdfSaveOptions pdfOptions = new PdfSaveOptions();
pdfOptions.OnePagePerSheet = true;

// Add custom header and footer
pdfOptions.IsCustomPrintAreaSet = true;
pdfOptions.CustomPrintPageTopMargin = 50;
pdfOptions.CustomPrintPageBottomMargin = 50;
pdfOptions.HeaderFooterManager.SetHeader(HeaderFooterType.FirstPage, "Company Financial Report");
pdfOptions.HeaderFooterManager.SetFooter(HeaderFooterType.AllPages, "&P of &N");

التحدي 3: الصور والرسوم البيانية التي تصبح غير صحيحة في PDF

** الحل:** تحسين جودة الصورة والرسوم البيانية باستخدام الإعدادات التالية:

PdfSaveOptions pdfOptions = new PdfSaveOptions();
pdfOptions.OnePagePerSheet = true;
pdfOptions.Quality = 100; // Highest quality setting
pdfOptions.DefaultEditLanguage = EditLanguage.Default; // Proper text rendering
pdfOptions.CheckFontCompatibility = true; // Ensure fonts are compatible

اعتبارات الأداء

  • بالنسبة لكتب العمل متعددة الشرائح ، يمكن أن يكون العملية مكثفة في الذاكرة ؛ فكر في معالجة الملفات بشكل متسلسل بدلاً من التوازي على أنظمة محاصرة في الذكاء.
  • عند تحويل ملفات Excel الكبيرة، استخدم نهج البث للحد من استخدام الذاكرة.
  • للتحويلات المتكررة من نفس الملف مع إعدادات مختلفة ، قم بتحميله مرة واحدة في الذاكرة وإعادة استخدامه.
  • التفكير في تنفيذ نظام التحويل للبيئات ذات الحجم العالي لإدارة استخدام الموارد.

أفضل الممارسات

  • تأكيد دائمًا ملفات الإدخال قبل المعالجة لمنع استثناءات وقت التشغيل.
  • تنفيذ المعالجة الصحيحة للخطأ حول عمليات الملفات I/O وعمليات التحويل.
  • إعداد معايير الامتثال المناسبة لـ PDF (PDF/A-1b، PDF 1.7) استنادًا إلى متطلبات الأرشيف أو التوزيع الخاصة بك.
  • يتم تخزين الملفات أو القوالب المستخدمة في كثير من الأحيان لتحسين الأداء للعمليات المتكررة.
  • التفكير في تنفيذ تقارير التقدم للتحويلات على المدى الطويل.

سيناريوهات متقدمة

للحصول على متطلبات أكثر تعقيدًا ، فكر في هذه التطبيقات المتقدمة:

السيناريو 1: تحويل ورقة اختيارية مع توجيه الصفحة المخصصة

// Create load options
LowCodeLoadOptions loadOptions = new LowCodeLoadOptions();
loadOptions.InputFile = "multi-sheet-report.xlsx";

// Create PDF save options with advanced settings
LowCodePdfSaveOptions pdfSaveOptions = new LowCodePdfSaveOptions();
PdfSaveOptions pdfOptions = new PdfSaveOptions();
pdfOptions.OnePagePerSheet = true;

// Only convert specific sheets
Workbook workbook = new Workbook(loadOptions.InputFile);
pdfOptions.SheetSet = new Aspose.Cells.Rendering.SheetSet(new int[] { 0, 2, 3 }); // Select specific sheets by index

// Set page orientation based on sheet content
foreach (Worksheet sheet in workbook.Worksheets)
{
    if (sheet.Cells.MaxColumn > 10) // Wide sheets get landscape orientation
    {
        PageSetup pageSetup = sheet.PageSetup;
        pageSetup.Orientation = PageOrientationType.Landscape;
    }
}

pdfSaveOptions.PdfOptions = pdfOptions;
pdfSaveOptions.OutputFile = "selective-sheets-report.pdf";

// Process the conversion
PdfConverter.Process(loadOptions, pdfSaveOptions);

السيناريو 2: إضافة التوقيعات الرقمية إلى PDFs المولدة

// Standard conversion setup
LowCodeLoadOptions loadOptions = new LowCodeLoadOptions();
loadOptions.InputFile = "financial-statement.xlsx";

LowCodePdfSaveOptions pdfSaveOptions = new LowCodePdfSaveOptions();
PdfSaveOptions pdfOptions = new PdfSaveOptions();
pdfOptions.OnePagePerSheet = true;

// Set up digital signature parameters
pdfOptions.DigitalSignature = new DigitalSignature();
pdfOptions.DigitalSignature.CertificateFilePath = "signature-certificate.pfx";
pdfOptions.DigitalSignature.Password = "certificate-password";
pdfOptions.DigitalSignature.Reason = "Financial approval";
pdfOptions.DigitalSignature.Location = "Finance Department";
pdfOptions.DigitalSignature.SignatureDate = DateTime.Now;

pdfSaveOptions.PdfOptions = pdfOptions;
pdfSaveOptions.OutputFile = "signed-financial-report.pdf";

// Process the conversion with digital signature
PdfConverter.Process(loadOptions, pdfSaveOptions);

استنتاجات

من خلال تنفيذ Aspose.Cells LowCode PDF Converter، يمكنك بفعالية تحويل ورقة عمل Excel متعددة إلى مستندات PDF مصممة بشكل احترافي والحفاظ على الانفصال المنطقي للورقة العملية مع خيار صفحة واحدة لكل ورق.

للحصول على مزيد من المعلومات والمزيد من الأمثلة، ارجع إلى Aspose.Cells.LowCode API مرجعية .

 عربي