标签:style blog http color 使用 文件
使用NPOI导出Excel代码如下,直接上代码,代码可以直接运行
private static MemoryStream RenderToExcel(DataTable dt) { if (Equals(dt, null)) { return null; } MemoryStream ms = new MemoryStream(); using (dt) { IWorkbook workbook = new HSSFWorkbook(); ISheet sheet = workbook.CreateSheet(); IRow headerRow = sheet.CreateRow(0); foreach (DataColumn column in dt.Columns) { headerRow.CreateCell(column.Ordinal).SetCellValue(column.Caption); } int rowIndex = 1; foreach (DataRow row in dt.Rows) { IRow dataRow = sheet.CreateRow(rowIndex); foreach (DataColumn column in dt.Columns) { dataRow.CreateCell(column.Ordinal).SetCellValue(row[column.Caption].ToString()); } rowIndex++; } workbook.Write(ms); ms.Flush(); ms.Position = 0; } return ms; }
private static void SaveToFile(MemoryStream ms, string dirPath, string fileName) { if (string.IsNullOrEmpty(dirPath) || string.IsNullOrEmpty(fileName)) { return; } if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } using (FileStream fs = new FileStream(string.Format("{0}{1}", dirPath, fileName), FileMode.Create)) { byte[] data = ms.ToArray(); fs.Write(data, 0, data.Length); fs.Flush(); data = null; } }
public static void SaveExcel(DataTable dt, string dirPath, string fileName) { SaveToFile(RenderToExcel(dt), dirPath, fileName); }
说明:因为使用的是第三方的,需要引入dll文件
请到http://npoi.codeplex.com/releases/view/115353下载npoi,有源码,有编译好的dll文件,下载好以后需要引入"NPOI.dll"
标签:style blog http color 使用 文件
原文地址:http://www.cnblogs.com/bygrace/p/3798842.html