天天看點

讀取EXCEL表格中的圖檔

在EXCEL表格内放置圖檔,假設表格的大小大于圖檔的寬高,圖檔完全置于表格内,如何讀取某個表格内的圖檔呢?使用微軟的EXCEL元件,直接從CELL或RANGE對象内是無法讀取的。圖檔是獨立于單元格的,不從屬于任何單元格,是以無法将圖檔與CELL或RANGE做對象級上的聯系。所有圖檔都隸屬于Shapes集合。每一張圖檔是一個shape判斷一張圖檔是否在某一單元格内,可以使用坐标位置的方法,如果圖檔的位置在單元格的位置的高寬範圍内,則表示圖檔在單元格内。判斷出一張圖檔在某單元格内後,可以使用shape對象的CopyPicture方法,将圖檔複制到剪貼闆,再從剪貼闆内将圖檔存到本地。 示意代碼如下:

for (int row = 1; row <= ws.UsedRange.Rows.Count; row++) {     for (int col = 1; col <= ws.UsedRange.Columns.Count; col++)   {       Range rge = ws.Cells[row, col] as Range;       foreach (Shape sh in ws.Shapes)     {         Range rg = excel.get_Range(sh.TopLeftCell, sh.BottomRightCell);         if (excel.Intersect(rge, rg, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,           Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,           Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing) != null)       {           sh.CopyPicture(Appearance.Button, Microsoft.Office.Interop.Excel.XlCopyPictureFormat.xlBitmap);           IDataObject data = Clipboard.GetDataObject();           if (data.GetDataPresent(DataFormats.Bitmap))           {               Image image = (Image)data.GetData(DataFormats.Bitmap, true);               image.Save("test.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);           }       }     }   } }