使用 EPPlus 将背景图像添加到 Excel 不起作用

Adding Background Image to Excel using EPPlus not working

我正在使用以下代码将背景图像添加到 Excel 使用 EPPlus.But 的工作表,打开时保存的 Excel 没有任何背景 imgae.And联机 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))
                {

                    // Itterate through 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();
            }

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;
}