使用EPplus将相同的图像多次插入Excel

时间:2015-10-26 03:23:44

标签: c# asp.net excel export epplus

我想使用EPplus方法多次将相同的图像插入excel。我在线进行了调查并尝试了此链接中的方法(Adding images into Excel using EPPlus),但我收到了以下错误'名称已存在于此行的图纸集合中

var picture = ws.Drawings.AddPicture(a.ToString(), repeatimage);

这是我的代码:

public void ExportToExcel()
{
    //for export

        ExcelPackage objExcelPackage = new ExcelPackage();   //create new workbook

        string[] filesindirectory = Directory.GetDirectories(Server.MapPath("~/Folder"));
        string repeatimagepath=@"C:\Users\user\Desktop\Project\Project1\Project1\NewProject\NewProject\Image\repeatimage.png";
        Bitmap repeatimage= new Bitmap(repeatimagepath);
        int count = 0;
        int count1 = 0;
        int x = 25;
        int finalValue = 0;

        foreach (string subdir in filesindirectory)
        {
            count++;
            string[] splitter = subdir.Split('\\');
            string folderName = splitter[splitter.Length - 1];
            ExcelWorksheet ws = objExcelPackage.Workbook.Worksheets.Add(folderName); //create new worksheet
            count1 = 0;
            foreach (string img in Directory.GetFiles(subdir))
            {
                count1++;
                System.Web.UI.WebControls.Image TEST_IMAGE = new System.Web.UI.WebControls.Image();
                System.Drawing.Image myImage = System.Drawing.Image.FromFile(img);
                var pic = ws.Drawings.AddPicture(count1.ToString(), myImage);  

                **for (int a = 0; a < 5; a++)
                {
                    var picture = ws.Drawings.AddPicture(a.ToString(), repeatimage);
                    picture.SetPosition(a * 5, 0, 2, 0);
                }**

                // Row, RowoffsetPixel, Column, ColumnOffSetPixel
                if (count1 > 1)
                {
                    pic.SetPosition(finalValue, 0, 2, 0);
                    finalValue += (x + 1); // Add 1 to have 1 row of empty row
                }
                else
                {
                    pic.SetPosition(count1, 0, 2, 0);
                    finalValue = (count1 + x) + 1; // Add 1 to have 1 row of empty
                }
                myImage.Dispose();
                repeatimage.Dispose();
            }
        }

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

问题:如何使用EPplus多次将同一图像插入Excel?

请帮助我,谢谢。

1 个答案:

答案 0 :(得分:2)

错误已经告诉你答案了
这一行count11

var pic = ws.Drawings.AddPicture(count1.ToString(), myImage);  

然后这一行

for (int a = 0; a < 5; a++)
{
    var picture = ws.Drawings.AddPicture(a.ToString(), repeatimage);
    picture.SetPosition(a * 5, 0, 2, 0);
}

您的a01234作为照片的名称
你看错了吗?