Làm thế nào để chuyển đổi Excel file sang PDF trong .NET

Làm thế nào để chuyển đổi Excel file sang PDF trong .NET

Bài viết này cho thấy làm thế nào để chuyển đổi nhiều tệp Excel sang PDF bằng cách sử dụng Aspose.Cells LowCode PDF Converter trong các ứng dụng .NET. Tác giả định dạng PDF cung cấp một cách tiếp cận nhanh chóng với việc chuyển hóa tài liệu mà không yêu cầu mã hóa rộng rãi hoặc kiến thức sâu sắc về các cấu trúc nội bộ của Excel - hoàn hảo cho các nhà phân tích kinh doanh và nhà phát triển báo cáo những người cần tự động hóa dòng công việc Báo cáo của họ.

Vấn đề thế giới thực

Trong môi trường doanh nghiệp, các nhóm báo cáo thường cần chuyển đổi hàng chục hoặc thậm chí hàng trăm sổ làm việc Excel sang định dạng PDF một cách thường xuyên. làm điều này bằng tay là mất thời gian, sai lầm, và tách rời các tài nguyên có giá trị từ các nhiệm vụ phân tích quan trọng hơn. Ngoài ra, đảm bảo định hình và bố trí liên tục trên tất cả các Báo cáo là khó khăn khi chuyển hóa tệp cá nhân.

Giải pháp Overview

Sử dụng Aspose.Cells LowCode PDF Converter, chúng tôi có thể giải quyết thách thức này một cách hiệu quả với mã tối thiểu. Giải pháp này là lý tưởng cho các nhà phân tích kinh doanh và nhà phát triển báo cáo những người cần làm đơn giản hóa các quá trình báo chí của họ, đảm bảo sự nhất quán giữa các tài liệu, và tiết kiệm thời gian cho công việc có giá trị hơn. Cách tiếp cận của chúng ta sẽ tập trung vào việc tạo ra một hệ thống xử lý bìa mạnh mẽ có khả năng quản lý khối lượng lớn các tệp Excel với cài đặt chuyển đổi tùy chỉnh.

Nguyên tắc

Trước khi thực hiện giải pháp, hãy chắc chắn rằng bạn có:

  • Visual Studio 2019 hoặc hơn
  • .NET 6.0 hoặc mới hơn (tương thích với .Net Framework 4.6.2+)
  • Aspose.Cells cho gói .NET được cài đặt thông qua NuGet
  • Sự hiểu biết cơ bản về lập trình C#
PM> Install-Package Aspose.Cells

Chế độ thực hiện từng bước

Bước 1: Cài đặt và cấu hình Aspose.Cells

Thêm gói Aspose.Cells vào dự án của bạn và bao gồm các không gian tên cần thiết:

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

Bước 2: Tạo cấu trúc thư mục cho việc xử lý Batch

Thiết lập một cấu trúc thư mục để tổ chức các tệp Excel nhập và xuất PDF của bạn:

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

Bước 3: Thực hiện File Discovery Logic

Tạo một phương pháp để khám phá tất cả các tệp Excel cần được chuyển đổi:

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

Bước 4: Thiết lập các tùy chọn PDF Converter

Tạo một phương pháp để thiết lập các tùy chọn chuyển đổi PDF cho kết quả nhất quán:

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

Bước 5: Thực hiện logic chuyển đổi tệp duy nhất

Tạo một phương pháp để chuyển đổi một tập tin Excel duy nhất sang 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;
    }
}

Bước 6: Thực hiện Batch Processing Logic

Bây giờ tạo phương pháp chính sẽ xử lý nhiều tệp:

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

Bước 7: Thực hiện xử lý song song cho hiệu suất tốt hơn

Đối với các gói lớn, thực hiện xử lý song song để tăng tốc chuyển đổi:

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

Bước 8: Hiển thị hoàn chỉnh

Dưới đây là một ví dụ hoàn chỉnh làm việc cho thấy toàn bộ quá trình chuyển đổi gói:

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

Sử dụng trường hợp và ứng dụng

Hệ thống báo cáo doanh nghiệp

Trong các hệ thống báo cáo tài chính, chu kỳ cuối tháng hoặc cuối quý thường yêu cầu chuyển đổi nhiều báo chí dựa trên Excel sang định dạng PDF để được phân phối cho các bên liên quan. Giải pháp biến đổi gói này cho phép các nhà phát triển báo giá tự động hóa quá trình, đảm bảo tất cả các báo thức được chuyển sang với cài đặt và định hình nhất quán, trong khi giảm đáng kể nỗ lực thủ công. Báo cáo có thể được lưu trữ một cách automatically trong một format tiêu chuẩn, làm cho việc thu hồi và tuân thủ dễ dàng hơn.

