Felicia Soh
Felicia Soh

Reputation: 865

Add image from a folder to Excel worksheet

I want to export all images from my image folder into Excel. I want to place every image in the image folder into a new excel worksheet. For example if there are ten images in the folder, I want to have ten Excel worksheets on the same Excel workbook with one image on each worksheet.

This is my code:

    string[] filesindirectory = Directory.GetFiles(Server.MapPath("~/Image"));
                int count = 0;
                foreach (string img in filesindirectory)
                {
                    count++;
                 ExcelWorksheet ws = objExcelPackage.Workbook.Worksheets.Add("Worksheet - " + count); //create new worksheet
                    System.Web.UI.WebControls.Image TEST_IMAGE = new System.Web.UI.WebControls.Image();
                    TEST_IMAGE.ImageUrl = "Image/" + Path.GetFileName(img);
                    TEST_IMAGE.ImageUrl = this.GetAbsoluteUrl(TEST_IMAGE.ImageUrl);

                   //I want to insert image here

var filepath= new FileInfo(@"C:\Users\user\Desktop\folder\" + datetime.ToString("dd-MM-yyyy_hh-mm-ss") + ".xlsx");
                        objExcelPackage.SaveAs(filepath);

This is my updated code:

string[] filesindirectory = Directory.GetFiles(Server.MapPath("~/Image"));
        int count = 0;
        foreach (string img in filesindirectory)
        {
            count++;
            ExcelWorksheet ws = objExcelPackage.Workbook.Worksheets.Add("Worksheet - " + count); //create new worksheet
            System.Web.UI.WebControls.Image TEST_IMAGE = new System.Web.UI.WebControls.Image();
            var filedest = new FileInfo(@"C:\Users\user\Desktop\Project\Project1\Source Code\Test\Test\Image\");
            System.Drawing.Image myimage = System.Drawing.Image.FromFile(filedest);
            var pic = ws.Drawings.AddPicture("NAME", myimage);

            var filepath = new FileInfo(@"C:\Users\user\Desktop\folder\" + datetime.ToString("dd-MM-yyyy_hh-mm-ss") + ".xlsx");
            objExcelPackage.SaveAs(filepath);

but I get the following error:

FileNotFoundException was unhandled by user code

, on this line:

var filedest = new FileInfo(@"C:\Users\user\Desktop\Project\Project1\Source Code\Test\Test\Image\");  

How to add image from a folder to Excel worksheet using EPPlus with my current code?

Upvotes: 1

Views: 5087

Answers (1)

Nic
Nic

Reputation: 1024

This should help you...

// Variable
string[] filesDirectory = Directory.GetFiles(Server.MapPath("~/Image"));
int count = 0;

foreach(string img in filesDirectory)
{
    count++;
    ExcelWorksheet ws = pkg.Workbook.Worksheets.Add("Worksheet - " + count);

    // img variable actually is your image path
    System.Drawing.Image myImage = System.Drawing.Image.FromFile(img);

    var pic = ws.Drawings.AddPicture("NAME", myImage);

    // Row, RowoffsetPixel, Column, ColumnOffSetPixel
    pic.SetPosition(1, 0, 2, 0);
}

Upvotes: 1

Related Questions