C# 读取Excel中的图片,按添加的顺序一一读取,不对应行号

这是在网上整理的代码,copy别人的,读取excel中的图片,不需要和行对应起来,只需要按添加的顺序一一读取

 

private string exclePath = @"D:\picture.xlsx";
private int StartRow = 2; //读的起始行
private int ImgCount = 0;
private void shouBtn_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();//引用Excel对象
Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Add(exclePath);
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开始.
Microsoft.Office.Interop.Excel.Worksheet sheet = workbook.Worksheets[1];//第一张sheet.
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();//得到第一列的名称,作为图片名称
//if (col == 1)
imgName = Guid.NewGuid().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();
if (iData.GetDataPresent(DataFormats.Bitmap))
{
pictureBox1.Image = (Bitmap)iData.GetData(DataFormats.Bitmap); //从内存取值;
pictureBox1.Image.Save(string.Format(@"D:\{0}.jpg", imgName)); //保存。
ImgCount += 1; //保存的图片数加1
}
else
{
pictureBox1.Image = null;
}
}
}
//}
MessageBox.Show("已成功保存" + ImgCount + "张图片!");
workbook.Close(false, null, null);
excel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
}

 

 

posted @ 2012-12-28 23:50  成功在于专注  阅读(2202)  评论(0)    收藏  举报