Bagaimana untuk Batch Menukar fail Excel ke PDF dalam .NET

Bagaimana untuk Batch Menukar fail Excel ke PDF dalam .NET

Artikel ini menunjukkan bagaimana untuk menggabungkan beberapa fail Excel ke dalam PDF menggunakan Aspose.Cells LowCode PDF Converter dalam aplikasi .NET. Konversi PDF menyediakan pendekatan yang lancar kepada penukaran dokumen tanpa memerlukan pengekodan yang luas atau pengetahuan yang mendalam tentang struktur dalaman Excel - sempurna untuk penganalisis perniagaan dan pembangun laporan yang perlu mengautomatikkan aliran kerja laporan mereka.

Masalah dunia sebenar

Dalam persekitaran perniagaan, pasukan laporan sering perlu menukar puluhan atau bahkan beratus-ratus buku kerja Excel ke format PDF secara teratur. Melakukan ini secara manual adalah masa-makanan, error-prone, dan memisahkan sumber-sumber yang berharga daripada tugas-tugas analisis yang lebih penting. Selain itu, memastikan pemformatan dan tataletak yang konsisten di seluruh laporan adalah mencabar apabila mengubah fail secara individu.

Gambaran keseluruhan penyelesaian

Dengan menggunakan Aspose.Cells LowCode PDF Converter, kita boleh menyelesaikan cabaran ini dengan cekap dengan kod minimum. penyelesaian ini sesuai untuk penganalisis perniagaan dan pembangun laporan yang perlu menyesuaikan proses laporan mereka, memastikan konsistensi di seluruh dokumen, dan membebaskan masa untuk kerja yang lebih berharga. pendekatan kami akan memberi tumpuan kepada mewujudkan sistem pemprosesan batch yang kukuh yang boleh mengendalikan jumlah besar fail Excel dengan tetapan penukaran tersuai.

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 System;
using System.IO;
using System.Collections.Generic;
using System.Threading.Tasks;

Langkah 2: Mencipta struktur direktori untuk pemprosesan batch

Menetapkan struktur direktori untuk mengatur fail input Excel dan fail output PDF anda:

// Create directories if they don't exist
string inputDirectory = @"C:\Reports\ExcelFiles";
string outputDirectory = @"C:\Reports\PDFOutput";
string logDirectory = @"C:\Reports\Logs";

Directory.CreateDirectory(inputDirectory);
Directory.CreateDirectory(outputDirectory);
Directory.CreateDirectory(logDirectory);

Langkah 3: Pelaksanaan File Discovery Logic

Mencipta kaedah untuk mencari semua fail Excel yang perlu ditukar:

private List<string> GetExcelFilesToProcess(string directoryPath, string searchPattern = "*.xlsx")
{
    List<string> excelFiles = new List<string>();
    
    try
    {
        // Get all Excel files (.xlsx) in the directory
        string[] files = Directory.GetFiles(directoryPath, searchPattern);
        excelFiles.AddRange(files);
        
        // Optionally, you can also search for .xls files
        string[] oldFormatFiles = Directory.GetFiles(directoryPath, "*.xls");
        excelFiles.AddRange(oldFormatFiles);
        
        Console.WriteLine($"Found {excelFiles.Count} Excel files to process.");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Error searching for Excel files: {ex.Message}");
    }
    
    return excelFiles;
}

Langkah 4: Mengesetkan opsyen PDF Converter

Mencipta kaedah untuk menetapkan opsyen penukaran PDF untuk output yang konsisten:

