이 기사에서는 Aspose.Cells LowCode Converters를 사용하여 메모리에서 Excel 형식 변환을 실행하는 방법을 보여줍니다. .NET 웹 응용 프로그램에서 이러한 컨버터는 광범위한 암호화 또는 디스크에 일시적인 파일을 저장할 필요가 없으며 Web 및 SaaS 환경에 이상적입니다.
현실 세계 문제
웹 애플리케이션은 종종 사용자가 업로드 한 Excel 파일을 처리하고 PDF, HTML 또는 JSON과 같은 다른 형식으로 변환하여 시청, 공유 또는 데이터 추출을 필요로합니다.전통적인 접근 방식은 자주 디스크에 일시적인 파일 저장, 보안 문제를 소개, 파일 관리 과제, 그리고 클라우드 환경에서 잠재적 인 스케일성 문제.
솔루션 검토
Aspose.Cells LowCode Converters를 사용하면 모든 메모리 변환을 수행함으로써 효율적으로이 도전을 해결할 수 있습니다.이 솔루션은 복잡한 파일 시스템 작업없이 안전하고 규모가 많은 문서 처리 기능을 구현해야하는 웹 개발자 및 SaaS 아키텍처에 이상적입니다.
원칙
솔루션을 실행하기 전에, 당신이 가지고 있는지 확인하십시오 :
- Visual Studio 2019 또는 이후
- .NET 6.0 또는 이후 (NET Framework 4.6.2+와 호환)
- NuGet을 통해 설치된 .NET 패키지에 대한 Aspose.Cells
- 웹 애플리케이션 프로젝트 (ASP.NET Core MVC, Web API 등)
PM> Install-Package Aspose.Cells
단계별 실행
단계 1: 설치 및 설정 Aspose.Cells
Aspose.Cells 패키지를 웹 프로젝트에 추가하고 필요한 이름 공간을 포함합니다.
using Aspose.Cells;
using Aspose.Cells.LowCode;
using Aspose.Cells.Rendering;
using System.IO;
단계 2: 파일 변환을 처리하기 위해 컨트롤러 방법을 만듭니다.
API 엔드 포인트 또는 컨트롤러 방법을 설정하여 파일 업로드를 수락하고 변환된 형식을 반환합니다.
[HttpPost("convert-to-pdf")]
public IActionResult ConvertToPdf(IFormFile excelFile)
{
if (excelFile == null || excelFile.Length == 0)
return BadRequest("No file uploaded");
// Continue with conversion process
}
단계 3 : 메모리 변환 논리를 구현
업로드 된 파일을 처리하고 완전히 메모리로 변환합니다 :
// Read the uploaded file into memory
using var inputStream = new MemoryStream();
excelFile.CopyTo(inputStream);
inputStream.Position = 0;
// Configure the conversion options
LowCodeLoadOptions loadOptions = new LowCodeLoadOptions();
loadOptions.InputStream = inputStream;
// Create output memory stream for the converted file
using var outputStream = new MemoryStream();
// Configure save options for PDF
LowCodePdfSaveOptions saveOptions = new LowCodePdfSaveOptions();
PdfSaveOptions pdfOptions = new PdfSaveOptions();
pdfOptions.OnePagePerSheet = true;
saveOptions.PdfOptions = pdfOptions;
saveOptions.OutputStream = outputStream;
// Execute the conversion
PdfConverter.Process(loadOptions, saveOptions);
4단계: 변환된 파일을 고객에게 반환합니다.
다운로드 할 수있는 응답으로 변환 된 파일을 반환합니다 :
// Reset the position of output stream
outputStream.Position = 0;
// Return as downloadable file
return File(outputStream.ToArray(), "application/pdf", "converted-document.pdf");
단계 5 : 다른 변환 유형의 구현
HTML, JSON 및 이미지와 같은 다른 변환 형식에 대한 방법을 추가하십시오 :
// HTML conversion
public MemoryStream ConvertToHtml(MemoryStream inputStream)
{
LowCodeLoadOptions loadOptions = new LowCodeLoadOptions();
loadOptions.InputStream = inputStream;
LowCodeHtmlSaveOptions saveOptions = new LowCodeHtmlSaveOptions();
HtmlSaveOptions htmlOptions = new HtmlSaveOptions();
htmlOptions.ExportImagesAsBase64 = true; // For fully self-contained HTML
saveOptions.HtmlOptions = htmlOptions;
var outputStream = new MemoryStream();
saveOptions.OutputStream = outputStream;
HtmlConverter.Process(loadOptions, saveOptions);
outputStream.Position = 0;
return outputStream;
}
// JSON conversion
public MemoryStream ConvertToJson(MemoryStream inputStream)
{
LowCodeLoadOptions loadOptions = new LowCodeLoadOptions();
loadOptions.InputStream = inputStream;
LowCodeSaveOptions saveOptions = new LowCodeSaveOptions();
var outputStream = new MemoryStream();
saveOptions.OutputStream = outputStream;
JsonConverter.Process(loadOptions, saveOptions);
outputStream.Position = 0;
return outputStream;
}
단계 6 : 웹 시나리오에 대한 실수 처리 구현
웹 환경에 적절한 오류 처리 구체를 추가하십시오 :
try
{
// Process execution code
PdfConverter.Process(loadOptions, saveOptions);
return File(outputStream.ToArray(), "application/pdf", "converted-document.pdf");
}
catch (Exception ex)
{
// Log the error
_logger.LogError(ex, "Error converting Excel file to PDF");
// Return appropriate HTTP response
return StatusCode(500, "An error occurred during file conversion. Please try again.");
}
단계 7 : 웹 애플리케이션 성능을 최적화
웹 환경에 대한 이러한 최적화 기술을 고려하십시오 :
// Implement an async version for better scalability
[HttpPost("convert-to-pdf-async")]
public async Task<IActionResult> ConvertToPdfAsync(IFormFile excelFile)
{
if (excelFile == null || excelFile.Length == 0)
return BadRequest("No file uploaded");
using var inputStream = new MemoryStream();
await excelFile.CopyToAsync(inputStream);
inputStream.Position = 0;
// Perform conversion on a background thread to free up web server threads
return await Task.Run(() => {
try
{
using var outputStream = new MemoryStream();
// Conversion code as before
PdfConverter.Process(loadOptions, saveOptions);
return File(outputStream.ToArray(), "application/pdf", "converted-document.pdf");
}
catch (Exception ex)
{
_logger.LogError(ex, "Error in async conversion");
throw;
}
});
}
단계 8 : 완전한 구현 예제
다음은 포맷 변환을위한 웹 API 컨트롤러의 완전한 작업 예입니다 :
[ApiController]
[Route("api/[controller]")]
public class ExcelConverterController : ControllerBase
{
private readonly ILogger<ExcelConverterController> _logger;
public ExcelConverterController(ILogger<ExcelConverterController> logger)
{
_logger = logger;
}
[HttpPost("convert")]
public async Task<IActionResult> ConvertExcelFile(IFormFile file, [FromQuery] string format)
{
if (file == null || file.Length == 0)
return BadRequest("Please upload a file");
using var inputStream = new MemoryStream();
await file.CopyToAsync(inputStream);
inputStream.Position = 0;
// Initialize options
LowCodeLoadOptions loadOptions = new LowCodeLoadOptions();
loadOptions.InputStream = inputStream;
using var outputStream = new MemoryStream();
try
{
switch (format?.ToLower())
{
case "pdf":
LowCodePdfSaveOptions pdfOptions = new LowCodePdfSaveOptions();
pdfOptions.OutputStream = outputStream;
PdfConverter.Process(loadOptions, pdfOptions);
return ReturnFile(outputStream, "application/pdf", "converted.pdf");
case "html":
LowCodeHtmlSaveOptions htmlOptions = new LowCodeHtmlSaveOptions();
htmlOptions.OutputStream = outputStream;
HtmlConverter.Process(loadOptions, htmlOptions);
return ReturnFile(outputStream, "text/html", "converted.html");
case "json":
LowCodeSaveOptions jsonOptions = new LowCodeSaveOptions();
jsonOptions.OutputStream = outputStream;
JsonConverter.Process(loadOptions, jsonOptions);
return ReturnFile(outputStream, "application/json", "converted.json");
case "png":
LowCodeImageSaveOptions imgOptions = new LowCodeImageSaveOptions();
ImageOrPrintOptions imageTypeOptions = new ImageOrPrintOptions();
imageTypeOptions.ImageType = Aspose.Cells.Drawing.ImageType.Png;
imgOptions.ImageOptions = imageTypeOptions;
imgOptions.OutputStream = outputStream;
ImageConverter.Process(loadOptions, imgOptions);
return ReturnFile(outputStream, "image/png", "converted.png");
default:
return BadRequest("Unsupported format. Please use: pdf, html, json, or png");
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error converting file to {Format}", format);
return StatusCode(500, "An error occurred during conversion");
}
}
private FileContentResult ReturnFile(MemoryStream stream, string contentType, string fileName)
{
stream.Position = 0;
return File(stream.ToArray(), contentType, fileName);
}
}
사례 및 응용 프로그램 사용
웹 기반 문서 뷰어 시스템
사용자가 Excel 파일을 업로드하고 Excel 소프트웨어를 필요로하지 않고 HTML 또는 PDF로 즉시 볼 수 있습니다.이 플랫폼 간 호환성과 모바일 친화적 인 문서가 브라우저에서 직접 표시됩니다.
SaaS 데이터 처리 플랫폼
프로세스는 데이터 통합을 위해 JSON로 변환하여 Excel 데이터를 업로드 한 다음 다양한 형식 (PDF, HTML)의 보고서를 생성합니다 - 모든 디스크 작업이 없어서 클라우드 배포를 복잡하게합니다.
API 기반 문서 변환 서비스
귀하의 생태계의 다른 응용 프로그램에 대한 Excel 형식 변환을 관리하는 전문 마이크로 서비스 또는 API 엔드 포인트를 구축하여 서비스 내에서 일관성을 유지하는 중앙 전환 능력을 제공합니다.
일반적인 도전과 해결책
도전 1 : 큰 파일 처리
솔루션: 메모리 제한을 초과하는 파일의 경우, 처리 또는 서버 측 스트리밍을 사용하십시오.
// For large files, consider setting timeout and memory limits
[RequestSizeLimit(100_000_000)] // 100MB limit
[RequestFormLimits(MultipartBodyLengthLimit = 100_000_000)]
public async Task<IActionResult> ConvertLargeFile(IFormFile file)
{
// Implementation with resource monitoring
}
도전 2 : 경쟁 요구 관리
솔루션: 서버 과도한 부하를 방지하기 위해 퀘어링 및 리소스 트롤링을 구현합니다.
// Use a semaphore to limit concurrent conversions
private static SemaphoreSlim _conversionSemaphore = new SemaphoreSlim(5); // Max 5 concurrent
public async Task<IActionResult> ConvertWithThrottling(IFormFile file)
{
await _conversionSemaphore.WaitAsync();
try
{
// Conversion code
}
finally
{
_conversionSemaphore.Release();
}
}
도전 3 : 보안 문제
솔루션: 입력 파일의 적절한 인증 및 위생을 구현 :
private bool ValidateExcelFile(IFormFile file)
{
// Check file extension
var extension = Path.GetExtension(file.FileName).ToLowerInvariant();
if (extension != ".xlsx" && extension != ".xls" && extension != ".xlsm")
return false;
// Verify file signature/magic bytes
using var headerStream = new MemoryStream();
file.OpenReadStream().CopyTo(headerStream, 8); // Read first 8 bytes
byte[] headerBytes = headerStream.ToArray();
// Check for Excel file signatures
return IsValidExcelFileSignature(headerBytes);
}
성과 고려 사항
- 모든 I/O 작업에 대한 비동기 처리를 사용하여 웹 서버에서 끈 차단을 방지합니다.
- 처리 부하를 줄이기 위해 자주 변환 된 문서의 캐싱을 구현하는 것을 고려하십시오.
- 높은 트래픽 응용 프로그램을 위해, 변환 처리에 대한 전용 배경 서비스를 구현
모범 사례
- 메모리 스트림 개체를 항상 사용하여, 특히 오랫동안 실행되는 웹 애플리케이션에서 기억 유출을 방지하십시오.
- 귀하의 서버 자원에 적합한 파일 크기 제한 구현
- 메트릭 및 모니터링을 사용하여 변환 시간 및 자원 사용을 추적합니다.
- 학대를 방지하기 위해 변환 끝점에 대한 속도 제한 메커니즘을 구현하는 것을 고려하십시오.
고급 시나리오
더 복잡한 요구 사항을 위해, 이러한 고급 구현을 고려하십시오 :
시나리오 1 : 배치 처리 다중 변환
[HttpPost("batch-convert")]
public async Task<IActionResult> BatchConvert(List<IFormFile> files, string format)
{
if (files == null || !files.Any())
return BadRequest("No files uploaded");
var results = new List<ConversionResult>();
foreach (var file in files)
{
using var inputStream = new MemoryStream();
await file.CopyToAsync(inputStream);
inputStream.Position = 0;
using var outputStream = new MemoryStream();
try
{
LowCodeLoadOptions loadOptions = new LowCodeLoadOptions();
loadOptions.InputStream = inputStream;
LowCodeSaveOptions saveOptions = new LowCodeSaveOptions();
saveOptions.OutputStream = outputStream;
switch (format.ToLower())
{
case "pdf":
PdfConverter.Process(loadOptions, saveOptions);
break;
// Other formats...
}
results.Add(new ConversionResult {
FileName = file.FileName,
Success = true,
Data = Convert.ToBase64String(outputStream.ToArray())
});
}
catch (Exception ex)
{
results.Add(new ConversionResult {
FileName = file.FileName,
Success = false,
ErrorMessage = ex.Message
});
}
}
return Ok(results);
}
시나리오 2 : 변환 전에 역동적 인 스프레이 플레이트 조작
[HttpPost("modify-and-convert")]
public async Task<IActionResult> ModifyAndConvert(IFormFile file,
[FromQuery] string format,
[FromBody] SpreadsheetModificationRequest modRequest)
{
using var inputStream = new MemoryStream();
await file.CopyToAsync(inputStream);
inputStream.Position = 0;
// First load the workbook to modify it
Workbook workbook = new Workbook(inputStream);
// Apply the requested modifications
var worksheet = workbook.Worksheets[modRequest.WorksheetIndex];
foreach (var cellMod in modRequest.CellModifications)
{
worksheet.Cells[cellMod.CellReference].PutValue(cellMod.NewValue);
}
// Now prepare for conversion
using var modifiedStream = new MemoryStream();
workbook.Save(modifiedStream, SaveFormat.Xlsx);
modifiedStream.Position = 0;
// Convert using LowCode converters
LowCodeLoadOptions loadOptions = new LowCodeLoadOptions();
loadOptions.InputStream = modifiedStream;
using var outputStream = new MemoryStream();
LowCodePdfSaveOptions saveOptions = new LowCodePdfSaveOptions();
saveOptions.OutputStream = outputStream;
PdfConverter.Process(loadOptions, saveOptions);
outputStream.Position = 0;
return File(outputStream.ToArray(), "application/pdf", "modified-and-converted.pdf");
}
결론
Aspose.Cells LowCode Converters를 사용하여 메모리 Excel 형식 변환을 구현함으로써 웹 개발자는 파일 시스템 중독없이 강력한 문서 처리 능력으로 응용 프로그램을 상당히 향상시킬 수 있습니다.이 접근 방식은 일시적인 파일 취약점을 제거하여 보안을 크게 개선하고 동시에 클라우드 및 SaaS 애플리케이션에 대한 우수한 성능과 규모성을 유지합니다.
더 많은 정보와 추가 예제는 다음과 같습니다. Aspose.Cells.LowCode API 참조.
추가 자원
- Aspose.Cells SaveOptions의 구현은 귀하의 특정 요구를 충족시키기 위해 변환 과정을 사용자 정의하는 데 도움이 될 수 있습니다.