简体   繁体   English

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

[英]Adding Background Image to Excel using EPPlus not working

I'm using the following code to add a background image to Excel sheets using EPPlus.But the saved Excel does not have any background imgae.And on on opening the file with online excel it says that the workbook is damaged.我正在使用以下代码使用 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))
                {

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

The BackgroundImage on the sheet has a method SetFromFile which does the trick.工作sheet上的BackgroundImage有一个方法SetFromFile可以解决问题。

Full code完整代码

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM