npoi吧 关注:95贴子:222
  • 0回复贴,共1

c# npoi 给excel添加图片 不是新增是编辑

只看楼主收藏回复

public static void Main()
{
AddQcCode("D:\\20191010_1714371437.xlsx", "201910090004");
}
public static void AddQcCode(string fileName,string dahName)
{
// 1.设置条形码规格
EncodingOptions encodeOption = new EncodingOptions();
encodeOption.Height = 130; // 必须制定高度、宽度
encodeOption.Width = 240;
// 2.生成条形码图片并保存
ZXing.BarcodeWriter wr = new BarcodeWriter();
wr.Options = encodeOption;
wr.Format = BarcodeFormat.EAN_13; // 条形码规格:EAN13规格:12(无校验位)或13位数字
Bitmap img = wr.Write(dahName); // 生成图片
string filePath ="D:\\"+ dahName+".jpg";
img.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
string excelFileName = fileName;//AppDomain.CurrentDomain.BaseDirectory +
//Log.Debug(excelFileName);
//1.创建EXCEL中的Workbook
IWorkbook myworkbook = new XSSFWorkbook();
//2.创建Workbook中的Sheet
ISheet mysheet = myworkbook.CreateSheet("sheet1");
//第一步:读取图片到byte数组
byte[] bytes = System.IO.File.ReadAllBytes("D:\\" + dahName + ".jpg");
//第二步:将图片添加到workbook中 指定图片格式 返回图片所在workbook->Picture数组中的索引地址(从1开始)
int pictureIdx = myworkbook.AddPicture(bytes, PictureType.JPEG);
//第三步:在sheet中创建画部
//var sheet = myworkbook.GetSheetAt(0);
//IDrawing patriarch = sheet.CreateDrawingPatriarch();
IDrawing patriarch = mysheet.CreateDrawingPatriarch();
//第四步:设置锚点 (在起始单元格的X坐标0-1023,Y的坐标0-255,在终止单元格的X坐标0-1023,Y的坐标0-255,起始单元格行数,列数,终止单元格行数,列数)
IClientAnchor anchor = patriarch.CreateAnchor(0, 0, 0, 0, 0, 0, 2, 2);
//第五步:创建图片
IPicture pict = (XSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);
pict.Resize();
//6.保存
FileStream file = new FileStream(excelFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);//写入流
file.Flush();
// FileStream file = new FileStream(excelFileName,FileMode.Create); //新建
myworkbook.Write(file);
myworkbook = null;
file.Close();
}


IP属地:广东1楼2019-10-10 17:41回复