Excel ワークシートを .NET で PDF に変換する方法

Excel ワークシートを .NET で PDF に変換する方法

この記事では、Aspose.Cells LowCode PDF Converter を使用してページごとに 1 ページの PDF ファイルを変換する方法を示しています .NET アプリケーション。

現実世界問題

金融アナリストは多くの場合、複数の表のExcel金融モデルを標準化されたPDFレポートに変換する必要があり、それぞれのワークシートがより簡単なレビューと印刷のために自分のページに表示されます。伝統的なコンバージョン方法は、継続的なページのすべてのデータを組み合わせるか、または各ページを手動で処理する必要があります。

ソリューション概要

Aspose.Cells LowCode PDF Converter を使用すると、この課題を最小限のコードで効率的に解決することができます このソリューションは、専門の PDF レポートを生成する必要がある財務専門家、報告開発者、およびビジネスアナリストに最適です。

原則

解決策を実施する前に、あなたが持っていることを確認してください:

  • 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 Aspose.Cells.Rendering;
using System;
using System.IO;

ステップ2:入力データの準備

この例では、既存のExcelファイルを使用します. ソースファイルには、PDFで別々のページに変換したい複数のワークシートが含まれていることを確認してください:

// Define the path to your Excel file
string excelFilePath = "financial-report-template.xlsx";

// Ensure the file exists
if (!File.Exists(excelFilePath))
{
    throw new FileNotFoundException("The specified Excel file was not found.", excelFilePath);
}

// Create output directory if it doesn't exist
string outputDirectory = "result";
if (!Directory.Exists(outputDirectory))
{
    Directory.CreateDirectory(outputDirectory);
}

ステップ3:PDFコンバーターのオプションを設定する

PDF Converter プロセスのオプションを設定し、1 ページごとに設定を指定します。

// Create the LowCode load options for the source file
LowCodeLoadOptions loadOptions = new LowCodeLoadOptions();
loadOptions.InputFile = excelFilePath;

// Create the LowCode PDF save options
LowCodePdfSaveOptions pdfSaveOptions = new LowCodePdfSaveOptions();

// Configure PDF-specific settings
PdfSaveOptions pdfOptions = new PdfSaveOptions();
pdfOptions.OnePagePerSheet = true;  // This is the key setting for our requirement

// Optionally set additional PDF options
pdfOptions.Compliance = PdfCompliance.PdfA1b;  // For archival compliance if needed
pdfOptions.AllColumnsInOnePagePerSheet = true; // Ensure all columns fit on one page

// Apply the PDF options to our save options
pdfSaveOptions.PdfOptions = pdfOptions;

// Set the output file path
string outputFilePath = Path.Combine(outputDirectory, "FinancialReport.pdf");
pdfSaveOptions.OutputFile = outputFilePath;

ステップ4:PDF変換プロセスを実行する

設定されたオプションで PDF Converter 作業を実行します:

try
{
    // Process the conversion using the LowCode PDF Converter
    PdfConverter.Process(loadOptions, pdfSaveOptions);
    
    Console.WriteLine($"Conversion completed successfully. PDF saved to: {outputFilePath}");
}
catch (Exception ex)
{
    Console.WriteLine($"Error during conversion: {ex.Message}");
    // Log the exception or handle it according to your application's requirements
}

ステップ5:出力処理

変換後、PDFを開くか、さらに処理したいかもしれません。

// Check if the output file was created
if (File.Exists(outputFilePath))
{
    // Open the file using the default PDF viewer (optional)
    try
    {
        System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
        {
            FileName = outputFilePath,
            UseShellExecute = true
        });
    }
    catch (Exception ex)
    {
        Console.WriteLine($"The file was created but could not be opened: {ex.Message}");
    }
}
else
{
    Console.WriteLine("The output file was not created.");
}

ステップ6:エラー処理の実施

強力な操作を確保するために、適切なエラー処理を追加します:

