现需要实现一个功能:读取excel中的图片并将它保存到数据库中(web页面中),从网上看了几种方法,但试了总是不成功,一种方法的代码如下,求解。。有更好的方法么?谢谢- private int StartRow = 2; //读的起始行
- private int ImgCount = 0;
- protected void btnImport_Click(object sender, EventArgs e)
- {
- try
- {
- string path = "C:\\Users\\wang\\Desktop\\user.xlsx";
- Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();//引用Excel对象
- Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Add(path);
- excel.UserControl = true;
- System.Text.StringBuilder sb = new System.Text.StringBuilder();
- excel.Visible = false;
- for (int i = 0; i < workbook.Worksheets.Count; i++)//循环取所有的Sheet.
- {
- Microsoft.Office.Interop.Excel.Worksheet sheet = workbook.Worksheets.get_Item(i + 1) as Microsoft.Office.Interop.Excel.Worksheet;//从1开始.
- for (int row = StartRow; row <= sheet.UsedRange.Rows.Count; row++)
- {
- string imgName = string.Empty;
- //取单元格值;
- for (int col = 1; col <= sheet.UsedRange.Columns.Count; col++)
- {
- Microsoft.Office.Interop.Excel.Range range = sheet.Cells[row, col] as Microsoft.Office.Interop.Excel.Range;
- sb.Append("," + col.ToString() + ":" + range.Text);
- if(col==1)
- imgName = range.Text.ToString();//得到第一列的名称,作为图片名称
- }
- sb.Append(System.Environment.NewLine);
- //取存图片;
- if (sheet.Shapes.Count > row - StartRow)
- {
- Microsoft.Office.Interop.Excel.Shape s = sheet.Shapes.Item(row - StartRow + 1) as Microsoft.Office.Interop.Excel.Shape;
- s.CopyPicture(Appearance.Button, Microsoft.Office.Interop.Excel.XlCopyPictureFormat.xlBitmap); //COPY到内存。
- IDataObject iData = Clipboard.GetDataObject(); //这里为什么总是为null?
- if (iData.GetDataPresent(DataFormats.Bitmap))
- {
-
- ImgCount += 1; //保存的图片数加1
- }
- else
- {
-
- }
- }
- }
- }
- }
- catch (Exception)
- {
-
- throw;
- }
- }
复制代码 |