本文展示了如何使用 Aspose.Cells LowCode Converters 在 .NET 网页应用程序中实施内存 Excel 格式转换,这些转机提供了一种顺利的方法来处理Excel format 变更,而无需进行广泛的编码或暂时存储到磁盘的文件,使其适合 Web 和 SaaS 环境.

现实世界问题

网页应用经常需要处理用户上传的 Excel 文件并将其转换为不同的格式,如 PDF、HTML 或 JSON 查看、共享或数据提取.

解决方案概述

使用 Aspose.Cells LowCode Converters,我们可以通过在内存中进行所有转换来有效地解决这个挑战,这种解决方案对于需要实施安全、可扩展的文档处理功能而无需复杂的文件系统操作的 Web 开发人员和 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 包添加到您的 Web 项目中,并包含所需的名称空间:

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:优化Web应用性能

考虑这些网站环境优化技术:

// 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:完整实施示例

下面是一个完整的工作例子,一个Web 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);
    }
}

使用案例和应用程序

基于Web的文档浏览器系统

允许用户上传 Excel 文件并立即将其视为 HTML 或 PDF 而不需要 Excel 的软件,这使得跨平台兼容性和移动友好的文档直接在浏览器中查看.

SaaS 数据处理平台

过程通过将 Excel 数据转换为 JSON 为数据库集成,然后为不同利益相关者创建各种格式(PDF、HTML)的报告 - 所有这些都没有磁盘操作,这会使云部署变得复杂.

基于 API 的文档转换服务

建立一个专门的微服务或API终端点,以处理您的生态系统中的其他应用程序的Excel格式转换,提供一个集中转型能力,在您的服务中保持一致性.

共同挑战与解决方案

挑战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 操作的无同步处理,以防止网页服务器中的线条封锁
  • 考虑实施经常转换文件的缓存,以减少处理负担
  • 对于高流量应用,实施专门的背景服务处理转换

最佳实践

  • 始终使用 MemoryStream 对象,以防止内存漏洞,特别是在长期运行的 Web 应用程序中
  • 实施适合您的服务器资源的文件大小限制
  • 使用测量和监测来跟踪转换时间和资源使用
  • 考虑实施转换终点限制机制,以防止滥用

先进的场景

对于更复杂的要求,请考虑这些先进的实施:

场景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");
}

结论

通过实施内存 Excel 格式转换与 Aspose.Cells LowCode Converters,网页开发人员可以显著提高他们的应用程序与强大的文档处理能力,没有文件系统依赖.

要了解更多信息和更多例子,请参阅 Aspose.Cells.LowCode API 参考.

额外资源

  • 实施 Aspose.Cells SaveOptions 可以帮助自定义您的转换过程,以满足您的具体需求.

More in this category