- using System.IO;
- using System.Data;
- using NPOI.HSSF.UserModel;
- using NPOI.SS.UserModel;
- using NPOI.SS.Util;
- namespace SuperCode.Common
- {
- class DataTableToExcel
- {
- /// <summary>
- /// datatabletoexcel
- /// </summary>
- /// <param name="table"></param>
- /// <returns></returns>
- public bool DataTableToExcel(DataTable table)
- {
- if (table != null)//判断是否为null
- {
- if (table.Rows.Count >= 1)//判断是否有记录
- {
- HSSFWorkbook hssfworkbook = new HSSFWorkbook();//创建一个excel
- ISheet s = hssfworkbook.CreateSheet("name");//创建一个工作表
- IRow rowhead = s.CreateRow(0);//创建第一行
- for (int i = 0; i < table.Columns.Count; i++)//循环为第一列赋值
- {
- rowhead.CreateCell(i).SetCellValue(table.Columns[i].ColumnName);
- }
- for (int i = 0; i < table.Rows.Count; i++)//循环为单元格赋值
- {
- DataRow row = table.Rows[i];
- IRow irow = s.CreateRow(i + 1);
- for (int b = 0; b < table.Columns.Count; b++)
- {
- irow.CreateCell(b).SetCellValue(row[b].ToString());
- }
- }
- FileStream file = new FileStream(@"SuperCode.xls", FileMode.Create);//创建一个文件流
- hssfworkbook.Write(file);//将excel内容写入文件流中
- file.Close();//关闭
- return true;
- }
- else
- {
- return false;
- }
- }
- else
- {
- return false;
- }
- }
- }
- }
复制代码 |