Cara mengkonversi file Excel ke PDF dalam .NET

Cara mengkonversi file Excel ke PDF dalam .NET

Artikel ini menunjukkan bagaimana untuk menggabungkan konversi berbilang file Excel ke PDF menggunakan Aspose.Cells LowCode PDF Converter dalam aplikasi .NET. Konversi PDF menyediakan pendekatan yang lancar untuk konversi dokumen tanpa memerlukan pengekodan yang luas atau pengetahuan yang mendalam tentang struktur internal Excel - sempurna untuk penganalisis bisnis dan pengembang laporan yang perlu mengautomatikkan aliran kerja laporan mereka.

Masalah dunia nyata

Dalam lingkungan bisnis, tim melaporkan sering perlu mengkonversi puluhan atau bahkan ratusan buku kerja Excel ke format PDF secara teratur. Melakukannya secara manual adalah waktu yang memakan waktu, error-prone, dan memisahkan sumber daya berharga dari tugas analisis yang lebih penting.

Penyelesaian Overview

Dengan menggunakan Aspose.Cells LowCode PDF Converter, kami dapat menyelesaikan tantangan ini dengan efisien dengan kode minimum. Solusi ini ideal untuk penganalisis bisnis dan pengembang laporan yang perlu menyederhanakan proses laporan mereka, memastikan konsistensi di antara dokumen, dan membebaskan waktu untuk kerja yang lebih berharga. Pendekatan kami akan fokus pada menciptakan sistem pemrosesan batch yang kuat yang dapat menangani volume besar file Excel dengan pengaturan konversi tersuai.

Persyaratan

Sebelum menerapkan solusi, pastikan Anda memiliki:

  • Visual Studio 2019 atau lebih baru
  • .NET 6.0 atau lebih baru (kompatibel dengan .Net Framework 4.6.2+)
  • Aspose.Cells untuk paket .NET yang diinstal melalui NuGet
  • Pemahaman dasar tentang program C#
PM> Install-Package Aspose.Cells

Implementasi langkah demi langkah

Langkah 1: Menginstal dan mengkonfigurasi Aspose.Cells

Tambah paket Aspose.Cells ke proyek Anda dan mencakup 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: Membuat struktur direktori untuk pemrosesan batch

Tetapkan struktur direktori untuk mengatur file input Excel dan file 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: Mengimplementasikan File Discovery Logic

Buat metode untuk menemukan semua file Excel yang perlu dikonversi:

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: Mengkonfigurasi PDF Converter Opsi

Buat metode untuk mengatur opsi konversi PDF untuk output 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 Logika Konversi File tunggal

Mencipta metode untuk mengkonversi satu file Excel ke 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: Implementasi Batch Processing Logic

Sekarang buat metode utama yang akan memproses beberapa file:

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 pemrosesan paralel untuk kinerja yang lebih baik

Untuk batch besar, melaksanakan pemrosesan paralel untuk mempercepat konversi:

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 implementasi lengkap

Berikut adalah contoh kerja lengkap yang menunjukkan seluruh proses konversi 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();
        }
    }
}

Menggunakan kasus dan aplikasi

Sistem Laporan Enterprise

Dalam sistem laporan keuangan, siklus akhir bulan atau suku akhir sering membutuhkan konversi banyak laporan berbasis Excel ke format PDF untuk didistribusikan kepada pihak berkepentingan. Solusi penukaran batch ini memungkinkan pengembang laporan untuk mengautomatikkan proses, memastikan semua laporan dikonversi dengan tetapan konsisten dan pemformatan, sementara secara dramatis mengurangi upaya manual.

Pemrosesan Data Departemen

Analis bisnis yang mengumpulkan data berbasis Excel dari beberapa departemen dapat menggunakan solusi ini untuk mengstandardisasi dan mengarkibkan presentasi.Dengan secara otomatis mengkonversi buku kerja yang diterima ke PDF, mereka membuat catatan permanen dari presentasinya sambil membuat informasi yang dapat dibagikan dengan pihak berkepentingan yang tidak memiliki Excel.Kemampuan pemrosesan paket berarti bahkan jabatan besar dengan ratusan liburan kerja dapat diproses dengan efisien.

Proses Manajemen Dokumen Automatik

Integrasi dengan sistem manajemen dokumen menjadi tidak mudah ketika laporan Excel secara otomatis diubah menjadi PDF. Solusi ini dapat dirancang untuk berjalan sebagai bagian dari aliran kerja yang lebih besar yang mengumpulkan file Excel baru, mengkonversi ke PDF, dan kemudian mengarahkan mereka ke repositori dokumen yang sesuai dengan metadata yang tepat.

Tantangan dan Solusi Umum

Tantangan 1: Mengendalikan file Excel dengan perlindungan kata sandi

** Solusi:** Mengubah opsi beban untuk mencakup pengendalian kata sandi:

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

** Solusi:** Pastikan opsi PDF terkonfigurasi dengan benar untuk mempertahankan format:

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 file Excel yang sangat besar

** Solusi:** Untuk file yang sangat besar, lakukan 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 kinerja

  • Untuk kinerja yang optimal dengan batch besar, gunakan pendekatan pemrosesan paralel dengan cara yang wajar. MaxDegreeOfParallelism Berdasarkan kemampuan server Anda
  • Pertimbangkan memproses file dalam paket yang lebih kecil ketika berurusan dengan buku kerja Excel yang sangat besar untuk menghindari tekanan memori
  • Mengimplementasikan mekanisme pemantauan untuk memantau kemajuan konversi dan penggunaan sumber daya
  • Untuk penyebaran produksi, pertimbangkan untuk menjalankan proses konversi pada server khusus atau selama jam off-peak

Praktik Terbaik

  • Mengesahkan file Excel sebelumnya sebelum proses batch untuk mengidentifikasi masalah potensial
  • Mengimplementasikan pengendalian kesalahan yang kuat untuk memastikan proses tidak berhenti jika satu file gagal
  • Membuat log terperinci dari proses konversi untuk penyelesaian masalah dan audit
  • Mengatur output PDF dalam hierarki folder terstruktur untuk pengelolaan yang lebih mudah
  • Mengatur sistem pemantauan yang memberi peringatan kepada administrator tentang kegagalan konversi
  • Test dengan berbagai jenis file Excel (XLSX, XLS,XLSM) untuk memastikan kompatibilitas

Skenario Lanjutan

Untuk keperluan yang lebih kompleks, pertimbangkan implementasi lanjutan ini:

Skenario 1: Nama PDF tersuai berdasarkan konten Excel Cell

Anda dapat mengekstrak nilai sel tertentu untuk digunakan dalam nama file 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";
    }
}

Skenario 2: Selective Sheet Conversion

Konversi hanya lembar tertentu dari setiap file 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;
}

Kesimpulan

Dengan menerapkan Aspose.Cells LowCode PDF Converter untuk pemrosesan batch, analis bisnis dan pengembang laporan dapat secara dramatis mengurangi waktu yang dihabiskan pada manual Excel ke konversi PDF. Pendekatan ini secara signifikan meningkatkan produktivitas dan menjamin konsistensi di seluruh PDF yang diciptakan sambil mempertahankan kualitas dan pemformatan file Excel asli. Solusi ini dapat disesuaikan dari penggunaan departemen kecil ke sistem laporan perusahaan, dengan opsi penyesuaian untuk memenuhi persyaratan bisnis tertentu.

Untuk informasi lebih lanjut dan contoh tambahan, lihat Spesifikasi Aspose.Cells.LowCode API .

 Indonesia