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

CBo*_*Boy 4 c# oledb excel image

我有一个带有两列的Excel工作表,一个是数字,第二列有一个图片.我想用oledb连接读取c#中的这些数据,我可以轻松读取数字,但是第二列中没有包含图片,所以在c#中我只得到第一列.

现在,我该如何阅读图片?我想从这个excel表中提取数字和相关图像.

小智 6

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

此示例假定您有一个Windows应用程序,您已将Picturebox放在名为"pictureBox1"上.

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

正如杰伊所提到的那样,图片与你的工作簿绑定,而不是自己的一部分.您可以使用TopLeftCell和BottomRightCell轻松找到图像的位置.

现在,你需要编写一个循环来拉出文档中的所有图像,但我会把它留给你.

        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();
        }
Run Code Online (Sandbox Code Playgroud)


Jay*_*Jay 5

恐怕不可能。

图片并不存在于单元格中——您可以将它们放置在单元格,并且可以调整它们的大小以使其看起来像在单元格中,但它们决不会占据该单元格。

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