private LowCodePdfSaveOptions ConfigurePdfOptions(bool onePagePerSheet = true, 
                                                 bool includeHiddenSheets = false,
                                                 bool printComments = false)
{
    // Create PDF save options
    PdfSaveOptions pdfOpts = new PdfSaveOptions();
    
    // Set whether each worksheet should be rendered as a separate page
    pdfOpts.OnePagePerSheet = onePagePerSheet;
    
    // Option to include hidden worksheets in the output
    pdfOpts.AllColumnsInOnePagePerSheet = true;
    
    // Configure additional PDF options
    pdfOpts.Compliance = PdfCompliance.PdfA1b; // For archival quality
    pdfOpts.PrintingPageType = PrintingPageType.ActualSize;
    
    // Configure comment display options
    pdfOpts.PrintComments = printComments ? PrintCommentsType.PrintInPlace : PrintCommentsType.PrintNoComments;
    
    // Create low code PDF save options
    LowCodePdfSaveOptions lcsopts = new LowCodePdfSaveOptions();
    lcsopts.PdfOptions = pdfOpts;
    
    return lcsopts;
}

Langkah 5: Mengimplementasikan logik penukaran fail tunggal

Mencipta kaedah untuk menukar satu fail Excel ke dalam PDF:

private bool ConvertExcelToPdf(string inputFilePath, string outputFilePath, LowCodePdfSaveOptions pdfOptions)
{
    try
    {
        // Create load options
        LowCodeLoadOptions loadOptions = new LowCodeLoadOptions();
        loadOptions.InputFile = inputFilePath;
        
        // Set output file path
        pdfOptions.OutputFile = outputFilePath;
        
        // Process the conversion
        PdfConverter.Process(loadOptions, pdfOptions);
        
        return true;
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Error converting {Path.GetFileName(inputFilePath)}: {ex.Message}");
        return false;
    }
}

Langkah 6: Melaksanakan batch pemprosesan logik

Sekarang cipta kaedah utama yang akan memproses pelbagai fail:

public void BatchConvertExcelToPdf(string inputDirectory, string outputDirectory, string searchPattern = "*.xlsx")
{
    // Get all Excel files
    List<string> excelFiles = GetExcelFilesToProcess(inputDirectory, searchPattern);
    
    // Configure PDF options
    LowCodePdfSaveOptions pdfOptions = ConfigurePdfOptions(true, false, false);
    
    // Track conversion statistics
    int successCount = 0;
    int failureCount = 0;
    
    // Process each file
    foreach (string excelFile in excelFiles)
    {
        string fileName = Path.GetFileNameWithoutExtension(excelFile);
        string outputFilePath = Path.Combine(outputDirectory, $"{fileName}.pdf");
        
        Console.WriteLine($"Converting: {fileName}");
        
        bool success = ConvertExcelToPdf(excelFile, outputFilePath, pdfOptions);
        
        if (success)
        {
            successCount++;
            Console.WriteLine($"Successfully converted: {fileName}");
        }
        else
        {
            failureCount++;
            Console.WriteLine($"Failed to convert: {fileName}");
        }
    }
    
    // Report summary
    Console.WriteLine("\n===== Conversion Summary =====");
    Console.WriteLine($"Total files processed: {excelFiles.Count}");
    Console.WriteLine($"Successfully converted: {successCount}");
    Console.WriteLine($"Failed conversions: {failureCount}");
}

Langkah 7: Melaksanakan pemprosesan serentak untuk prestasi yang lebih baik

Untuk batch besar, melaksanakan pemprosesan paralel untuk mempercepatkan penukaran:

