导出Excel中指定单元格的图片 - 炫Q香蕉派

导出Excel中指定单元格的图片

想导出excel中的图片,并用某个单元格的数据命名,结果发现找不到图片的单元格,这可怎么办,发现图片是存储在单独的Shapes中的,所以只能根据图片的Top和行的Top比较判断图片在哪一行了,这里用到一个Excel的引用

using Microsoft.Office.Interop.Excel;

然后就是提取和保存代码了

string fn = @"Book1.xls";
ApplicationClass excel = new ApplicationClass();
Workbook workbook = excel.Workbooks.Add(fn);
excel.UserControl = true;
excel.Visible = false;
Worksheet sheet = workbook.Worksheets.get_Item(1) as Worksheet;
int row = 0;
Range range;
for (int i = 1; i <= sheet.Shapes.Count; i++)
{
    Shape s = sheet.Shapes.Item(i) as Shape;
    float img_top = s.Top;
    do
    {
        row++;
        range = sheet.Cells[row, 1] as Range;
    } while (img_top - 5 > (double)(range.Top));
    string f = "img_" + range.Text + ".jpg";
    Clipboard.Clear();
    s.CopyPicture(Appearance.Button, XlCopyPictureFormat.xlBitmap);
    IDataObject iData = Clipboard.GetDataObject();
    if (iData != null && iData.GetDataPresent(DataFormats.Bitmap))
    {
        System.Drawing.Image img = Clipboard.GetImage();
        if (img != null)
        {
            img.Save(@"" + f, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
    }
}
workbook.Close(false, null, null);
excel.Quit();

参考文献:
http://blog.163.com/jiajia8166@126/blog/static/1813520201282753358819/?latestBlog
http://blog.sina.com.cn/s/blog_4c6e822d0102e2f0.html
http://www.cnblogs.com/MR_ke/archive/2010/03/08/1680576.html

标签: none

添加新评论