Home » excel » c# – Adding Background Image to Excel using EPPlus not working

c# – Adding Background Image to Excel using EPPlus not working

Posted by: admin May 14, 2020 Leave a comment

Questions:

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();
            }
How to&Answers:

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