.net 使用EPPlus将背景图像添加到Excel不工作

hyrbngr7  于 2023-11-20  发布在  .NET
关注(0)|答案(1)|浏览(176)

我正在使用以下代码使用EPPlus向Excel工作表添加背景图像。但是保存的Excel没有任何背景图像。并且在使用在线Excel打开文件时,它说工作簿已损坏。

foreach (var file in Filelist)
{
    // Load workbook
    //var fileInfo = new FileInfo(@file);
    FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

    Bitmap bmp = new Bitmap("image.png");
    //ExcelPackage pkg = new ExcelPackage(fs);

    using (var package = new ExcelPackage(fs))
    {
        // Iterate over workbook sheets
        foreach (var sheet in package.Workbook.Worksheets)
        {
            sheet.BackgroundImage.Image = bmp;
            sheet.Protection.IsProtected = false;
        }
                   
        package.SaveAs(new FileInfo(@"New.xlsx"));
    }

    fs.Close();
}

字符串

2w2cym1i

2w2cym1i1#

sheet上的BackgroundImage有一个方法SetFromFile,它可以完成这个任务。
完整代码

var file = @"c:\folder\spreadsheet.xlsx"; // Path to your source spreadsheet file here.
var image = @"c:\folder\background.png"; // Path to your background image here.
var imageFile = new FileInfo(image);

using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var package = new ExcelPackage(fs))
{
    foreach (var sheet in package.Workbook.Worksheets)
    {
        sheet.BackgroundImage.SetFromFile(imageFile);
    }

    package.SaveAs(new FileInfo(@"c:\folder\new.xlsx")); // Path to destination spreadsheet file here;
}

字符串

相关问题