Asp.Net 常用工具类之Office—Excel导入(5)
之前在做一个项目的时候,客户方面只提供了一份简单的Excel文件,且要跟现有数据进行对接。
当时想到的是如果数据量不大,可以Excel一条一条加进去,无奈数据有几十兆!!!
换了一种思维,进行了导入;当时也试了网上各种帮助类,无奈不是这种问题就是那种问题,甚至还有乱码问题。
代码虐我千百遍,我待程序如初恋!
走起,自己写!
分别对现有的Excel文档内容进行了List和DataTable转换:
Excel转DataTable:
/// <summary> /// Excel导入到DataTable /// </summary> /// <param name="filename">文件名称和路径</param> /// <param name="sheetname">表名</param> /// <param name="rowindex">第几行开始</param> /// <returns></returns> public static DataTable ExcelToDataTable(string filename, string sheetname = "", int rowindex = 0) { DataTable dt = new DataTable(); using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read)) { IWorkbook workbook = new HSSFWorkbook(fs); ISheet sheet = !sheetname.IsNullOrEmpty() ? workbook.GetSheet(sheetname) : workbook.GetSheetAt(0); if (sheet != null) { IRow firstrow = sheet.GetRow(rowindex); int cellcount = firstrow.LastCellNum; for (int i = firstrow.FirstCellNum; i < cellcount; ++i) { ICell cell = firstrow.GetCell(i); string cellValue = cell?.StringCellValue; if (cellValue == null) continue; DataColumn column = new DataColumn(cellValue); dt.Columns.Add(column); } rowindex = sheet.FirstRowNum + 1; int rowcount = sheet.LastRowNum; for (int i = rowindex; i <= rowcount; ++i) { IRow row = sheet.GetRow(i); if (row == null) continue; DataRow dataRow = dt.NewRow(); for (int j = row.FirstCellNum; j < cellcount; ++j) { if (row.GetCell(j) != null) dataRow[j] = row.GetCell(j).ToString(); } dt.Rows.Add(dataRow); } } } return dt; }
调用方法:
/// <summary> /// excel导出到dt /// </summary> public static void ToDataTable() { var table = Excel.ExcelToDataTable("dt7.xls"); }
Excel转List:
/// <summary> /// Excel导入List对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="filename">文件名称和路径</param> /// <param name="sheetindex">第几个表,默认0为第一个</param> /// <param name="index">从第几行开始导出,默认为1,不导出表头</param> /// <returns></returns> public static List<T> ExcelToList<T>(string filename, int sheetindex = 0, int index = 1) where T : new() { List<T> list = new List<T>(); using (FileStream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read)) { IWorkbook workbook = new HSSFWorkbook(fileStream); ISheet sheet = workbook.GetSheetAt(sheetindex); int startindex = sheet.FirstRowNum; int endindex = sheet.LastRowNum; if (index == 1) { startindex += 1; endindex += 1; } for (int i = startindex; i < endindex; i++) { var entity = new T(); IRow row = sheet.GetRow(i); if (row.Cells.Count > 0) { int j = 0; foreach (PropertyInfo item in typeof(T).GetProperties()) { if (!Ignore.IgnoreField(item.Name)) continue; ICell cell = row.GetCell(j); if (cell != null) { item.SetValue(entity, ConvertExtension.ChangeType(cell.StringCellValue, item.PropertyType), null); j++; } } list.Add(entity); } } } return list; }
调用方法:
/// <summary> /// excel导出到list /// </summary> public static void ImportExcel2() { var list = Excel.ExcelToList<User>("dt8.xls"); }
OK,各位看官,这一期的文章Excel导入写到这里喏,感谢大家的支持,您的支持是我的动力!
下一期给大家带来的是常用的Word操作,敬请期待!!!