try
{
    // Create the load options
    LowCodeLoadOptions loadOptions = new LowCodeLoadOptions();
    
    // Verify input file exists before assigning
    if (!File.Exists(excelFilePath))
    {
        throw new FileNotFoundException("Input Excel file not found", excelFilePath);
    }
    
    loadOptions.InputFile = excelFilePath;
    
    // Create and configure PDF save options
    LowCodePdfSaveOptions pdfSaveOptions = new LowCodePdfSaveOptions();
    PdfSaveOptions pdfOptions = new PdfSaveOptions();
    pdfOptions.OnePagePerSheet = true;
    pdfSaveOptions.PdfOptions = pdfOptions;
    pdfSaveOptions.OutputFile = outputFilePath;
    
    // Execute conversion
    PdfConverter.Process(loadOptions, pdfSaveOptions);
    
    // Verify output was created
    if (!File.Exists(outputFilePath))
    {
        throw new Exception("PDF conversion completed but output file was not created");
    }
    
    Console.WriteLine("Conversion successful!");
}
catch (CellsException cellsEx)
{
    // Handle Aspose.Cells specific exceptions
    Console.WriteLine($"Aspose.Cells error: {cellsEx.Message}");
    // Consider logging the exception or custom handling based on cellsEx.Code
}
catch (IOException ioEx)
{
    // Handle file IO exceptions
    Console.WriteLine($"File operation error: {ioEx.Message}");
}
catch (Exception ex)
{
    // Handle other exceptions
    Console.WriteLine($"General error: {ex.Message}");
}

ステップ7:パフォーマンスの最適化

生産環境のためのこれらの最適化テクニックを検討する:

  • MemoryStream を使用して高容量処理:
// For high-volume processing, using memory streams can be more efficient
using (MemoryStream outputStream = new MemoryStream())
{
    // Configure save options to use memory stream
    LowCodePdfSaveOptions pdfSaveOptions = new LowCodePdfSaveOptions();
    pdfSaveOptions.OutputStream = outputStream;
    pdfSaveOptions.PdfOptions = new PdfSaveOptions { OnePagePerSheet = true };
    
    // Process the conversion
    PdfConverter.Process(loadOptions, pdfSaveOptions);
    
    // Now you can use the stream as needed (save to file, send via network, etc.)
    outputStream.Position = 0;
    using (FileStream fileStream = File.Create(outputFilePath))
    {
        outputStream.CopyTo(fileStream);
    }
}
  • バッチ処理には、可能な限りオブジェクトを再利用する:
// Create PDF options once and reuse
PdfSaveOptions pdfOptions = new PdfSaveOptions { OnePagePerSheet = true };

// Process multiple files
foreach (string excelFile in Directory.GetFiles("input-directory", "*.xlsx"))
{
    LowCodeLoadOptions loadOptions = new LowCodeLoadOptions { InputFile = excelFile };
    LowCodePdfSaveOptions saveOptions = new LowCodePdfSaveOptions
    {
        PdfOptions = pdfOptions,
        OutputFile = Path.Combine("output-directory", Path.GetFileNameWithoutExtension(excelFile) + ".pdf")
    };
    
    PdfConverter.Process(loadOptions, saveOptions);
}

ステップ8:完璧な実施例

以下は、プロセス全体を示す完全な作業例です。

using Aspose.Cells;
using Aspose.Cells.LowCode;
using Aspose.Cells.Rendering;
using System;
using System.IO;

