C# 使用Workbook在excel中插入由Byte[]转成的图片
时间: 2023-12-12 09:02:37 浏览: 186
可以使用以下代码将一个 Byte 数组插入到 Excel 工作表中:
```
using Excel = Microsoft.Office.Interop.Excel;
byte[] imageBytes = // 从某处获取图片的 Byte 数组
// 创建 Excel 对象
Excel.Application excel = new Excel.Application();
Excel.Workbook workbook = excel.Workbooks.Add();
Excel.Worksheet worksheet = workbook.Worksheets[1];
// 将 Byte 数组转换为 Image 对象
System.IO.MemoryStream ms = new System.IO.MemoryStream(imageBytes);
System.Drawing.Image image = System.Drawing.Image.FromStream(ms);
// 将 Image 对象插入到 Excel 工作表中
Excel.Range range = worksheet.Cells[1, 1] as Excel.Range;
Excel.Pictures pictures = worksheet.Pictures(System.Type.Missing) as Excel.Pictures;
Excel.Picture picture = pictures.Insert(image, range) as Excel.Picture;
// 调整图片大小
picture.ShapeRange.LockAspectRatio = Microsoft.Office.Core.MsoTriState.msoFalse;
picture.ShapeRange.Width = 200;
picture.ShapeRange.Height = 200;
// 保存 Excel 文件
workbook.SaveAs("path/to/file.xlsx");
// 关闭 Excel 对象
workbook.Close();
excel.Quit();
```
阅读全文