public void ParallelBatchConvertExcelToPdf(string inputDirectory, string outputDirectory, string searchPattern = "*.xlsx")
{
    // Get all Excel files
    List<string> excelFiles = GetExcelFilesToProcess(inputDirectory, searchPattern);
    
    // Track conversion statistics
    int successCount = 0;
    int failureCount = 0;
    object lockObj = new object();
    
    // Configure PDF options (will be reused for each conversion)
    LowCodePdfSaveOptions pdfOptions = ConfigurePdfOptions(true, false, false);
    
    // Process files in parallel
    Parallel.ForEach(excelFiles, 
        new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, 
        excelFile =>
    {
        string fileName = Path.GetFileNameWithoutExtension(excelFile);
        string outputFilePath = Path.Combine(outputDirectory, $"{fileName}.pdf");
        
        // Each thread needs its own copy of the options
        LowCodePdfSaveOptions threadPdfOptions = ConfigurePdfOptions(true, false, false);
        threadPdfOptions.OutputFile = outputFilePath;
        
        Console.WriteLine($"Converting: {fileName}");
        
        // Create load options
        LowCodeLoadOptions loadOptions = new LowCodeLoadOptions();
        loadOptions.InputFile = excelFile;
        
        try
        {
            // Process the conversion
            PdfConverter.Process(loadOptions, threadPdfOptions);
            
            lock (lockObj)
            {
                successCount++;
                Console.WriteLine($"Successfully converted: {fileName}");
            }
        }
        catch (Exception ex)
        {
            lock (lockObj)
            {
                failureCount++;
                Console.WriteLine($"Failed to convert {fileName}: {ex.Message}");
            }
        }
    });
    
    // Report summary
    Console.WriteLine("\n===== Conversion Summary =====");
    Console.WriteLine($"Total files processed: {excelFiles.Count}");
    Console.WriteLine($"Successfully converted: {successCount}");
    Console.WriteLine($"Failed conversions: {failureCount}");
}

Langkah 8: Contoh pelaksanaan lengkap

Berikut ialah contoh kerja lengkap yang menunjukkan keseluruhan proses penukaran batch:

using Aspose.Cells;
using Aspose.Cells.LowCode;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

namespace ExcelBatchConverter
{
    public class ExcelToPdfBatchConverter
    {
        private readonly string _inputDirectory;
        private readonly string _outputDirectory;
        private readonly string _logDirectory;
        
        public ExcelToPdfBatchConverter(string inputDirectory, string outputDirectory, string logDirectory)
        {
            _inputDirectory = inputDirectory;
            _outputDirectory = outputDirectory;
            _logDirectory = logDirectory;
            
            // Ensure directories exist
            Directory.CreateDirectory(_inputDirectory);
            Directory.CreateDirectory(_outputDirectory);
            Directory.CreateDirectory(_logDirectory);
        }
        
        // Log the conversion activity
        private void LogConversion(string message)
        {
            string logFilePath = Path.Combine(_logDirectory, $"ConversionLog_{DateTime.Now.ToString("yyyyMMdd")}.txt");
            string logEntry = $"[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}] {message}";
            
            try
            {
                File.AppendAllText(logFilePath, logEntry + Environment.NewLine);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Warning: Unable to write to log file: {ex.Message}");
            }
            
            Console.WriteLine(logEntry);
        }
        
        // Get all Excel files to process
        private List<string> GetExcelFilesToProcess(string searchPattern = "*.xlsx")
        {
            List<string> excelFiles = new List<string>();
            
            try
            {
                // Get all Excel files in the directory
                excelFiles.AddRange(Directory.GetFiles(_inputDirectory, "*.xlsx"));
                excelFiles.AddRange(Directory.GetFiles(_inputDirectory, "*.xls"));
                excelFiles.AddRange(Directory.GetFiles(_inputDirectory, "*.xlsm"));
                
                LogConversion($"Found {excelFiles.Count} Excel files to process.");
            }
            catch (Exception ex)
            {
                LogConversion($"Error searching for Excel files: {ex.Message}");
            }
            
            return excelFiles;
        }
        
        // Configure PDF conversion options
        private LowCodePdfSaveOptions ConfigurePdfOptions()
        {
            // Create PDF save options
            PdfSaveOptions pdfOpts = new PdfSaveOptions();
            
            // Set whether each worksheet should be rendered as a separate page
            pdfOpts.OnePagePerSheet = true;
            
            // Set additional PDF options
            pdfOpts.Compliance = PdfCompliance.PdfA1b; // For archival quality
            pdfOpts.AllColumnsInOnePagePerSheet = true;
            
            // Create low code PDF save options
            LowCodePdfSaveOptions lcsopts = new LowCodePdfSaveOptions();
            lcsopts.PdfOptions = pdfOpts;
            
            return lcsopts;
        }
        