namespace ExcelToPdfConverter
{
    class Program
    {
        static void Main(string[] args)
        {
            // Define input and output paths
            string inputDirectory = "input-files";
            string outputDirectory = "result";
            string excelFilePath = Path.Combine(inputDirectory, "financial-report.xlsx");
            
            // Ensure directories exist
            Directory.CreateDirectory(outputDirectory);
            
            try
            {
                Console.WriteLine($"Converting {excelFilePath} to PDF...");
                
                // Simple one-line approach (less customization)
                string quickOutputPath = Path.Combine(outputDirectory, "QuickOutput.pdf");
                PdfConverter.Process(excelFilePath, quickOutputPath);
                Console.WriteLine($"Basic conversion completed: {quickOutputPath}");
                
                // Advanced approach with custom options
                // Setup load options
                LowCodeLoadOptions loadOptions = new LowCodeLoadOptions
                {
                    InputFile = excelFilePath
                };
                
                // Setup PDF save options with specific settings
                LowCodePdfSaveOptions pdfSaveOptions = new LowCodePdfSaveOptions();
                PdfSaveOptions pdfOptions = new PdfSaveOptions
                {
                    OnePagePerSheet = true,
                    Compliance = PdfCompliance.PdfA1b,
                    PrintingPageType = PrintingPageType.ActualSize
                };
                pdfSaveOptions.PdfOptions = pdfOptions;
                
                string customOutputPath = Path.Combine(outputDirectory, "CustomOutput.pdf");
                pdfSaveOptions.OutputFile = customOutputPath;
                
                // Execute the conversion
                PdfConverter.Process(loadOptions, pdfSaveOptions);
                Console.WriteLine($"Advanced conversion completed: {customOutputPath}");
                
                // Batch processing example
                BatchProcessExcelFiles(inputDirectory, outputDirectory);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
            
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
        
        static void BatchProcessExcelFiles(string inputDir, string outputDir)
        {
            // Get all Excel files
            string[] excelFiles = Directory.GetFiles(inputDir, "*.xlsx");
            
            if (excelFiles.Length == 0)
            {
                Console.WriteLine("No Excel files found for batch processing.");
                return;
            }
            
            // Create reusable PDF options
            PdfSaveOptions pdfOptions = new PdfSaveOptions
            {
                OnePagePerSheet = true
            };
            
            Console.WriteLine($"Batch processing {excelFiles.Length} files...");
            
            foreach (string file in excelFiles)
            {
                try
                {
                    string fileName = Path.GetFileNameWithoutExtension(file);
                    string outputPath = Path.Combine(outputDir, $"{fileName}.pdf");
                    
                    // Configure options
                    LowCodeLoadOptions loadOptions = new LowCodeLoadOptions
                    {
                        InputFile = file
                    };
                    
                    LowCodePdfSaveOptions saveOptions = new LowCodePdfSaveOptions
                    {
                        PdfOptions = pdfOptions,
                        OutputFile = outputPath
                    };
                    
                    // Process conversion
                    PdfConverter.Process(loadOptions, saveOptions);
                    Console.WriteLine($"Converted: {Path.GetFileName(file)} -> {Path.GetFileName(outputPath)}");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error processing {Path.GetFileName(file)}: {ex.Message}");
                }
            }
            
            Console.WriteLine("Batch processing completed.");
        }
    }
}

ケースとアプリケーションの使用

企業報告システム

金融機関は、Excelデータモデルから標準化されたPDFレポートの生成を自動化することができます. 各ワークシートには、さまざまな金融メトリック(バランス表、収入報告、現金流の予測)が表示され、データの明確な分離を維持し、すべてのレポーターを通じて一貫したフォーマットを確保します. これは、理事会のメンバー、監査官、規制審査員の読みやすさを向上させます。

規制遵守文書世代

規制当局に標準化された財務または運用データを提出しなければならない組織は、Excelベースのデータが適切なPDFフォーマットに変換することができる。1ページごとにオプションが、各法定フォームまたはデータセットが電子または印刷で提出されるときにその誠実さと正しい配置を維持することを保証し、格式のエラーによる遵守リスクを減らす。

自動レポート配布システム

セールスまたはオペレーティング部門は、Excelデータが定期的にプロのPDFに変換され、顧客や内部の関係者に配布される自動化されたシステムを実施することができます。一ページ一覧のフォーマットでは、受信者がそれぞれのビジネスユニット、製品ライン、または時間期間がより簡単なナビゲーションと分析のために自分のページに表示される、よく構築された文書を受け取ることを保証します。

共通の課題と解決策

課題1 : 大型ワークシートがページの境界線を超える

ソリューション: PDF オプションを調整して、スケール設定を変更して大きなワークシートを処理します。

PdfSaveOptions pdfOptions = new PdfSaveOptions();
pdfOptions.OnePagePerSheet = true;
pdfOptions.AllColumnsInOnePagePerSheet = false; // Let large sheets span multiple pages horizontally
pdfOptions.WidthFitToPagesCount = 2; // Allow up to 2 pages for width if needed

課題2:PDFに表示されないカスタマイズヘッドとフォーター

ソリューション: PDF エクスポートにカスタマイズされたヘッドと足を導入する:

PdfSaveOptions pdfOptions = new PdfSaveOptions();
pdfOptions.OnePagePerSheet = true;

// Add custom header and footer
pdfOptions.IsCustomPrintAreaSet = true;
pdfOptions.CustomPrintPageTopMargin = 50;
pdfOptions.CustomPrintPageBottomMargin = 50;
pdfOptions.HeaderFooterManager.SetHeader(HeaderFooterType.FirstPage, "Company Financial Report");
pdfOptions.HeaderFooterManager.SetFooter(HeaderFooterType.AllPages, "&P of &N");

チャレンジ3:画像とグラフがPDFで不適切にランダーする

ソリューション: この設定で画像とグラフの品質を向上させる:

PdfSaveOptions pdfOptions = new PdfSaveOptions();
pdfOptions.OnePagePerSheet = true;
pdfOptions.Quality = 100; // Highest quality setting
pdfOptions.DefaultEditLanguage = EditLanguage.Default; // Proper text rendering
pdfOptions.CheckFontCompatibility = true; // Ensure fonts are compatible

パフォーマンス考慮

