隐藏

.NET用NPOI组件将图片文件写到EXCEL中

发布:2023/3/25 0:31:50作者:管理员 来源:本站 浏览次数:329

先看效果:


再看代码:



private void button1_Click(object sender, EventArgs e)


     {


         ///图片文件全路径  E:\11\DKSG9869_1.jpg


         string path = txtPath.Text.Trim();


         int rowIndex = 0;//第一行


         int colIndex = 1;//第二列


         ///创建工作薄hssfworkbook


         HSSFWorkbook hssfworkbook = new HSSFWorkbook();


         ///在工作薄hssfworkbook的基础上创建工作表Ssss


         HSSFSheet sheet = hssfworkbook.CreateSheet("Ssss");


         ///在工作表Ssss的基础上创建行row


         HSSFRow row = sheet.CreateRow(rowIndex);


         ///设置行的高度


         row.Height = 1020;


         ///行row的基础上创建单元格0(也称第一列)


         HSSFCell cell0 = row.CreateCell(0);


         ///设置单元格第一列的默认宽度


         cell0.Sheet.DefaultColumnWidth = 1000;


         ///设置单元格第一列的默认高度


         cell0.Sheet.DefaultRowHeight = 1000;


         ///给单元格(第一列)写值


         cell0.SetCellValue("NPOI");


         


         ///行row的基础上创建单元格1(也称第二列)


         HSSFCell cell1 = row.CreateCell(colIndex);


         ///设置单元格第二列的默认宽度


         cell1.Sheet.DefaultColumnWidth = 1000;


         ///设置单元格第二列的默认高度


         cell1.Sheet.DefaultRowHeight = 1000;


         cell1.Sheet.CreateDrawingPatriarch().CreatePicture(new HSSFClientAnchor(0, 0, 1010, 252, colIndex, rowIndex, colIndex, rowIndex), hssfworkbook.AddPicture(System.IO.File.ReadAllBytes(path), HSSFWorkbook.PICTURE_TYPE_JPEG)).LineStyle = HSSFPicture.LINESTYLE_NONE;


         FileStream file = new FileStream(@"1.xls", FileMode.Create);


         hssfworkbook.Write(file);


         file.Close();


     }




不用说了吧,重在这句


1


cell1.Sheet.CreateDrawingPatriarch().CreatePicture(new HSSFClientAnchor(0, 0, 1010, 252, colIndex, rowIndex, colIndex, rowIndex), hssfworkbook.AddPicture(System.IO.File.ReadAllBytes(path), HSSFWorkbook.PICTURE_TYPE_JPEG)).LineStyle = HSSFPicture.LINESTYLE_NONE;