使用OLEDB从Excel文件中检索图片

我有一个Excel表,有两列,一个是数字,第二列有一个图片。 我想从oledb连接的C#中读取这些数据,我可以很容易地读取数字,但图片不包含在第二列,所以在C#中我只是得到第一列。

现在,我怎样才能读取图像? 我想从这个Excel表格中提取数字和相关图像。

恐怕不可能。

图片不在细胞中生存 – 你可以把它们放在细胞上,你可以把它们看起来像在细胞中,但是它们决不会占据细胞。

您可以使用VBA和COM互操作来处理工作表的图像内容,但不能操作OLEDB。

这是一个较老的主题,但我想我会添加一些我的代码到目前为止。

这个例子假设你有一个Windows应用程序,你已经把一个Picturebox放在了所谓的“pictureBox1”上。

它还假定您添加对Excel的引用(Microsoft.Office.Interop.Excel)。

正如杰伊所说,图片是绑定在你的工作簿上的,而不是自己的单元的一部分。 通过使用TopLeftCell和BottomRightCell,你可以很容易地find图像的位置。

现在,您需要编写一个循环来提取文档中的所有图像,但是我会将其留给您。

string file = @"C:\sample.xlsx"; if(System.IO.File.Exists(file)) { Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application(); excelApp.Visible = true; //FOR TESTING ONLY Microsoft.Office.Interop.Excel.Workbook wb = excelApp.Workbooks.Open(file, 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); Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Sheets[1]; //Selects the first sheet Microsoft.Office.Interop.Excel.Range range = (Microsoft.Office.Interop.Excel.Range)ws.Cells[1, 1]; //Select cell A1 object cellValue = range.Value2; #region Extract the image Microsoft.Office.Interop.Excel.Picture pic = (Microsoft.Office.Interop.Excel.Picture)ws.Pictures(1); if (pic != null) { //This code will detect what the region span of the image was int startCol = (int)pic.TopLeftCell.Column; int startRow = (int)pic.TopLeftCell.Row; int endCol = (int)pic.BottomRightCell.Column; int endRow = (int)pic.BottomRightCell.Row; pic.CopyPicture(Microsoft.Office.Interop.Excel.XlPictureAppearance.xlScreen, Microsoft.Office.Interop.Excel.XlCopyPictureFormat.xlBitmap); if (Clipboard.ContainsImage()) { Image img = Clipboard.GetImage(); this.pictureBox1.Image = img; } } #endregion //Close the workbook wb.Close(false,Type.Missing,Type.Missing); //Exit Excel excelApp.Quit(); } 

Nick的答案在我的web应用程序中非常有用,只是稍微改变了一点就是没有将图像复制到剪贴板

  Thread thread = new Thread(() => { foreach (var pic in ws.Pictures()) { if (pic != null) { //This code will detect what the region span of the image was int startCol = pic.TopLeftCell.Column; int startRow = pic.TopLeftCell.Row; int endCol = pic.BottomRightCell.Column; int endRow = pic.BottomRightCell.Row; pic.CopyPicture(XlPictureAppearance.xlScreen, XlCopyPictureFormat.xlBitmap); if (Clipboard.GetDataObject() != null) { Image img = Clipboard.GetImage(); } } } }); thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA thread.Start(); thread.Join(); 

为我工作