  • マルチシートワークブックの場合、プロセスはメモリインテンツであり得る; メンテナンス制限されたシステムでパラレルではなく、連続的にファイルを処理することを検討します。
  • 大型 Excel ファイルを変換する際には、ストリーミングアプローチを使用してメモリの使用量を減らします。
  • 異なる設定で同じファイルを繰り返し変換する場合は、ファイルのメモリに一度アップロードして再利用します。
  • リソース利用を管理するために、高容量環境のためのクエウシステムの導入を検討する。

ベストプラクティス

  • 実行時間の例外を防ぐために、処理前に常に入力ファイルを有効にする。
  • ファイル I/O 作業および変換プロセスの周りに適切なエラー処理を実施します。
  • PDFの適切な遵守基準(PDF/A-1b、PDF 1.7)をアーカイブまたは配布要件に基づいて設定します。
  • 頻繁に使用されるファイルやテンプレートをキャッシュして、繰り返し作業のパフォーマンスを向上させます。
  • 長期バッチ変換の進歩報告の実施を検討する。

高度なシナリオ

より複雑な要件のために、これらの先進的な実施を検討してください:

シナリオ1:カスタマイズされたページ指向によるセレクティブシート変換

// Create load options
LowCodeLoadOptions loadOptions = new LowCodeLoadOptions();
loadOptions.InputFile = "multi-sheet-report.xlsx";

// Create PDF save options with advanced settings
LowCodePdfSaveOptions pdfSaveOptions = new LowCodePdfSaveOptions();
PdfSaveOptions pdfOptions = new PdfSaveOptions();
pdfOptions.OnePagePerSheet = true;

// Only convert specific sheets
Workbook workbook = new Workbook(loadOptions.InputFile);
pdfOptions.SheetSet = new Aspose.Cells.Rendering.SheetSet(new int[] { 0, 2, 3 }); // Select specific sheets by index

// Set page orientation based on sheet content
foreach (Worksheet sheet in workbook.Worksheets)
{
    if (sheet.Cells.MaxColumn > 10) // Wide sheets get landscape orientation
    {
        PageSetup pageSetup = sheet.PageSetup;
        pageSetup.Orientation = PageOrientationType.Landscape;
    }
}

pdfSaveOptions.PdfOptions = pdfOptions;
pdfSaveOptions.OutputFile = "selective-sheets-report.pdf";

// Process the conversion
PdfConverter.Process(loadOptions, pdfSaveOptions);

シナリオ2:デジタルサインを生成されたPDFに追加する

// Standard conversion setup
LowCodeLoadOptions loadOptions = new LowCodeLoadOptions();
loadOptions.InputFile = "financial-statement.xlsx";

LowCodePdfSaveOptions pdfSaveOptions = new LowCodePdfSaveOptions();
PdfSaveOptions pdfOptions = new PdfSaveOptions();
pdfOptions.OnePagePerSheet = true;

// Set up digital signature parameters
pdfOptions.DigitalSignature = new DigitalSignature();
pdfOptions.DigitalSignature.CertificateFilePath = "signature-certificate.pfx";
pdfOptions.DigitalSignature.Password = "certificate-password";
pdfOptions.DigitalSignature.Reason = "Financial approval";
pdfOptions.DigitalSignature.Location = "Finance Department";
pdfOptions.DigitalSignature.SignatureDate = DateTime.Now;

pdfSaveOptions.PdfOptions = pdfOptions;
pdfSaveOptions.OutputFile = "signed-financial-report.pdf";

// Process the conversion with digital signature
PdfConverter.Process(loadOptions, pdfSaveOptions);

結論

Aspose.Cells LowCode PDF Converter を実装することで、複数の表の Excel ワークブックをプロフェッショナルにフォーマットされた PDF ドキュメントに効率的に変換し、論理的なワークシートの分離を一ページごとにオプションで維持できます。このアプローチは、文書の完全性とプロの外観を維持しながら、財務およびビジネス報告プロセスを大幅に簡素化します。

詳しい情報や追加の例を参照してください。 Aspose.Cells.LowCode API リファレンス .

 日本語