Bagaimana untuk menukar lembaran kerja Excel ke PDF dengan .NET

Bagaimana untuk menukar lembaran kerja Excel ke PDF dengan .NET

Artikel ini menunjukkan bagaimana untuk menukar fail Excel ke dalam PDF dengan tataletak satu halaman-per lembaran menggunakan Aspose.Cells LowCode PDF Converter dalam aplikasi .NET.Penukar PDF menyediakan pendekatan yang lancar untuk mengubah skrip Excel menjadi dokumen PDF yang diformatkan secara profesional tanpa memerlukan pengekodan yang luas atau pengetahuan yang mendalam mengenai struktur dalaman Excel.

Masalah dunia sebenar

Para penganalisis kewangan sering perlu menukar pelbagai lembaran Model Kewangan Excel ke dalam laporan PDF standard di mana setiap lembar kerja muncul pada halaman mereka sendiri untuk pemeriksaan dan pencetakan yang lebih mudah. kaedah penukaran tradisional sama ada menggabungkan semua data ke halaman yang berterusan atau memerlukan pemprosesan manual bagi setiap Lembaran. Selain itu, dalam persekitaran perniagaan, pertukaran ini perlu diautomatik, konsisten, dan disepadukan dalam aliran kerja yang sedia ada.

Gambaran keseluruhan penyelesaian

Dengan menggunakan Aspose.Cells LowCode PDF Converter, kita boleh menyelesaikan cabaran ini dengan cekap dengan kod minimum. penyelesaian ini sesuai untuk profesional kewangan, pembangun laporan, dan penganalisis perniagaan yang perlu menghasilkan laporan PDF profesional sambil mengekalkan pemisahan logik lembaran kerja daripada sumber data Excel mereka.

Prerequisites

Sebelum melaksanakan penyelesaian, pastikan anda mempunyai:

  • Visual Studio 2019 atau seterusnya
  • .NET 6.0 atau seterusnya (sesuai dengan .Net Framework 4.6.2+)
  • Aspose.Cells untuk pakej .NET yang dipasang melalui NuGet
  • Pemahaman asas tentang pemrograman C#
PM> Install-Package Aspose.Cells

Pelaksanaan langkah demi langkah

Langkah 1: Pemasangan dan Konfigurasi Aspose.Cells

Tambah pakej Aspose.Cells kepada projek anda dan termasuk ruang nama yang diperlukan:

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

Langkah 2: Sediakan data input anda

Untuk contoh ini, kami akan menggunakan fail Excel yang sedia ada. pastikan fail sumber anda mengandungi beberapa lembaran kerja yang anda ingin konversi ke halaman berasingan dalam 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);
}

Langkah 3: Mengesetkan opsyen PDF Converter

Tetapkan opsyen untuk proses PDF Converter, menentukan seting satu halaman per lembaran:

// 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;

Langkah 4: Melaksanakan proses penukaran PDF

Melaksanakan operasi PDF Converter dengan opsyen yang dikonfigurasi:

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
}

Langkah 5: Menguruskan output

Selepas penukaran, anda mungkin mahu membuka PDF atau memprosesnya lebih lanjut:

// 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.");
}

Langkah 6 : Menguruskan kesilapan

Menambah pemprosesan kesilapan yang betul untuk memastikan operasi yang kukuh:

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}");
}

Langkah 7: Mengoptimumkan prestasi

Pertimbangkan teknik pengoptimuman ini untuk persekitaran pengeluaran:

  • Menggunakan MemoryStream untuk pemprosesan volum tinggi:
// 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);
    }
}
  • Untuk pemprosesan batch, gunakan semula objek apabila mungkin:
// 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);
}

Langkah 8: Contoh pelaksanaan lengkap

Berikut ialah contoh kerja lengkap yang membuktikan keseluruhan proses:

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.");
        }
    }
}

Penggunaan Kasus dan Permohonan

Sistem Laporan Perniagaan

