简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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