不少朋友在做项目的过程中或多或少的都会用到excel导入、导出功能,下面我来给大家介绍一下使用NPOI如何导入、导出excel,
通过代码描述一下npoi的使用方法,希望都够给需要的朋友一点点帮助,也能和大家一起学习一下npoi的使用方法,废话不多说,直接上代码
使用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); }
将Excel中的数据导入到DB中的方法如下
public static DataTable ReadExcelToDataTable(string fileName) { using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { var workbook = default(IWorkbook); if (fileName.IndexOf(".xlsx", StringComparison.OrdinalIgnoreCase) > 0) workbook = new XSSFWorkbook(stream); else workbook = new HSSFWorkbook(stream); var sheet = workbook.GetSheetAt(workbook.ActiveSheetIndex); if (Equals(sheet, null)) { return null; } var dt = new DataTable(); CreateDataColumn(sheet, dt); CreateDataTable(sheet, dt); return dt; } }
private static void CreateDataTable(ISheet sheet, DataTable dt) { for (var i = 1; i < sheet.LastRowNum; i++) { var sheetRow = sheet.GetRow(i); var dataRow = dt.NewRow(); for (var j = 0; j < sheetRow.LastCellNum; j++) { dataRow[j] = sheetRow.GetCell(j).ToString(); } dt.Rows.Add(dataRow); } }
private static void CreateDataColumn(ISheet sheet, DataTable dt) { var firstRow = sheet.GetRow(0); for (var i = 0; i < firstRow.LastCellNum; i++) { var column = new DataColumn(firstRow.GetCell(i).StringCellValue); dt.Columns.Add(column); } }
说明:因为使用的是第三方的,需要引入dll文件
请到http://npoi.codeplex.com/releases/view/115353下载npoi,有源码,有编译好的dll文件。
如果只有导出到Excel的功能,下载好以后只需引入"NPOI.dll"
如果将excel中的数据导入到数据库中,并且需要同时兼容office 2003和office 2007的话,需要引入"NPOI.dll"、"NPOI.OOXML.dll"、"NPOI.OpenXml4net.dll"
如果仅仅需要兼容office 2003只需要引入"NPOI.dll"就可以了
office 2010下我没试过,有兴趣的朋友可以试一下,我所使用的编码环境是.net framework 4.0过低的版本我没试过,不知道以上代码能否正常执行
欢迎加入群:254082423
一起学习讨论asp.net mvc