Setiap lembaran kerja yang mengandungi metrik kewangan yang berbeza (lembaran keseimbangan, laporan pendapatan, projeksi aliran tunai) muncul di halaman mereka sendiri, mengekalkan pemisahan data yang jelas sambil memastikan pemformatan yang konsisten di seluruh laporan. Ini meningkatkan kebolehbacaan bagi ahli jawatankuasa, auditor, dan peninjau peraturan.

Generasi Dokumen Kepatuhan Peraturan

Organisasi yang perlu mengemukakan data kewangan atau operasi standard kepada badan-badan pengawal selia boleh menukar data mereka berasaskan Excel ke dalam format PDF yang mematuhi. opsyen satu halaman per lembaran memastikan bahawa setiap borang atau set data peraturan mengekalkan integriti dan tataletak yang betul apabila diserahkan secara elektronik atau percetakan, mengurangkan risiko pematuhan daripada kesilapan pemformatan.

Sistem Pengedaran Laporan Automatik

Jabatan jualan atau operasi boleh melaksanakan sistem automatik di mana data Excel secara berkala ditukar kepada PDF profesional untuk pengedaran kepada pelanggan atau pihak berkepentingan dalaman. format satu halaman per lembaran memastikan bahawa penerima menerima dokumen yang terstruktur dengan setiap unit perniagaan, barisan produk, atau tempoh masa muncul pada halaman mereka sendiri untuk navigasi dan analisis yang lebih mudah.

Tantangan dan Penyelesaian Bersama

Tantangan 1: Lembaran kerja besar melampaui sempadan halaman

** Penyelesaian:** Menyesuaikan opsyen PDF untuk mengendalikan lembaran kerja yang besar dengan mengubah tetapan skala:

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

Tantangan 2: tajuk dan kaki tersuai yang tidak muncul dalam PDF

** Penyelesaian:** Mengimplementasikan kepala dan kaki tersuai dalam output 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");

Tantangan 3 : Gambar dan carta yang tidak betul dalam PDF

** Penyelesaian:** Meningkatkan kualiti imej dan carta dengan tetapan berikut:

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

Pertimbangan prestasi

  • Untuk buku kerja berbilang lembaran, proses ini boleh menjadi memori-intens; pertimbangkan pemprosesan fail secara berurutan daripada secara serentak pada sistem-sistem yang dikekalkan.
  • Apabila menukar fail Excel yang besar, gunakan pendekatan streaming untuk mengurangkan penggunaan memori.
  • Untuk penukaran berulang fail yang sama dengan tetapan yang berbeza, muat fail sekali ke dalam memori dan gunakan semula.
  • Pertimbangkan pelaksanaan sistem kuing untuk persekitaran volum tinggi untuk menguruskan penggunaan sumber.

amalan terbaik

  • Sentiasa mengesahkan fail input sebelum pemprosesan untuk mengelakkan pengecualian masa kerja.
  • Melaksanakan pemprosesan ralat yang betul di sekitar operasi fail I/O dan proses penukaran.
  • Tetapkan piawaian pematuhan PDF yang sesuai (PDF/A-1b, PDF 1.7) berdasarkan keperluan arkib atau pengedaran anda.
  • Cache sering menggunakan fail atau templat untuk meningkatkan prestasi untuk operasi berulang.
  • Pertimbangkan pelaksanaan laporan kemajuan untuk penukaran batch jangka panjang.

Senario lanjutan

Untuk keperluan yang lebih kompleks, pertimbangkan pelaksanaan lanjutan ini:

Senario 1: Penukaran lembaran selektif dengan orientasi halaman yang disesuaikan

// 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);

Senario 2: Menambah tandatangan digital kepada PDF yang dihasilkan

// 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);

Conclusion

Dengan melaksanakan Aspose.Cells LowCode PDF Converter, anda boleh dengan cekap menukar buku kerja Excel berbilang lembaran ke dalam dokumen PDF yang diformat secara profesional dan mengekalkan pemisahan lembar kerja logik dengan opsyen satu halaman-ke-lapar. pendekatan ini secara signifikan menyempurnakan proses laporan kewangan dan perniagaan sambil memelihara integriti dokumen dan penampilan profesional.

Untuk maklumat lanjut dan contoh tambahan, rujuk kepada Aspose.Cells.LowCode API rujukan .

 Melayu