我有一个包含两列的 Excel 工作表,一列是数字,第二列是图片。 我想通过 oledb 连接从 C# 读取这些数据,我可以轻松读取数字,但图片不包含在第二列中,所以在 C# 中我只得到第一列。
现在,我该如何阅读图像?我想从此 Excel 工作表中提取数字和相关图像。
最佳答案
这是一个较旧的主题,但我想到目前为止我会添加一些代码。
此示例假设您有一个 Windows 应用程序,您在其中放置了一个名为“pictureBox1”的图片框。
它还假设您添加了对 Excel (Microsoft.Office.Interop.Excel) 的引用。
图片绑定(bind)到您的工作簿,而不是 Jay 提到的单元格本身的一部分。通过使用 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();
}
关于c# - 使用 OLEDB 从 Excel 文件中检索图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2632715/