当前位置:   article > 正文

ExcelHelper 导出导入代码块_excelhelper::exportdata使用

excelhelper::exportdata使用

前段时间写了几个关于导入导出的功能,现在空闲下来了,把主要代码块贴出来。

感觉没有什么好讲的,相信很多地方都能看到类似的源码。

只是用习惯了,会比较方便,所以贴出来,也方便以后查看。

以后遇到这样可以重复利用的代码块,会多整理的。(#^.^#)

  1. /// <summary>
  2. /// 导入excel生成DataTable
  3. /// </summary>
  4. /// <param name="inputStream">Excel文件流</param>
  5. /// <param name="extension">后缀名</param>
  6. /// <returns></returns>
  7. public static DataTable BuildTable(Stream inputStream, string extension)
  8. {
  9. DataTable dt = new DataTable();
  10. try
  11. {
  12. IWorkbook workbook = null;
  13. ISheet sheet = null;
  14. if (Regex.IsMatch(extension, ".*xls$"))
  15. {
  16. workbook = new HSSFWorkbook(inputStream);
  17. sheet = workbook.GetSheetAt(0);
  18. }
  19. else
  20. {
  21. workbook = new XSSFWorkbook(inputStream);
  22. sheet = workbook.GetSheetAt(0);
  23. }
  24. IRow headerRow = sheet.GetRow(0);
  25. int cellCount = headerRow.LastCellNum;
  26. for (int j = 0; j < cellCount; j++)
  27. {
  28. ICell cell = headerRow.GetCell(j);
  29. dt.Columns.Add(cell.ToString());
  30. }
  31. for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
  32. {
  33. IRow row = sheet.GetRow(i);
  34. DataRow dataRow = dt.NewRow();
  35. for (int j = row.FirstCellNum; j < cellCount; j++)
  36. {
  37. var cell = row.GetCell(j);
  38. if (cell != null)
  39. {
  40. //用于转化为日期格式
  41. if (cell.CellType == CellType.Numeric && DateUtil.IsCellDateFormatted(cell))
  42. {
  43. dataRow[j] = cell.DateCellValue.ToString();
  44. }
  45. else
  46. {
  47. dataRow[j] = cell.ToString();
  48. }
  49. }
  50. }
  51. dt.Rows.Add(dataRow);
  52. }
  53. }
  54. catch (Exception ex)
  55. {
  56. // ignored
  57. }
  58. return dt;
  59. }
  1. /// <summary>
  2. /// Web导出
  3. /// </summary>
  4. /// <param name="workbook"></param>
  5. /// <param name="strFileName"></param>
  6. public static void ExportByWeb(HSSFWorkbook workbook, string strFileName)
  7. {
  8. HttpContext curContext = HttpContext.Current;
  9. // 设置编码和附件格式
  10. curContext.Response.ContentType = "application/vnd.ms-excel";
  11. curContext.Response.ContentEncoding = Encoding.UTF8;
  12. curContext.Response.Charset = "";
  13. curContext.Response.AppendHeader("Content-Disposition",
  14. "attachment;filename=" + HttpUtility.UrlEncode(strFileName + ".xls", Encoding.UTF8));
  15. //获取流
  16. MemoryStream ms = CovertToStream(workbook);
  17. //输出
  18. curContext.Response.BinaryWrite(ms.GetBuffer());
  19. curContext.Response.End();
  20. }
  1. /// <summary>
  2. /// 转化流
  3. /// </summary>
  4. /// <param name="workbook"></param>
  5. /// <returns></returns>
  6. private static MemoryStream CovertToStream(HSSFWorkbook workbook)
  7. {
  8. using (MemoryStream ms = new MemoryStream())
  9. {
  10. workbook.Write(ms);
  11. ms.Flush();
  12. ms.Position = 0;
  13. //sheet.Dispose()
  14. //workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheet
  15. return ms;
  16. }
  17. }
  1. /// <summary>
  2. /// 转化为Excel工作本
  3. /// </summary>
  4. /// <param name="dtSource"></param>
  5. /// <param name="strHeaderText"></param>
  6. /// <param name="workbook"></param>
  7. /// <param name="sheet"></param>
  8. /// <returns></returns>
  9. public static HSSFWorkbook DateTaleCovertToWorkBook(DataTable dtSource, string strHeaderText, HSSFWorkbook workbook, ISheet sheet)
  10. {
  11. #region 右击文件 属性信息
  12. {
  13. DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
  14. dsi.Company = "NPOI";
  15. workbook.DocumentSummaryInformation = dsi;
  16. SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
  17. si.Author = "文件作者信息"; //填加xls文件作者信息
  18. si.ApplicationName = "创建程序信息"; //填加xls文件创建程序信息
  19. si.LastAuthor = "最后保存者信息"; //填加xls文件最后保存者信息
  20. si.Comments = "作者信息"; //填加xls文件作者信息
  21. si.Title = "标题信息"; //填加xls文件标题信息
  22. si.Subject = "主题信息";//填加文件主题信息
  23. si.CreateDateTime = DateTime.Now;
  24. workbook.SummaryInformation = si;
  25. }
  26. #endregion
  27. ICellStyle dateStyle = workbook.CreateCellStyle();
  28. IDataFormat format = workbook.CreateDataFormat();
  29. dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
  30. //取得列宽
  31. int[] arrColWidth = new int[dtSource.Columns.Count];
  32. foreach (DataColumn item in dtSource.Columns)
  33. {
  34. arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
  35. }
  36. for (int i = 0; i < dtSource.Rows.Count; i++)
  37. {
  38. for (int j = 0; j < dtSource.Columns.Count; j++)
  39. {
  40. int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;
  41. if (intTemp > arrColWidth[j])
  42. {
  43. arrColWidth[j] = intTemp;
  44. }
  45. }
  46. }
  47. int rowIndex = 0;
  48. foreach (DataRow row in dtSource.Rows)
  49. {
  50. #region 新建表,填充表头,填充列头,样式
  51. if (rowIndex == 65535 || rowIndex == 0)
  52. {
  53. if (rowIndex != 0)
  54. {
  55. sheet = workbook.CreateSheet();
  56. }
  57. #region 列头及样式
  58. {
  59. IRow headerRow = sheet.CreateRow(0);
  60. ICellStyle headStyle = workbook.CreateCellStyle();
  61. headStyle.Alignment = HorizontalAlignment.Left;
  62. headStyle.WrapText = true;
  63. IFont font = workbook.CreateFont();
  64. font.FontHeightInPoints = 10;
  65. //font.Boldweight = 700;
  66. headStyle.SetFont(font);
  67. foreach (DataColumn column in dtSource.Columns)
  68. {
  69. headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
  70. headerRow.GetCell(column.Ordinal).CellStyle = headStyle;
  71. //设置列宽
  72. sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
  73. }
  74. //headerRow.Dispose();
  75. }
  76. #endregion
  77. rowIndex = 1;
  78. }
  79. #endregion
  80. #region 填充内容
  81. IRow dataRow = sheet.CreateRow(rowIndex);
  82. foreach (DataColumn column in dtSource.Columns)
  83. {
  84. ICell newCell = dataRow.CreateCell(column.Ordinal);
  85. string drValue = row[column].ToString();
  86. switch (column.DataType.ToString())
  87. {
  88. case "System.String"://字符串类型
  89. newCell.SetCellValue(drValue);
  90. break;
  91. case "System.DateTime"://日期类型
  92. DateTime dateV;
  93. DateTime.TryParse(drValue, out dateV);
  94. newCell.SetCellValue(dateV);
  95. newCell.CellStyle = dateStyle;//格式化显示
  96. break;
  97. case "System.Boolean"://布尔型
  98. bool boolV = false;
  99. bool.TryParse(drValue, out boolV);
  100. newCell.SetCellValue(boolV);
  101. break;
  102. case "System.Int16"://整型
  103. case "System.Int32":
  104. case "System.Int64":
  105. case "System.Byte":
  106. int intV = 0;
  107. int.TryParse(drValue, out intV);
  108. newCell.SetCellValue(intV);
  109. break;
  110. case "System.Decimal"://浮点型
  111. case "System.Double":
  112. double doubV = 0;
  113. double.TryParse(drValue, out doubV);
  114. newCell.SetCellValue(doubV);
  115. break;
  116. case "System.DBNull"://空值处理
  117. newCell.SetCellValue("");
  118. break;
  119. default:
  120. newCell.SetCellValue("");
  121. break;
  122. }
  123. }
  124. #endregion
  125. rowIndex++;
  126. }
  127. return workbook;
  128. }

完。




 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/216080
推荐阅读
相关标签
  

闽ICP备14008679号