techno
techno

Reputation: 6500

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

Upvotes: 1

Views: 991

Answers (1)

pfx
pfx

Reputation: 23234

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

Upvotes: 3

Related Questions