.NET에서 Excel 파일을 PDF로 변환하는 방법
이 기사는 Aspose.Cells LowCode PDF Converter를 사용하여 여러 Excel 파일을 PDF로 변환하는 방법을 보여줍니다 .NET 응용 프로그램에서 PDF 컨버터는 Excel 내부 구조에 대한 광범위한 코딩이나 깊은 지식을 필요로하지 않고 문서 전환에 유연한 접근 방식을 제공합니다 - 비즈니스 분석가 및 보고 작업 흐름을 자동화 할 필요가있는 보고 개발자에게 완벽합니다.
현실 세계 문제
기업 환경에서 보고 팀은 종종 정기적으로 수십 또는 심지어 수백 개의 Excel 워크북을 PDF 형식으로 변환해야합니다.이 작업을 수행하는 것은 시간 소비, 오류 방지, 그리고 더 중요한 분석 작업에서 귀중한 자원을 분리 합니다.
솔루션 검토
Aspose.Cells LowCode PDF Converter를 사용하면 최소 코드로 효율적으로이 도전을 해결할 수 있습니다.이 솔루션은 비즈니스 분석가 및 보고 개발자가 보고 프로세스를 단순화하고 문서의 일관성을 보장하고 더 가치있는 작업을위한 시간을 자유롭게해야하는 데 이상적입니다.우리의 접근 방식은 사용자 지정 변환 설정으로 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 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 셀 콘텐츠를 기반으로 사용자 지정된 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를 배치 처리, 비즈니스 분석가 및 보고 개발자는 매뉴얼 Excel에서 PDF 변환에 지출 된 시간을 크게 줄일 수 있습니다.이 접근 방식은 생산성을 크게 향상시키고 모든 생성 된 PDF에 대한 일관성을 보장하면서 원래 Excel 파일의 품질과 포맷을 유지합니다.
더 많은 정보와 추가 예제는 다음과 같습니다. Aspose.Cells.LowCode API 참조 .