Bộ xử lý dữ liệu

Các nhà phân tích kinh doanh thu thập dữ liệu dựa trên Excel từ nhiều bộ phận có thể sử dụng giải pháp này để tiêu chuẩn hóa và lưu trữ các bài đăng.Bằng cách tự động chuyển đổi sổ làm việc nhận được sang PDF, họ tạo ra một hồ sơ vĩnh viễn của những bài viết trong khi làm cho thông tin được chia sẻ với các bên liên quan không có Excel.

Quản lý tài liệu tự động Workflows

Việc tích hợp với các hệ thống quản lý tài liệu trở nên vô hiệu khi các báo cáo Excel tự động được chuyển đổi sang PDF. Giải pháp này có thể được lên kế hoạch để chạy như là một phần của một dòng công việc lớn hơn mà thu thập các tập tin Excel mới, biến chúng thành PDF, và sau đó hướng dẫn chúng đến các lưu trữ văn bản thích ứng với metadata phù hợp.

Những thách thức và giải pháp chung

Thách thức 1: xử lý các tệp Excel với bảo vệ mật khẩu

** Giải pháp:** Thay đổi các tùy chọn tải để bao gồm xử lý mật khẩu:

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

Thách thức 2: Giữ định dạng Excel trong PDF Output

** Giải pháp:** Hãy chắc chắn rằng các tùy chọn PDF được cấu hình đúng cách để giữ định dạng:

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

Thách thức 3: xử lý các tệp Excel rất lớn

** Giải pháp:** Đối với các tệp cực kỳ lớn, thực hiện tối ưu hóa bộ nhớ:

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;

Các tính toán hiệu suất

  • Để có hiệu suất tối ưu với các gói lớn, hãy sử dụng phương pháp xử lý song song với một cách hợp lý MaxDegreeOfParallelism dựa trên khả năng của máy chủ của bạn
  • Hãy xem xét việc xử lý các tập tin trong các gói nhỏ hơn khi đối phó với sổ làm việc Excel rất lớn để tránh áp lực bộ nhớ
  • Thực hiện một cơ chế giám sát để theo dõi tiến bộ chuyển đổi và sử dụng tài nguyên
  • Đối với việc triển khai sản xuất, hãy xem xét việc chạy quá trình chuyển đổi trên một máy chủ dành riêng hoặc trong các giờ off-peak.

Thực hành tốt nhất

  • Tự xác nhận tệp Excel trước khi xử lý tập hợp để xác định các vấn đề tiềm năng
  • Hành động xử lý lỗi mạnh mẽ để đảm bảo rằng quá trình không dừng lại nếu một tệp thất bại
  • Tạo hồ sơ chi tiết của quá trình chuyển đổi để giải quyết vấn đề và kiểm toán
  • *Hành trình PDF xuất trong một thư mục cấu trúc để quản lý dễ dàng hơn
  • Cài đặt một hệ thống giám sát để cảnh báo người quản trị về sự cố chuyển đổi
    • Kiểm tra với các loại tệp Excel khác nhau (XLSX, XLS và XLSM) để đảm bảo sự tương thích

kịch bản tiên tiến

Đối với các yêu cầu phức tạp hơn, hãy xem xét các ứng dụng tiên tiến này:

Kịch bản 1: Tên PDF tùy chỉnh dựa trên nội dung Excel Cell

Bạn có thể rút các giá trị tế bào cụ thể để sử dụng trong tên tệp 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";
    }
}

Kịch bản 2: Selective Sheet Conversion

Chuyển đổi chỉ các bảng cụ thể từ mỗi tệp 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;
}

Kết luận

Bằng cách triển khai Aspose.Cells LowCode PDF Converter cho việc xử lý hàng loạt, các nhà phân tích kinh doanh và nhà phát triển báo cáo có thể giảm đáng kể thời gian dành cho trình điều khiển Excel sang chuyển đổi PDF. Cách tiếp cận này cải thiện hiệu quả và đảm bảo sự nhất quán trên tất cả các tập tin PDF được tạo trong khi duy trì chất lượng và định dạng của các tệp Excel ban đầu. Giải pháp được quy mô từ việc sử dụng một bộ phận nhỏ đến các hệ thống Báo cáo toàn bộ doanh nghiệp, với các tùy chọn tùy chỉnh để đáp ứng các yêu cầu kinh tế cụ thể.

Để biết thêm thông tin và các ví dụ bổ sung, hãy tham khảo Hướng dẫn sử dụng Aspose.Cells.LowCode API .

 Tiếng Việt