首页 > 解决方案 > EPPlus:结合形状和程序化图片的错误

问题描述

问题:

当我以编程方式打开一个其中包含形状(例如箭头)的 Excel 文件,然后通过向其中添加新图像(以编程方式)来修改该文件时,如果我尝试获取GetAsByteArray这个新修改的 Excel 文件的字节() ,它崩溃了。

重现错误的步骤:

  1. 创建一个 Excel 文件 (xlsx) 并在其中添加一个形状(例如箭头)

  2. 使用此代码打开该文件并添加程序图片

    string path = Server.MapPath("~/Content/input.xlsx");
    
    using (Stream stream = System.IO.File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    {
        // Read file
        ExcelPackage excelPackage = new ExcelPackage(stream);
    
        // Get worksheets
        ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.FirstOrDefault();
    
        // Add programmatic picture
        worksheet.Drawings
            .AddPicture("logo", new FileInfo(Server.MapPath("~/Content/logo.png")))
            .SetPosition(5, 0, 5, 0);
    
        byte[] output = File(excelPackage.GetAsByteArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "output.xlsx");
    }
    

有什么想法或解决方法吗?

标签: epplus

解决方案


试试这个代码。添加图像后,它将为您提供字节。但是 Excel 文件不会发生其他任何事情。

//create a fileinfo object of an excel file on the disk
FileInfo file = new FileInfo(Server.MapPath(""~/Content/input.xlsx"));

//create a new Excel package from the file
using (ExcelPackage package = new ExcelPackage(file))
{
    //create an instance of the the first sheet in the loaded file
    ExcelWorksheet worksheet = package.Workbook.Worksheets[1];

    //Add programmatic picture
    worksheet.Drawings
        .AddPicture("logo", new FileInfo(Server.MapPath("~/Content/logo.png")))
        .SetPosition(5, 0, 5, 0);

    //get the new size in byte array
    byte[] output = package.GetAsByteArray();
}

推荐阅读