1、首先引用NPOI
2、本例用到的引用
3、在Controller里面添加導出方法
public ActionResult ExportMsgData(string term) { //為list賦值 MsgListToExcelForXLSXModel1(list, ""); return Content(""); }
4、導出基礎方法
public void MsgListToExcelForXLSXModel1(List<BackMsgProblemList> dt, string file) { XSSFWorkbook xssfworkbook = new XSSFWorkbook(); ISheet sheet = xssfworkbook.CreateSheet("Test"); DataTable tblDatas = new DataTable("Datas"); DataColumn dc = null; //賦值給dc,是便於對每一個datacolumn的操作 dc = tblDatas.Columns.Add("編號", Type.GetType("System.Int32")); dc.AutoIncrement = true;//自動增加 dc.AutoIncrementSeed = 1;//起始為1 dc.AutoIncrementStep = 1;//步長為1 dc.AllowDBNull = false;// dc = tblDatas.Columns.Add("問題標題", Type.GetType("System.String")); dc = tblDatas.Columns.Add("問題狀態名稱", Type.GetType("System.String")); dc = tblDatas.Columns.Add("問題圖片一", Type.GetType("System.String")); dc = tblDatas.Columns.Add("問題圖片二", Type.GetType("System.String")); dc = tblDatas.Columns.Add("問題圖片三", Type.GetType("System.String")); dc = tblDatas.Columns.Add("問題圖片四", Type.GetType("System.String")); dc = tblDatas.Columns.Add("問題圖片五", Type.GetType("System.String")); dc = tblDatas.Columns.Add("問題圖片六", Type.GetType("System.String")); dc = tblDatas.Columns.Add("報驗圖片一", Type.GetType("System.String")); dc = tblDatas.Columns.Add("報驗圖片二", Type.GetType("System.String")); dc = tblDatas.Columns.Add("報驗圖片三", Type.GetType("System.String")); dc = tblDatas.Columns.Add("報驗圖片四", Type.GetType("System.String")); dc = tblDatas.Columns.Add("報驗圖片五", Type.GetType("System.String")); dc = tblDatas.Columns.Add("報驗圖片六", Type.GetType("System.String")); dc = tblDatas.Columns.Add("復檢圖片一", Type.GetType("System.String")); dc = tblDatas.Columns.Add("復檢圖片二", Type.GetType("System.String")); dc = tblDatas.Columns.Add("復檢圖片三", Type.GetType("System.String")); dc = tblDatas.Columns.Add("復檢圖片四", Type.GetType("System.String")); dc = tblDatas.Columns.Add("復檢圖片五", Type.GetType("System.String")); dc = tblDatas.Columns.Add("復檢圖片六", Type.GetType("System.String")); //表頭 IRow row = sheet.CreateRow(0); for (int i = 0; i < tblDatas.Columns.Count; i++) { ICell cell = row.CreateCell(i); cell.SetCellValue(tblDatas.Columns[i].ColumnName); //自動適應寬度 sheet.AutoSizeColumn(i); sheet.SetColumnWidth(i, sheet.GetColumnWidth(i)); } //數據 for (int i = 0; i < dt.Count(); i++) { IRow row1 = sheet.CreateRow(i + 1); ICell cell = row1.CreateCell(0); cell.SetCellValue(i + 1); cell = row1.CreateCell(1); cell.SetCellValue(dt[i].RIP_Name); cell = row1.CreateCell(2); cell.SetCellValue(dt[i].PB_AllName); var arry = dt[i].PB_AllName.Split('>'); cell = row1.CreateCell(3); cell.SetCellValue(arry.Length > 0 ? arry[0] : ""); cell = row1.CreateCell(4); cell.SetCellValue(arry.Length > 1 ? arry[1] : ""); cell = row1.CreateCell(5); cell.SetCellValue(arry.Length > 2 ? arry[2] : ""); cell = row1.CreateCell(6); cell.SetCellValue(arry.Length > 3 ? arry[3] : ""); cell = row1.CreateCell(7); cell.SetCellValue(dt[i].AName); cell = row1.CreateCell(8); cell.SetCellValue(dt[i].BD_Name); cell = row1.CreateCell(9); cell.SetCellValue(dt[i].U_Name); cell = row1.CreateCell(10); cell.SetCellValue(dt[i].H_Code); cell = row1.CreateCell(11); cell.SetCellValue(dt[i].RIP_DistributName); cell = row1.CreateCell(12); cell.SetCellValue(dt[i].RIP_SeverityName); cell = row1.CreateCell(13); cell.SetCellValue(dt[i].HCIC_AddDateStr); cell = row1.CreateCell(14); cell.SetCellValue(dt[i].RectificationNum.ToString()); cell = row1.CreateCell(15); cell.SetCellValue(dt[i].QuestionStateName); if (dt[i].ContentAccListForCreate != null && dt[i].ContentAccListForCreate.Count > 0) { MsgInsetImg(sheet, row1, dt, i, xssfworkbook, dt[i].ContentAccListForCreate, 16); } if (dt[i].ContentAccListForInspection != null && dt[i].ContentAccListForInspection.Count > 0) { MsgInsetImg(sheet, row1, dt, i, xssfworkbook, dt[i].ContentAccListForInspection, 22); } if (dt[i].ContentAccListForCheck != null && dt[i].ContentAccListForCheck.Count > 0) { MsgInsetImg(sheet, row1, dt, i, xssfworkbook, dt[i].ContentAccListForCheck, 28); } } /*不能使用如下方法生成Excel,因為在xssfworkbook.Write(stream);操作后會關閉流,導致報錯【不能操作已關閉的流】*/ ////轉為字節數組 //MemoryStream stream = new MemoryStream(); //xssfworkbook.Write(stream); //var buf = stream.ToArray(); ////保存為Excel文件 //using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write)) //{ // fs.Write(buf, 0, buf.Length); // fs.Flush(); //} /*可以使用下面方式導出-這里數據量多會報錯【發現XX.xlsx中部分內容有問題,是否讓我們盡量嘗試恢復】*/ //MemoryStream stream = new MemoryStream(); //xssfworkbook.Write(stream); //Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xlsx", DateTime.Now.ToString("yyyyMMddHHmmssfff"))); //Response.BinaryWrite(stream.ToArray()); //xssfworkbook = null; //stream.Close(); //stream.Dispose(); /*最終推薦下面方式*/ HttpContext curContext = HttpContext.Current; MemoryStream ms = new MemoryStream(); xssfworkbook.Write(ms); curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("aaa.xlsx", Encoding.UTF8) + ".xlsx"); curContext.Response.AddHeader("Content-Length", ms.ToArray().Length.ToString()); curContext.Response.ContentEncoding = Encoding.UTF8; curContext.Response.BinaryWrite(ms.ToArray()); ms.Close(); ms.Dispose(); curContext.Response.End(); }
5、插入圖片方法
private void MsgInsetImg(ISheet sheet, IRow row1, List<BackMsgProblemList> dt, int i, XSSFWorkbook xssfworkbook, List<string> ContentAccList, int colnum) { for (int j = 0; j < 6; j++) { //設置圖片那的寬高 sheet.SetColumnWidth(colnum + j, 5845); row1.Height = 1731; if (ContentAccList.Count <= j) { break; } var dPath = ImageShow + ContentAccList[j]; try { System.Drawing.Image imgOutput = System.Drawing.Bitmap.FromFile(dPath); System.Drawing.Image img = imgOutput.GetThumbnailImage(160, 115, null, IntPtr.Zero); //圖片轉換為文件流 MemoryStream ms = new MemoryStream(); img.Save(ms, ImageFormat.Bmp); BinaryReader br = new BinaryReader(ms); var picBytes = ms.ToArray(); ms.Close(); //插入圖片 if (picBytes != null && picBytes.Length > 0) { var rows = i + 1; var cols = colnum + j; /* Add Picture to Workbook, Specify picture type as PNG and Get an Index */ int pictureIdx = xssfworkbook.AddPicture(picBytes, NPOI.SS.UserModel.PictureType.PNG); //添加圖片 /* Create the drawing container */ XSSFDrawing drawing = (XSSFDrawing)sheet.CreateDrawingPatriarch(); /* Create an anchor point */ XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, cols, rows, 1, 3); /* Invoke createPicture and pass the anchor point and ID */ XSSFPicture picture = (XSSFPicture)drawing.CreatePicture(anchor, pictureIdx); /* Call resize method, which resizes the image */ picture.Resize(); picBytes = null; } } catch (Exception ex) { log.Fatal("--圖片導出失敗:當前文件路徑:" + dPath); } } }
6、導出成果
說明:這里采用的是Excel2007以上版本即:XSSFWorkbook,目前XSSFWorkbook版本的資料較少,希望能幫助大家。
備注:excel寬高采用的不是像素,經過計算大約為寬:36.53125=1像素 高:15.05217391304348=1像素