.NET で Excel ファイルを PDF に変換する方法
この記事では、Aspose.Cells LowCode PDF Converter を使用して複数の Excel ファイルを PDF に変換する方法を示しています .NET アプリケーションで PDF カバーは、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 に変換することによって、データの提出の永続的な記録を作成しながら、情報をExcel を持たない関係者と共有することができます。
自動ドキュメント管理ワークフロー
ドキュメント管理システムとの統合は、Excel レポートが自動的に PDF に変換されるときに不安定になります. このソリューションは新しい Excel ファイルをアップグレードし、PDF でコンバータするより大きなワークフローの一環として実行する予定となり、それらを適切なメタデータを備えた関連する文書レポジトリにリダイレクトします. 一貫したフォーマットおよびアーカイブ品質の 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 Cell コンテンツに基づくカスタマイズされた 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, business analysts and report developers can dramatically reduce the time spent on manual Excel to PDF conversions. This approach significantly improves productivity and ensures consistency across all generated PDFs whileining the quality and formatting of the original Excel files. The solution is scalable from small departmental use to enterprise-wide reporting systems, with options for customization to meet specific business requirements. このアプローチは生成されたすべてのPDFの生産性を大幅に改善し、オリジナルのExcelファイルの品質とフォーマットを維持します。
詳しい情報や追加の例を参照してください。 Aspose.Cells.LowCode API リファレンス .