Rumah > Soal Jawab > teks badan
要建立一个三列的excel表格,最后一列是个二维码,使用NPOI写完之后,导出的死活打不开,不知道代码哪里错了,麻烦各位帮忙看看代码哪里错了,不甚感激。
public static void CreateImageExcel(List<string> links) { //创建工作薄 HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet("Sheet1"); //填充列标题以及样式 int rowsNum = 0; //行号 HSSFRow headerRow = (HSSFRow)sheet.CreateRow(rowsNum); string strQrCodePath = ""; headerRow.CreateCell(0, CellType.String).SetCellValue("编号"); headerRow.CreateCell(1, CellType.String).SetCellValue("链接"); headerRow.CreateCell(2, CellType.String).SetCellValue("二维码"); HSSFRow row = null; rowsNum = 1; //行号,从第2行开始 foreach (var link in Links) { //写入字段值 row = (HSSFRow)sheet.CreateRow(rowsNum); row.CreateCell(0, CellType.String).SetCellValue(rowsNum); row.CreateCell(1, CellType.String).SetCellValue(Link); row.CreateCell(2, CellType.Blank).SetCellValue(""); strQrCodePath = CommonHelper.CreateQRCode(Configer.GetAppSetting<string>("siteUrl") + "/p/" + item.Link, 8, 4); byte[] bytes = System.IO.File.ReadAllBytes(strQrCodePath); int pictureIdx = workbook.AddPicture(bytes, PictureType.PNG); HSSFPatriarch patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch(); HSSFClientAnchor anchor = new HSSFClientAnchor(0, 10, 1023, 0, 2, rowsNum, 2, rowsNum); HSSFPicture pict = (HSSFPicture)patriarch.CreatePicture(anchor, pictureIdx); pict.Resize(); rowsNum++; //删除二维码 if (System.IO.File.Exists(strQrCodePath)) { System.IO.File.Delete(strQrCodePath); } } using (MemoryStream ms = new MemoryStream()) { workbook.Write(ms); ms.Flush(); ms.Position = 0; // 设置编码和附件格式 string fileName = model.Channel.Name + "_" + DateTime.Now.ToString("yyyy-MM-dd-HHmmss") + ".xlsx";//客户端保存的文件名 System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"; System.Web.HttpContext.Current.Response.ContentEncoding = Encoding.UTF8; System.Web.HttpContext.Current.Response.Charset = ""; System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8)); System.Web.HttpContext.Current.Response.BinaryWrite(ms.GetBuffer()); ms.Close(); ms.Dispose(); System.Web.HttpContext.Current.Response.End(); } }
欧阳克2016-11-12 11:38:05
//创建工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
应该是这句代码的问题HSSFWorkbook创建的工作簿只支持2003格式的,即xls
要想导出xlsx的格式,应该用XSSFWorkbook对象,例如IWorkbook workbook = new XSSFWorkbook();
我今天在做导入也遇到这个问题,通过上面的方式解决的