写入到Excel表格文件当中,导出/导入数据
/// <summary> /// 写入到Excel表格文件当中,导出数据 /// </summary> /// <param name="dt"></param> /// <returns></returns> public bool DataTableToExcel(DataTable dt, string DataFile) { bool result = false; IWorkbook workbook = null; FileStream fs = null; IRow row = null; ISheet sheet = null; ICell cell = null; try { if (dt != null && dt.Rows.Count > 0) { workbook = new HSSFWorkbook(); string NowBOPName = this.CmbBOPName.Text.Trim(); sheet = workbook.CreateSheet(NowBOPName);//创建一个名称为Sheet0的表 int rowCount = dt.Rows.Count;//行数 int columnCount = dt.Columns.Count;//列数 //把A0:C0合并为一个单元格 并赋值 ICell hbcell = sheet.CreateRow(0).CreateCell(0); hbcell.SetCellValue(NowBOPName + "工序"); sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, 2)); //设置样式 居中 字体 ICellStyle hbstyle = workbook.CreateCellStyle(); hbstyle.VerticalAlignment = VerticalAlignment.Center; hbstyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; IFont hbfont = workbook.CreateFont(); hbfont.FontHeight = 15 * 20; hbstyle.SetFont(hbfont); hbcell.CellStyle = hbstyle; //设置列头 row = sheet.CreateRow(1);//excel第一行设为标题,第二行列头 for (int c = 0; c < columnCount; c++) { cell = row.CreateCell(c); cell.SetCellValue(dt.Columns[c].ColumnName); } //设置每行每列的单元格, for (int i = 0; i < rowCount; i++) { row = sheet.CreateRow(i + 2);//excel第三行开始写入数据 for (int j = 0; j < columnCount; j++) { cell = row.CreateCell(j); cell.SetCellValue(dt.Rows[i][j].ToString()); } } using (fs = File.OpenWrite(DataFile)) { workbook.Write(fs);//向打开的这个xls文件中写入数据 result = true; } } return result; } catch (Exception ex) { if (fs != null) { fs.Close(); } return false; } }
/// <summary> /// 将excel导入到datatable /// </summary> /// <param name="filePath">excel路径</param> /// <param name="isColumnName">第一行是否是列名</param> /// <returns>返回datatable</returns> public static DataTable ExcelToDataTable(string filePath, bool isColumnName) { DataTable dataTable = null; FileStream fs = null; DataColumn column = null; DataRow dataRow = null; IWorkbook workbook = null; ISheet sheet = null; IRow row = null; ICell cell = null; int startRow = 0; try { using (fs = File.OpenRead(filePath)) { // 2007版本 if (filePath.IndexOf(".xlsx") > 0) workbook = new XSSFWorkbook(fs); // 2003版本 else if (filePath.IndexOf(".xls") > 0) workbook = new HSSFWorkbook(fs); if (workbook != null) { sheet = workbook.GetSheetAt(0);//读取第一个sheet,当然也可以循环读取每个sheet dataTable = new DataTable(); if (sheet != null) { int rowCount = sheet.LastRowNum;//总行数 if (rowCount > 0) { IRow firstRow = sheet.GetRow(1);//第二行列名 int cellCount = firstRow.LastCellNum;//列数 //构建datatable的列 if (isColumnName) { startRow = 2;//如果第一行是标题,第二行列名,则从第二行开始读取 for (int i = firstRow.FirstCellNum; i < cellCount; ++i) { cell = firstRow.GetCell(i); if (cell != null) { if (cell.StringCellValue != null) { column = new DataColumn(cell.StringCellValue); dataTable.Columns.Add(column); } } } } else { for (int i = firstRow.FirstCellNum; i < cellCount; ++i) { column = new DataColumn("column" + (i + 1)); dataTable.Columns.Add(column); } } //填充行 for (int i = startRow; i <= rowCount; ++i) { row = sheet.GetRow(i); if (row == null) continue; dataRow = dataTable.NewRow(); for (int j = row.FirstCellNum; j < cellCount; ++j)//dataTable.Columns.Count { cell = row.GetCell(j); if (cell == null) { dataRow[j] = ""; } else { //CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,) switch (cell.CellType) { case CellType.Blank: dataRow[j - row.FirstCellNum] = ""; break; case CellType.Numeric: short format = cell.CellStyle.DataFormat; //对时间格式(2015.12.5、2015/12/5、2015-12-5等)的处理 if (format == 14 || format == 31 || format == 57 || format == 58) dataRow[j - row.FirstCellNum] = cell.DateCellValue; else dataRow[j - row.FirstCellNum] = cell.NumericCellValue; break; case CellType.String: dataRow[j - row.FirstCellNum] = cell.StringCellValue; break; case CellType.Formula: //System.Globalization.NumberFormatInfo nfi = new System.Globalization.NumberFormatInfo(); //nfi.NumberDecimalDigits = 2; //short format = cell.CellStyle.Format("{0:F2}", Convert.ToDouble(23, 5235); dataRow[j - row.FirstCellNum] = ((float)cell.NumericCellValue); break; } } } dataTable.Rows.Add(dataRow); } } } } } return dataTable; } catch (Exception ex) { if (fs != null) { fs.Close(); } return null; } }
C#.net. WPF.core 技术交流群 群号205082182,欢迎加入,也可以直接点击左侧和下方的"加入QQ群",直接加入
分类:
C# WINFORM
, C#
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!