        // Process all Excel files in the input directory
        public void ProcessAllFiles(bool useParallelProcessing = true)
        {
            LogConversion("Starting batch conversion process...");
            
            List<string> excelFiles = GetExcelFilesToProcess();
            
            if (excelFiles.Count == 0)
            {
                LogConversion("No Excel files found to process.");
                return;
            }
            
            // Conversion statistics
            int successCount = 0;
            int failureCount = 0;
            
            if (useParallelProcessing)
            {
                // For thread safety with parallel processing
                object lockObj = new object();
                
                // Process files in parallel
                Parallel.ForEach(excelFiles, 
                    new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, 
                    excelFile =>
                {
                    string fileName = Path.GetFileNameWithoutExtension(excelFile);
                    string outputFilePath = Path.Combine(_outputDirectory, $"{fileName}.pdf");
                    
                    try
                    {
                        // Create load options for this file
                        LowCodeLoadOptions loadOptions = new LowCodeLoadOptions();
                        loadOptions.InputFile = excelFile;
                        
                        // Configure PDF options for this file
                        LowCodePdfSaveOptions pdfOptions = ConfigurePdfOptions();
                        pdfOptions.OutputFile = outputFilePath;
                        
                        // Process the conversion
                        PdfConverter.Process(loadOptions, pdfOptions);
                        
                        lock (lockObj)
                        {
                            successCount++;
                            LogConversion($"Successfully converted: {fileName}");
                        }
                    }
                    catch (Exception ex)
                    {
                        lock (lockObj)
                        {
                            failureCount++;
                            LogConversion($"Failed to convert {fileName}: {ex.Message}");
                        }
                    }
                });
            }
            else
            {
                // Process files sequentially
                foreach (string excelFile in excelFiles)
                {
                    string fileName = Path.GetFileNameWithoutExtension(excelFile);
                    string outputFilePath = Path.Combine(_outputDirectory, $"{fileName}.pdf");
                    
                    try
                    {
                        // Create load options for this file
                        LowCodeLoadOptions loadOptions = new LowCodeLoadOptions();
                        loadOptions.InputFile = excelFile;
                        
                        // Configure PDF options for this file
                        LowCodePdfSaveOptions pdfOptions = ConfigurePdfOptions();
                        pdfOptions.OutputFile = outputFilePath;
                        
                        // Process the conversion
                        PdfConverter.Process(loadOptions, pdfOptions);
                        
                        successCount++;
                        LogConversion($"Successfully converted: {fileName}");
                    }
                    catch (Exception ex)
                    {
                        failureCount++;
                        LogConversion($"Failed to convert {fileName}: {ex.Message}");
                    }
                }
            }
            
            // Report summary
            LogConversion("\n===== Conversion Summary =====");
            LogConversion($"Total files processed: {excelFiles.Count}");
            LogConversion($"Successfully converted: {successCount}");
            LogConversion($"Failed conversions: {failureCount}");
            LogConversion("Batch conversion process completed.");
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            // Define directory paths
            string inputDirectory = @"C:\Reports\ExcelFiles";
            string outputDirectory = @"C:\Reports\PDFOutput";
            string logDirectory = @"C:\Reports\Logs";
            
            // Create and run the converter
            ExcelToPdfBatchConverter converter = new ExcelToPdfBatchConverter(
                inputDirectory, outputDirectory, logDirectory);
                
            // Process all files (using parallel processing)
            converter.ProcessAllFiles(true);
            
            Console.WriteLine("Process completed. Press any key to exit.");
            Console.ReadKey();
        }
    }
}

