将文件夹中的图像添加到Excel工作表

时间:2015-10-22 01:58:35

标签: c# asp.net excel export epplus

我想将图像文件夹中的所有图像导出到Excel中。我想将图像文件夹中的每个图像放入一个新的Excel工作表中。例如,如果文件夹中有10个图像,我希望在同一个Excel工作簿上有10个Excel工作表,每个工作表上有一个图像。

这是我的代码:

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

这是我更新的代码:

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

但是我收到以下错误:

  

FileNotFoundException未被用户代码

处理

,在这一行:

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

如何使用EPPlus将文件夹中的图像添加到Excel工作表中?

1 个答案:

答案 0 :(得分:1)

这应该对你有帮助......

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