1、创建Excel模板
2、安装NPOI管理包
3、创建工作簿 (XLSX和XLS步骤一样,以XLS为例)
IWorkbook workbook = null;
string time = DateTime.Now.ToString("yyyyMMddHHmmss");
string excelTempPath = Application.StartupPath + @"\Excel\分析模板.xls";//分析模板
string path = Application.StartupPath + @"\Excel\分析文件" + time + ".xls";//保存路径
//读取Excel模板
using (FileStream fs = new FileStream(excelTempPath, FileMode.Open, FileAccess.Read))
{
workbook = new HSSFWorkbook(fs);
}//获取sheet模板
ISheet sheet1 = workbook.GetSheetAt(0);
//将DataSet导出为Excel
4、讲datatable数据写入Excel
//将DataSet导出为Excel
int rowCount = dt.Rows.Count;//行数
int columnCount = dt.Columns.Count;//列数//设置列头
IRow row = sheet1.CreateRow(0);//excel第一行设为列头
for (int c = 0; c < columnCount; c++)
{
ICell cell = row.CreateCell(c);
cell.SetCellValue(dt.Columns[c].ColumnName);
}
//设置每行每列的单元格,
for (int i = 0; i < rowCount; i++)
{
row = sheet1.CreateRow(i + 1);
for (int j = 0; j < columnCount; j++)
{
ICell cell = row.CreateCell(j);//excel第二行开始写入数据
if (dt.Rows[i][j].ToString().Length > 0)//判断分数是否为空
{//写入数值类型
cell.SetCellValue((double)Convert.ToDecimal((dt.Rows[i][j])));
}
else
{//写入文本类型
cell.SetCellValue(dt.Rows[i][j].ToString());
}
}
}workbook.SetSheetName(0, dt.TableName);//修改excel页名为datatable表名
5、向文件输出数据
//向outPath输出数据
using (FileStream fs = File.Open(path, FileMode.Create, FileAccess.Write))
{
workbook.Write(fs);//向打开的这个xls文件中写入数据
fs.Close();
}