本人第一篇博文
感谢 https://www.cnblogs.com/hdkn235/p/3440691.html 提供的学习资料
本方式采用的NPOI 详细使用看上面链接文章
此代码在上面链接的中代码稍做修改 把DataTable里面的单元格 遍历 并且判断单元格类型插入excel数据表中
/// <summary> /// Excel下载 /// </summary> /// <param name="Excel_DT">数据源</param> /// <param name="templatefileName">excel模版文件名 .xls</param> /// <param name="DownFileName">下载文件名 .xls</param> public void ExportToExcel(DataTable Excel_DT, string templatefileName,string DownFileName) { #region 加载模板文件到工作簿对象中 //创建工作簿对象 HSSFWorkbook hssfworkbook; //打开模板文件到文件流中 using (FileStream file = new FileStream(HttpContext.Current.Request.PhysicalApplicationPath + @"template/"+ templatefileName, FileMode.Open, FileAccess.Read)) { //将文件流中模板加载到工作簿对象中 hssfworkbook = new HSSFWorkbook(file); } #endregion #region 根据模板设置工作表的内容 //建立一个名为Sheet1的工作表 ISheet sheet1 = hssfworkbook.GetSheet("Sheet1"); IRow ExcelColumn = sheet1.CreateRow(0);//创建首行 int bb = 0;//excel 单元格序号 foreach (DataColumn cc in Excel_DT.Columns)//遍历DataTable列集合 { ICell ExcelCell = ExcelColumn.CreateCell(bb);//创建首行单元格 string columnsstr = cc.ToString(); ExcelCell.SetCellValue(columnsstr); bb++; } int i2 = 1; //将数据添加到表中对应的单元格中,因为行已经创建,不需要重新创建行 for (int i = 0; i < Excel_DT.Rows.Count; i++) { int ii = i+1;//excel 行序号 bb = 0; //excel 单元格序号 IRow ExcelRow = sheet1.CreateRow(ii);//创建行 foreach (DataColumn cc in Excel_DT.Columns) { object cell = Excel_DT.Rows[i][cc]; Type tt = cell.GetType(); ICell ExcelCell = ExcelRow.CreateCell(bb); //创建单元格 switch (tt.Name) //判断Excel_DT item值类型 { case "String": ExcelCell.SetCellValue((string)cell); break; case "DateTime": ExcelCell.SetCellValue((DateTime)cell); break; case "Decimal": decimal dcell = (decimal)cell; ExcelCell.SetCellValue((double)dcell); break; case "Double": ExcelCell.SetCellValue((double)cell); break; case "Int32": int icell = (int)cell; ExcelCell.SetCellValue((double)icell); break; } bb++; } }