当前位置:   article > 正文

利用NPOI开源的读写Excel、WORD等微软OLE2组件读写execl,控制样式或单元格

npoi 读取 ole2
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.UI;
  6. using System.Web.UI.WebControls;
  7. //add
  8. using System.Data;
  9. using System.IO;
  10. using NPOI;
  11. using NPOI.HSSF.UserModel;
  12. public partial class ExeclOperation : System.Web.UI.Page
  13. {
  14. #region 页面加载
  15. protected void Page_Load(object sender, EventArgs e)
  16. {
  17. DataTable dt = ReadExcelToDataTable("~/xls/demo001.xls", 0, 0);
  18. ViewState["dtview"] = dt;
  19. GridView1.DataSource = dt;
  20. GridView1.DataBind();
  21. }
  22. #endregion
  23. #region DS直接生成Execl
  24. protected void btnExport_Click(object sender, EventArgs e)
  25. {
  26. DataSet ds = new DataSet();
  27. DataTable dt = ViewState["dtview"] as DataTable;
  28. ds.Tables.Add(dt);
  29. bool success = ExportExcelByDataSet(ds, "~/xls/", "demo.xls", "这是测试数据");
  30. if (success)
  31. {
  32. ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), "alert1", "alert('生成execl文件成功')", true);
  33. }
  34. else
  35. {
  36. ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), "alert2", "alert('生成execl文件失败')", true);
  37. }
  38. }
  39. #endregion
  40. #region GridView自动列适应,不换行
  41. protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
  42. {
  43. if (e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Header)
  44. {
  45. TableCellCollection cells1 = e.Row.Cells;
  46. for (int i = 0; i < cells1.Count; i++)
  47. {
  48. cells1[i].Wrap = false;
  49. }
  50. }
  51. }
  52. #endregion
  53. #region DataSet与Execl互转
  54. /// <summary>
  55. /// 传入ds直接生成excel文件
  56. /// </summary>
  57. /// <param name="ds">DataSet</param>
  58. /// <param name="strPath">文件路径</param>
  59. /// <param name="strFileName">文件名</param>
  60. /// <param name="ReportHeader">execl表头</param>
  61. /// <returns></returns>
  62. public static bool ExportExcelByDataSet(DataSet ds, string strPath, string strFileName, string ReportHeader = "")
  63. {
  64. //NPOI
  65. HSSFWorkbook hssfworkbook2 = new HSSFWorkbook();
  66. HSSFSheet sheet = (HSSFSheet)hssfworkbook2.CreateSheet("sheet1");
  67. //定义字体 font 设置字体类型和大小
  68. HSSFFont font = (HSSFFont)hssfworkbook2.CreateFont();
  69. font.FontName = "宋体";
  70. font.FontHeightInPoints = 11;
  71. //定义单元格格式;单元格格式style1 为font的格式
  72. HSSFCellStyle style1 = (HSSFCellStyle)hssfworkbook2.CreateCellStyle();
  73. style1.SetFont(font);
  74. style1.Alignment = NPOI.SS.UserModel.HorizontalAlignment.LEFT;
  75. HSSFCellStyle style2 = (HSSFCellStyle)hssfworkbook2.CreateCellStyle();
  76. style2.SetFont(font);
  77. style2.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER;
  78. style2.BorderBottom = NPOI.SS.UserModel.BorderStyle.THIN;
  79. style2.BorderLeft = NPOI.SS.UserModel.BorderStyle.THIN;
  80. style2.BorderRight = NPOI.SS.UserModel.BorderStyle.THIN;
  81. style2.BorderTop = NPOI.SS.UserModel.BorderStyle.THIN;
  82. //style2.WrapText = true;
  83. //设置大标题行
  84. int RowCount = 0;
  85. int arrFlag = 0;
  86. string TileName1 = "";
  87. string TileName2 = "";
  88. string s = ReportHeader;
  89. string[] sArray = s.Split('|');
  90. if (ReportHeader != "")
  91. {
  92. foreach (string i in sArray)
  93. {
  94. string str1 = i.ToString();
  95. string[] subArray = str1.Split('@');
  96. foreach (string k in subArray)
  97. {
  98. Console.WriteLine(k.ToString());
  99. if (arrFlag == 0)
  100. {
  101. TileName1 = k.ToString();
  102. }
  103. else
  104. {
  105. TileName2 = k.ToString();
  106. }
  107. arrFlag = arrFlag + 1;
  108. }
  109. HSSFRow row0 = (HSSFRow)sheet.CreateRow(RowCount); //创建报表表头标题 8列
  110. row0.CreateCell(0).SetCellValue(TileName1);
  111. row0.CreateCell(1).SetCellValue(TileName2);
  112. RowCount = RowCount + 1;
  113. arrFlag = 0;
  114. }
  115. }
  116. //设置全局列宽和行高
  117. sheet.DefaultColumnWidth = 14;//全局列宽
  118. sheet.DefaultRowHeightInPoints = 15;//全局行高
  119. //设置标题行数据
  120. int a = 0;
  121. string mColumnName = "";
  122. HSSFRow row1 = (HSSFRow)sheet.CreateRow(RowCount); //创建报表表头标题 8列
  123. for (int k = 0; k < ds.Tables[0].Columns.Count; k++)
  124. {
  125. mColumnName = ds.Tables[0].Columns[k].ColumnName.ToString();
  126. row1.CreateCell(a).SetCellValue(mColumnName);
  127. row1.Cells[a].CellStyle = style2;
  128. a++;
  129. }
  130. //填写ds数据进excel
  131. for (int i = 0; i < ds.Tables[0].Rows.Count; i++)//写6行数据
  132. {
  133. HSSFRow row2 = (HSSFRow)sheet.CreateRow(i + RowCount + 1);
  134. int b = 0;
  135. for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
  136. {
  137. string DgvValue = "";
  138. DgvValue = ds.Tables[0].Rows[i][j].ToString(); ;
  139. row2.CreateCell(b).SetCellValue(DgvValue);
  140. b++;
  141. }
  142. }
  143. //获取用户选择路径
  144. string ReportPath = HttpContext.Current.Server.MapPath(strPath + strFileName);
  145. //创建excel
  146. System.IO.FileStream file3 = new FileStream(ReportPath, FileMode.Create);
  147. hssfworkbook2.Write(file3);
  148. file3.Close();
  149. return true;
  150. }
  151. /// <summary>
  152. /// 用NPOI直接读取excel返回DataTable
  153. /// </summary>
  154. /// <param name="ExcelFileStream">文件流</param>
  155. /// <param name="SheetIndex">Sheet序号</param>
  156. /// <param name="StartRowIndex">开始行号</param>
  157. /// <returns></returns>
  158. public static DataTable ReadExcelToDataTable(Stream ExcelFileStream, int SheetIndex, int StartRowIndex)
  159. {
  160. HSSFWorkbook workbook = new HSSFWorkbook(ExcelFileStream);
  161. HSSFSheet sheet = (HSSFSheet)workbook.GetSheetAt(SheetIndex);
  162. DataTable table = new DataTable();
  163. HSSFRow headerRow = (HSSFRow)sheet.GetRow(StartRowIndex);
  164. int cellCount = headerRow.LastCellNum;
  165. for (int i = headerRow.FirstCellNum; i < cellCount; i++)
  166. {
  167. DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
  168. table.Columns.Add(column);
  169. }
  170. int rowCount = sheet.LastRowNum;
  171. for (int i = (StartRowIndex + 1); i <= sheet.LastRowNum; i++)
  172. {
  173. HSSFRow row = (HSSFRow)sheet.GetRow(i);
  174. DataRow dataRow = table.NewRow();
  175. for (int j = row.FirstCellNum; j < cellCount; j++)
  176. {
  177. if (row.GetCell(j) != null)
  178. dataRow[j] = row.GetCell(j).ToString();
  179. }
  180. table.Rows.Add(dataRow);
  181. }
  182. ExcelFileStream.Close();
  183. workbook = null;
  184. sheet = null;
  185. return table;
  186. }
  187. /// <summary>
  188. /// 用NPOI直接读取excel返回DataTable
  189. /// </summary>
  190. /// <param name="FilePath">文件路径</param>
  191. /// <param name="SheetIndex">Sheet序号</param>
  192. /// <param name="StartRowIndex">开始行号</param>
  193. /// <returns></returns>
  194. public static DataTable ReadExcelToDataTable(string FilePath, int SheetIndex, int StartRowIndex)
  195. {
  196. DataSet ds = new DataSet();
  197. FileStream fs = File.Open(HttpContext.Current.Server.MapPath(FilePath), FileMode.Open);
  198. DataTable dt = ReadExcelToDataTable(fs, SheetIndex, StartRowIndex);
  199. return dt;
  200. }
  201. #endregion
  202. }

 

  1. #region DataSet与Execl互转
  2. /// <summary>
  3. /// 传入ds直接生成excel文件
  4. /// </summary>
  5. /// <param name="ds">DataSet</param>
  6. /// <param name="strPath">文件路径</param>
  7. /// <param name="ReportHeader">execl表头</param>
  8. /// <returns></returns>
  9. public static bool ExportExcelByDataSet(DataSet ds, string strPath, string ReportHeader = "")
  10. {
  11. //NPOI
  12. HSSFWorkbook hssfworkbook2 = new HSSFWorkbook();
  13. #region 循环开始
  14. for (int p = 0; p < ds.Tables.Count; p++)
  15. {
  16. int t = p + 1;
  17. HSSFSheet sheet = (HSSFSheet)hssfworkbook2.CreateSheet("page" + t);
  18. //定义字体 font 设置字体类型和大小
  19. HSSFFont font = (HSSFFont)hssfworkbook2.CreateFont();
  20. font.FontName = "宋体";
  21. font.FontHeightInPoints = 11;
  22. //定义单元格格式;单元格格式style1 为font的格式
  23. HSSFCellStyle style1 = (HSSFCellStyle)hssfworkbook2.CreateCellStyle();
  24. style1.SetFont(font);
  25. style1.Alignment = NPOI.SS.UserModel.HorizontalAlignment.LEFT;
  26. HSSFCellStyle style2 = (HSSFCellStyle)hssfworkbook2.CreateCellStyle();
  27. style2.SetFont(font);
  28. style2.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER;
  29. style2.BorderBottom = NPOI.SS.UserModel.BorderStyle.THIN;
  30. style2.BorderLeft = NPOI.SS.UserModel.BorderStyle.THIN;
  31. style2.BorderRight = NPOI.SS.UserModel.BorderStyle.THIN;
  32. style2.BorderTop = NPOI.SS.UserModel.BorderStyle.THIN;
  33. //style2.WrapText = true;
  34. //设置大标题行
  35. int RowCount = 0;
  36. int arrFlag = 0;
  37. string TileName1 = "";
  38. string TileName2 = "";
  39. string s = ReportHeader;
  40. string[] sArray = s.Split('|');
  41. if (ReportHeader != "")
  42. {
  43. foreach (string i in sArray)
  44. {
  45. string str1 = i.ToString();
  46. string[] subArray = str1.Split('@');
  47. foreach (string k in subArray)
  48. {
  49. Console.WriteLine(k.ToString());
  50. if (arrFlag == 0)
  51. {
  52. TileName1 = k.ToString();
  53. }
  54. else
  55. {
  56. TileName2 = k.ToString();
  57. }
  58. arrFlag = arrFlag + 1;
  59. }
  60. HSSFRow row0 = (HSSFRow)sheet.CreateRow(RowCount); //创建报表表头标题 8列
  61. row0.CreateCell(0).SetCellValue(TileName1);
  62. row0.CreateCell(1).SetCellValue(TileName2);
  63. RowCount = RowCount + 1;
  64. arrFlag = 0;
  65. }
  66. }
  67. //设置全局列宽和行高
  68. sheet.DefaultColumnWidth = 14;//全局列宽
  69. sheet.DefaultRowHeightInPoints = 15;//全局行高
  70. //设置标题行数据
  71. int a = 0;
  72. string mColumnName = "";
  73. HSSFRow row1 = (HSSFRow)sheet.CreateRow(RowCount); //创建报表表头标题 8列
  74. for (int k = 0; k < ds.Tables[p].Columns.Count; k++)
  75. {
  76. mColumnName = ds.Tables[p].Columns[k].ColumnName.ToString();
  77. row1.CreateCell(a).SetCellValue(mColumnName);
  78. row1.Cells[a].CellStyle = style2;
  79. a++;
  80. }
  81. //填写ds数据进excel
  82. for (int i = 0; i < ds.Tables[p].Rows.Count; i++)//写6行数据
  83. {
  84. HSSFRow row2 = (HSSFRow)sheet.CreateRow(i + RowCount + 1);
  85. int b = 0;
  86. for (int j = 0; j < ds.Tables[p].Columns.Count; j++)
  87. {
  88. string DgvValue = "";
  89. DgvValue = ds.Tables[p].Rows[i][j].ToString(); ;
  90. row2.CreateCell(b).SetCellValue(DgvValue);
  91. b++;
  92. }
  93. }
  94. }
  95. #endregion
  96. //获取用户选择路径
  97. string ReportPath = (strPath);
  98. //创建excel
  99. System.IO.FileStream file3 = new FileStream(ReportPath, FileMode.Create);
  100. hssfworkbook2.Write(file3);
  101. file3.Close();
  102. return true;
  103. }
  104. /// <summary>
  105. /// 用NPOI直接读取excel返回DataSet
  106. /// </summary>
  107. /// <param name="ExcelFileStream">FileStream fs = File.Open(dlg.FileName, FileMode.Open);</param>
  108. /// <param name="SheetCount">sheet数量</param>
  109. /// <returns></returns>
  110. public static DataSet ReadExcelToDataSet(Stream ExcelFileStream,int SheetCount)
  111. {
  112. HSSFWorkbook workbook = new HSSFWorkbook(ExcelFileStream);
  113. DataSet ds = new DataSet();
  114. for (int k = 0; k < SheetCount; k++)
  115. {
  116. HSSFSheet sheet = (HSSFSheet)workbook.GetSheetAt(k);
  117. DataTable table = new DataTable("table" + k);
  118. HSSFRow headerRow = (HSSFRow)sheet.GetRow(0);
  119. int cellCount = headerRow.LastCellNum;
  120. for (int i = headerRow.FirstCellNum; i < cellCount; i++)
  121. {
  122. string columnName = headerRow.GetCell(i).StringCellValue;
  123. DataColumn column = new DataColumn(columnName);
  124. if (!table.Columns.Contains(columnName))
  125. {
  126. table.Columns.Add(column);
  127. }
  128. }
  129. int rowCount = sheet.LastRowNum;
  130. for (int i = (0 + 1); i <= sheet.LastRowNum; i++)
  131. {
  132. HSSFRow row = (HSSFRow)sheet.GetRow(i);
  133. DataRow dataRow = table.NewRow();
  134. for (int j = row.FirstCellNum; j < cellCount; j++)
  135. {
  136. if (row.GetCell(j) != null)
  137. dataRow[j] = row.GetCell(j);
  138. }
  139. table.Rows.Add(dataRow);
  140. }
  141. sheet = null;
  142. ds.Tables.Add(table);
  143. }
  144. workbook = null;
  145. ExcelFileStream.Close();
  146. return ds;
  147. }
  148. #endregion


转载于:https://www.cnblogs.com/smartsmile/archive/2012/10/25/6234403.html

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

闽ICP备14008679号