标签:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Data; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using NPOI.HSSF.UserModel; namespace ConsoleApplication5 { class ExcelHelper { private string fileName = null; private IWorkbook workbook = null; private FileStream fs = null; private bool disposed; public ExcelHelper() {} public ExcelHelper(string filename) { this.fileName = filename; disposed = false; } #region 把Datatable数据导入Excel文件 /// <summary> /// 把Datatable数据导入Excel文件 /// </summary> /// <param name="data">表</param> /// <param name="sheetName">sheet的名称</param> /// <param name="isColumnWritten">是否导入列名</param> /// <returns></returns> public int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten) { int i = 0; int j = 0; int count = 0; ISheet sheet = null; //判断是否存在该文件 if (File.Exists("../../IntroductionToExcel/"+fileName) == false) { //创建文件 File.Create("../../IntroductionToExcel/" + fileName).Close(); } fs = new FileStream("../../IntroductionToExcel/"+fileName, FileMode.Open, FileAccess.ReadWrite); fs.Position=0; //判断Excel版本 if (fileName.IndexOf(".xlsx") > 0)//2007版本 { workbook = new XSSFWorkbook(); } else if (fileName.IndexOf(".xls") > 0)//2003版本 { workbook = new HSSFWorkbook(); } try { if (workbook != null) { sheet = workbook.CreateSheet(sheetName);//创建sheet } else { return -1; } if (isColumnWritten)//是否导入列名 { IRow row = sheet.CreateRow(0);//第一行,索引从0开始 for (j = 0; j < data.Columns.Count; j++) { row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);//导入列名 } count = 1; } else { count = 0; } for (i = 0; i < data.Rows.Count; i++)//循环行 { IRow row = sheet.CreateRow(count); for (j = 0; j < data.Columns.Count; j++)//循环列 { row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());//当前单元格data.Rows[i][j] } ++count; } workbook.Write(fs); return count;//返回导入行数 } catch { return -1; } } #endregion } }
标签:
原文地址:http://www.cnblogs.com/zxxblog/p/4449989.html