Excel 워크시트를 .NET으로 PDF로 변환하는 방법

Excel 워크시트를 .NET으로 PDF로 변환하는 방법

이 기사에서는 Excel 파일을 변환하는 방법을 보여줍니다. PDF에 대하여 .NET 응용 프로그램에서 Aspose.Cells LowCode PDF Converter를 사용하여 1 페이지/시트 레이아웃을 제공합니다.PDF 컨버터는 Excel 스파이더를 전문적으로 형성된 PDF 문서로 변환하는 유연한 접근 방식을 제공하며 Excel 내부 구조에 대한 광범위한 코딩이나 깊은 지식이 필요하지 않습니다.

현실 세계 문제

금융 분석가들은 종종 각 워크시트가 검토 및 인쇄를 촉진하기 위해 자신의 페이지에 나타나는 표준화 된 PDF 보고서로 Excel 금융 모델을 변환해야합니다. 전통적인 전환 방법은 모든 데이터를 지속적인 페이지로 결합하거나 각 잎의 수동 처리가 필요합니다..

솔루션 검토

Aspose.Cells LowCode PDF Converter를 사용하면 최소 코드를 사용하여 이 도전을 효율적으로 해결할 수 있습니다.이 솔루션은 금융 전문가, 보고서 개발자 및 비즈니스 분석가가 전문 PDF 보고서를 생성해야하며 Excel 데이터 소스에서 워크시트의 논리적 분리를 유지해야합니다.

원칙

솔루션을 실행하기 전에, 당신이 가지고 있는지 확인하십시오 :

  • 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 페이지/시트 형식은 수신자가 각 비즈니스 단위, 제품 라인 또는 시간 기간이 자신의 페이지에 나타나는 잘 구성된 문서를 받는 것을 보장합니다.

일반적인 도전과 해결책

도전 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를 구현함으로써, 당신은 효율적으로 전문적으로 형식화 된 PDF 문서로 멀티 슬라이드 Excel 워크북을 변환하고 논리적 인 테이블 분리 옵션을 유지할 수 있습니다.이 접근 방식은 상당히 금융 및 비즈니스 보고 프로세스를 촉진하고 동시에 서류의 무결성과 전문적인 외모를 유지합니다.

더 많은 정보와 추가 예제는 다음과 같습니다. Aspose.Cells.LowCode API 참조 .

 한국어