Penggunaan Kasus dan Permohonan

Sistem Laporan Perniagaan

Dalam sistem laporan kewangan, kitaran akhir bulan atau suku akhir sering memerlukan penukaran banyak laporan berasaskan Excel ke format PDF untuk didistribusikan kepada pihak berkepentingan. penyelesaian pengubahsuaian batch ini membolehkan pembangun laporan untuk mengautomatikkan proses, memastikan semua laporan ditukar dengan tetapan dan pemformatan yang konsisten, manakala secara dramatik mengurangkan usaha manual. laporan boleh secara automatik disimpan dalam format standard, menjadikannya lebih mudah untuk mendapatkan dan mematuhi.

Pemprosesan Data Jabatan

Para penganalisis perniagaan yang mengumpul data berasaskan Excel dari pelbagai jabatan boleh menggunakan penyelesaian ini untuk menyesuaikan dan mengarkibkan mesej.Dengan secara automatik menukar buku kerja yang diterima ke dalam PDF, mereka mencipta rekod data yang kekal sambil membuat maklumat yang boleh dikongsi dengan pihak berkepentingan yang tidak mempunyai Excel.Kemampuan pemprosesan batch bermakna walaupun bahagian-bahagian besar dengan beratus-ratus kitab kerja boleh dipraktikkan dengan cekap.

Proses pengurusan dokumen automatik

Integrasi dengan sistem pengurusan dokumen menjadi tidak mudah apabila laporan Excel secara automatik ditukar kepada PDF. Penyelesaian ini boleh dirancang untuk dijalankan sebagai sebahagian daripada aliran kerja yang lebih besar yang memuat naik fail Excel baru, menukarnya ke PDF, dan kemudian mengarahkan mereka ke repositori dokumen yang sesuai dengan metadata yang betul.

Tantangan dan Penyelesaian Bersama

Tantangan 1: Mengendalikan fail Excel dengan perlindungan kata laluan

** Penyelesaian:** Mengubah opsyen beban untuk termasuk pengendalian kata laluan:

// For password-protected Excel files
LowCodeLoadOptions loadOptions = new LowCodeLoadOptions();
loadOptions.InputFile = excelFile;
loadOptions.Password = "YourPassword"; // Supply the password

// Then proceed with conversion as normal
PdfConverter.Process(loadOptions, pdfOptions);

Tantangan 2: Mengekalkan Excel Format dalam output PDF

** Penyelesaian:** Pastikan opsyen PDF dikonfigurasikan dengan betul untuk mengekalkan pemformatan:

PdfSaveOptions pdfOpts = new PdfSaveOptions();
pdfOpts.OnePagePerSheet = true;
pdfOpts.PrintingPageType = PrintingPageType.ActualSize;
pdfOpts.DefaultFontName = "Arial"; // Specify a fallback font
pdfOpts.Compliance = PdfCompliance.PdfA1b; // For archival quality

Tantangan 3: Mengendalikan fail Excel yang sangat besar

** Penyelesaian:** Untuk fail yang sangat besar, melaksanakan pengoptimuman memori:

LowCodeLoadOptions loadOptions = new LowCodeLoadOptions();
loadOptions.InputFile = largeExcelFile;
loadOptions.MemorySetting = MemorySetting.MemoryPreference; // Optimize for memory usage

// Consider file-specific optimizations
PdfSaveOptions pdfOpts = new PdfSaveOptions();
pdfOpts.OptimizationType = OptimizationType.MinimumSize;

Pertimbangan prestasi

  • Untuk prestasi yang optimum dengan batch besar, gunakan pendekatan pemprosesan paralel dengan MaxDegreeOfParallelism Berdasarkan keupayaan pelayan anda
  • Pertimbangkan pemprosesan fail dalam set yang lebih kecil apabila berurusan dengan buku kerja Excel yang sangat besar untuk mengelakkan tekanan memori
  • Melaksanakan mekanisme pemantauan untuk memantau kemajuan penukaran dan penggunaan sumber
  • Untuk penyebaran pengeluaran, pertimbangkan untuk menjalankan proses penukaran pada pelayan khusus atau semasa jam off-peak

