简体   繁体   中英

Excel sheet in Microsoft excel interop. Save an image to a file

I have installed EPPlus in my c# project and used it to locate the proper image in an Excel worksheet. I want to take the image now and save it as a PNG file.

 FileInfo fi = new FileInfo(@"c:/folder/workbook.xlsx");
 using (ExcelPackage excelPackage = new ExcelPackage(fi))
  {
   ExcelWorksheet ws = excelPackage.Workbook.Worksheets[0];
   int imageCount = firstWorksheet.Drawings.Count;
   for (int i = 0; i <= imageCount-1; i++)
    {
       if (firstWorksheet.Drawings[i].DrawingType.ToString().ToLower() == "picture")
        {
         save it to a file;
        }
    }
  }

Here is what I did that works great. Of course this is a little abbreviated.

OfficeOpenXml.Drawing.ExcelDrawing image = firstWorksheet.Drawings[i]; OfficeOpenXml.Drawing.ExcelPicture p = (OfficeOpenXml.Drawing.ExcelPicture)image; p.Image.Save(@"c:/autocell/becbec.png");

This works with embedded xml files / tables. I also pasted in jpegs and pngs and bitmaps and this code found and saved them just fine too.

You can give the export URL and then it will be shown in the excel file

Get Absolute URL function

private string GetAbsoluteUrl(string relativeUrl)
{
    relativeUrl = relativeUrl.Replace("~/", string.Empty);
    string[] splits = Request.Url.AbsoluteUri.Split('/');
    if (splits.Length >= 2)
    {
        string url = splits[0] + "//";
        for (int i = 2; i < splits.Length - 1; i++)
        {
            url += splits[i];
            url += "/";
        }
 
        return url + relativeUrl;
    }
    return relativeUrl;
}

and save it like this

//Convert the Relative Url to Absolute Url and set it to Image control.

Image1.ImageUrl = this.GetAbsoluteUrl(Image1.ImageUrl);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM