如何在 .NET 中将 Excel 文件转换为 PDF

如何在 .NET 中将 Excel 文件转换为 PDF

本文展示了如何将多个 Excel 文件转换为 PDF 使用 Aspose.Cells LowCode PDF Converter 在 .NET 应用程序中。 该 PDF converter 提供了一个顺利的方法,以文档转型,而不需要广泛编码或深入了解 Excel 的内部结构 - 适合企业分析师和报告开发人员谁需要自动化他们的报告工作流。

现实世界问题

在企业环境中,报告团队经常需要定期将数十个或甚至数百个Excel工作簿转换为PDF格式,手动做到这一点是浪费时间、错误的,并将有价值的资源从更重要的分析任务中分开。

解决方案概述

使用 Aspose.Cells LowCode PDF Converter,我们可以以最小的代码有效地解决这个挑战。 这个解决方案是理想的企业分析师和报告开发人员谁需要简化他们的报告过程,确保文件的一致性,并为更有价值的工作节省时间。

原則

在实施解决方案之前,请确保您有:

  • Visual Studio 2019 或以后
  • .NET 6.0 或更高版本(兼容 .Net Framework 4.6.2+)
  • 通过 NuGet 安装的 .NET 包的 Aspose.Cells
  • C#编程的基本理解
PM> Install-Package Aspose.Cells

步骤实施

步骤1:安装和设置 Aspose.Cells

将 Aspose.Cells 包添加到您的项目中,并包含所需的名称空间:

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

步骤2:创建集合处理的目录结构

设置一个目录结构,以组织您的输入 Excel 文件和输出 PDF 文档:

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

步骤3:实施文件发现逻辑

创建一个方法,以查找需要转换的所有 Excel 文件:

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

步骤4:设置 PDF 转换器选项

创建一个方法来设置 PDF 转换选项,以便连续输出:

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

步骤5:实施单个文件转换逻辑

创建一个方法来将单个 Excel 文件转换为 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;
    }
}

步骤6:实施包处理逻辑

现在创建将处理多个文件的主要方法:

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

步骤7:实施平行处理,以提高性能

对于大套件,执行平行处理,以加快转换:

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

步骤8:完整实施示例

下面是一个完整的工作例子,展示了整个集合转换过程:

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

使用案例和应用程序

企业报告系统

在财务报告系统中,月末或季度周期往往需要将许多基于Excel的报告转换为PDF格式,以便向利益相关者分发。 此包转型解决方案允许报告开发人员自动化过程,确保所有报告均以一致的设置和格制格换,同时显著减少手动努力。

部门数据处理

从多个部门收集基于Excel的数据的企业分析师可以使用这个解决方案来标准化和存档提交。 通过自动将收到的工作簿转换为PDF,他们创建了一个永久记录数据提议,同时使信息与没有Expl 的利益相关者共享。

自动文件管理工作流

与文档管理系统的整合变得无缝,当Excel报告自动转换为PDF时,这个解决方案可以计划作为一个更大的工作流的一部分运行,将新 Excel 文件编辑到PDF,然后将其导向到适当的文件存储库,配有相应的代数据。

共同挑战与解决方案

挑战1:使用密码保护处理 Excel 文件

** 解決方案:** 改變充電選項以包含密碼處理:

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

挑战2:在 PDF 输出中保持 Excel 格式化

** 解决方案:** 确保 PDF 选项正确配置以保存格式化:

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

挑战3:处理非常大的Excel文件

**解决方案:**对于非常大的文件,实施内存优化:

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;

绩效考虑

  • 为了在大型集合中获得最佳性能,使用平行处理方法,以合理的方式进行处理。 MaxDegreeOfParallelism 基于您的服务器的能力
  • 在处理非常大的Excel工作簿时考虑处理小组的文件,以避免内存压力
  • 实施监测机制,以跟踪转换进展和资源利用
  • 对于生产部署,请考虑在专门的服务器上运行转换过程,或者在超级时间内

最佳实践

  • ** 提前验证 Excel 文件** 在包处理之前,以识别潜在问题
  • 实施强大的错误处理,以确保一个文件故障时不会停止处理
  • ** 创建转换过程的详细日志** 解决问题和审计
  • 组织输出PDF在结构化文件夹的序列,以便更容易管理
  • 设置监控系统,警告管理员的转换故障
  • ** 使用不同 Excel 文件类型(XLSX、XLS、 XLSM)进行测试,以确保兼容性

先进的场景

对于更复杂的要求,请考虑这些先进的实施:

场景1:基于 Excel 单元格内容的自定义 PDF 名称

您可以在 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";
    }
}

场景2:选择性表格转换

从每个 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;
}

结论

通过实施 Aspose.Cells LowCode PDF Converter for batch processing,业务分析师和报告开发人员可以显著减少在手动 Excel 转换到 PDF 的时间。 这种方法大大提高了生产力,并确保了所有创建的 PDF 之间的一致性,同时保持了原始Excel 文件的质量和格式化。

要了解更多信息和更多例子,请参阅 Aspose.Cells.LowCode API 参考 .

 中文