amalan terbaik

  • Pengesahan fail Excel sebelum pemprosesan batch untuk mengenal pasti masalah yang berpotensi
  • Mengimplementasikan pemprosesan ralat yang kukuh untuk memastikan proses tidak berhenti jika satu fail gagal
  • ** Mencipta log terperinci** proses penukaran untuk penyelesaian masalah dan audit
  • Mengatur PDF output dalam hierarki folder berstruktur untuk pengurusan yang lebih mudah
  • Setkan sistem pemantauan yang memberi amaran kepada pentadbir mengenai kegagalan penukaran
  • Ujian dengan pelbagai jenis fail Excel (XLSX, XLS dan XLSM) untuk memastikan keserasian

Senario lanjutan

Untuk keperluan yang lebih kompleks, pertimbangkan pelaksanaan lanjutan ini:

Senario 1: Nama PDF disesuaikan berdasarkan kandungan Excel Cell

Anda boleh mengekstrak nilai sel tertentu untuk digunakan dalam nama fail PDF:

// Advanced naming based on cell content
private string GetCustomPdfName(string excelFilePath)
{
    try
    {
        // Load the workbook
        Workbook workbook = new Workbook(excelFilePath);
        
        // Get report date from cell A1
        string reportDate = workbook.Worksheets[0].Cells["A1"].StringValue;
        
        // Get report type from cell B1
        string reportType = workbook.Worksheets[0].Cells["B1"].StringValue;
        
        // Create a custom name
        string customName = $"{reportType}_{reportDate}";
        
        // Sanitize the filename
        foreach (char invalidChar in Path.GetInvalidFileNameChars())
        {
            customName = customName.Replace(invalidChar, '_');
        }
        
        return customName + ".pdf";
    }
    catch
    {
        // Fallback to default naming if extraction fails
        return Path.GetFileNameWithoutExtension(excelFilePath) + ".pdf";
    }
}

Scenario 2 : Penukaran lembaran selektif

Menukar hanya lembaran tertentu daripada setiap fail Excel:

// Configure PDF options to convert only specific sheets
private LowCodePdfSaveOptions ConfigureSelectiveSheetsOptions(string[] sheetNames)
{
    PdfSaveOptions pdfOpts = new PdfSaveOptions();
    pdfOpts.OnePagePerSheet = true;
    
    // Create a worksheet name collection for selective conversion
    WorksheetCollection worksheets = new WorksheetCollection();
    foreach (string sheetName in sheetNames)
    {
        worksheets.Add(sheetName);
    }
    
    // Set sheet selection
    SheetOptions sheetOptions = new SheetOptions();
    sheetOptions.SheetNames = worksheets;
    pdfOpts.SheetOptions = sheetOptions;
    
    // Create low code PDF save options
    LowCodePdfSaveOptions lcsopts = new LowCodePdfSaveOptions();
    lcsopts.PdfOptions = pdfOpts;
    
    return lcsopts;
}

Conclusion

Dengan melaksanakan Aspose.Cells LowCode PDF Converter untuk pemprosesan batch, penganalisis perniagaan dan pembangun laporan boleh secara drastik mengurangkan masa yang dihabiskan pada manual Excel kepada penukaran PDF. Pendekatan ini secara signifikan meningkatkan produktiviti dan memastikan konsistensi di seluruh PDF yang dikeluarkan sambil mengekalkan kualiti dan pemformatan fail Excel asal. Penyelesaian ini boleh disesuaikan dari penggunaan jabatan kecil kepada sistem laporan korporat, dengan pilihan untuk penyesuaian untuk memenuhi keperluan perniagaan tertentu.

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

 Melayu