查看: 2590|回复: 0

[.NET开发] NPOI导出

发表于 2018-3-22 08:00:01
  1. //导出全部
  2. expertPara = GetExpetPara();
  3. expertPara.BeginIndex = pager.CurrentPageIndex;
  4. expertPara.EndIndex = int.MaxValue;
  5. DataSet ds = ExpertBLL.GetPriMngExpertDate(expertPara);
  6. DataTable dt = ds.Tables[0];
  7. //判断加载哪个模板
  8. string tempath = "~/Templates/专家录入管理表.xls";
  9. //1、获取数据。
  10. using (FileStream file = new FileStream(HttpContext.Current.Server.MapPath(tempath), FileMode.Open, FileAccess.Read))
  11. {
  12. string ReportFileName = Server.MapPath("out.xls");
  13. HSSFWorkbook hssfworkbook = new HSSFWorkbook(file);
  14. HSSFSheet sheet1 = hssfworkbook.GetSheetAt(0) as HSSFSheet;
  15. sheet1.ForceFormulaRecalculation = true;
  16. sheet1.IsPrintGridlines = true;
  17. sheet1.DisplayGridlines = true;
  18. HSSFCellStyle _style = sheet1.Workbook.CreateCellStyle() as HSSFCellStyle;
  19. _style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
  20. _style.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
  21. int rowIndex = 0;
  22. {
  23. rowIndex = 2;
  24. int i = 1;
  25. foreach (DataRow row in ds.Tables[0].Select())
  26. {
  27. int cellIndex = 0;
  28. HSSFRow fr = GetRow(sheet1, rowIndex++);
  29. GetCell(fr, cellIndex++, _style).SetCellValue(i.ToString());
  30. GetCell(fr, cellIndex++, _style).SetCellValue(row["C_Name"].ToString());
  31. GetCell(fr, cellIndex++, _style).SetCellValue(DelHTML(row["C_Sex"].ToString()));
  32. GetCell(fr, cellIndex++, _style).SetCellValue(DelHTML(row["C_WorkUnit"].ToString()));
  33. GetCell(fr, cellIndex++, _style).SetCellValue(row["C_expert_type"].ToString());
  34. GetCell(fr, cellIndex++, _style).SetCellValue(row["C_position"].ToString());
  35. GetCell(fr, cellIndex++, _style).SetCellValue(row["C_title"].ToString());
  36. GetCell(fr, cellIndex++, _style).SetCellValue(row["C_Tel"].ToString());
  37. GetCell(fr, cellIndex++, _style).SetCellValue(row["C_BusinessOutlets"].ToString());
  38. GetCell(fr, cellIndex++, _style).SetCellValue(row["C_BankAccount"].ToString());
  39. i++;
  40. }
  41. sheet1.ForceFormulaRecalculation = true;
  42. using (FileStream filess = File.OpenWrite(ReportFileName))
  43. {
  44. hssfworkbook.Write(filess);
  45. }
  46. System.IO.FileInfo filet = new System.IO.FileInfo(ReportFileName);
  47. Response.Clear();
  48. Response.Charset = "GB2312";
  49. Response.ContentEncoding = System.Text.Encoding.UTF8;
  50. // 添加头信息,为"文件下载/另存为"对话框指定默认文件名
  51. string name = DateTime.Now + ".xls";
  52. Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(name));
  53. // 添加头信息,指定文件大小,让浏览器能够显示下载进度
  54. Response.AddHeader("Content-Length", filet.Length.ToString());
  55. // 指定返回的是一个不能被客户端读取的流,必须被下载
  56. Response.ContentType = "application/ms-excel";
  57. // 把文件流发送到客户端
  58. Response.WriteFile(filet.FullName);
  59. // 停止页面的执行
  60. Response.End();
  61. }
  62. }
复制代码



回复

使用道具 举报