1.新建TestClass类示例,导入类TestClass类的模板数据,其他类可通用该导入方法
1 public class TestClass 2 { 3 public string code { get; set; } 4 public string name { get; set; } 5 public string description { get; set; } 6 }
2.新建Excel导入模板,模板第2行为类中的字段名称,一一对应

3.封装工具类ExcelHelper提供静态方法GetEntityFromExcel<T>导入时调用
获取单元格的值
1 /// <summary> 2 /// 获取单元格的值 3 /// </summary> 4 /// <param name="cell"></param> 5 /// <param name="sheet"></param> 6 /// <returns></returns> 7 private static string GetCellValue(ICell cell, ISheet sheet) 8 { 9 string ret = ""; 10 11 if (cell != null) 12 { 13 switch (cell.CellType) 14 { 15 case CellType.Blank: 16 break; 17 case CellType.Numeric: 18 if (DateUtil.IsCellDateFormatted(cell)) 19 { 20 ret = cell.DateCellValue.GetValueOrDefault().ToString("yyyyMMdd"); 21 } 22 else 23 { 24 ret = cell.NumericCellValue.ToString(); 25 } 26 break; 27 case CellType.String: 28 ret = cell.StringCellValue.Trim(); 29 break; 30 case CellType.Formula: 31 try 32 { 33 IFormulaEvaluator evaluator = WorkbookFactory.CreateFormulaEvaluator(sheet.Workbook); 34 var formulaValue = evaluator.EvaluateInCell(cell); 35 if (formulaValue.CellType == CellType.Numeric) 36 ret = formulaValue.NumericCellValue.ToString().Trim(); 37 else if (formulaValue.CellType == CellType.String) 38 ret = formulaValue.StringCellValue.Trim(); 39 } 40 catch (Exception ex) 41 { 42 ret = cell.ToString().Trim(); 43 } 44 break; 45 default: 46 ret = cell.ToString().Trim(); 47 break; 48 } 49 } 50 51 return ret; 52 }
获取一行的值
1 /// <summary> 2 /// 获取一行的值 3 /// </summary> 4 /// <param name="row"></param> 5 /// <param name="sheet"></param> 6 /// <returns></returns> 7 private static string GetDetailFromRow<T>(IRow row, ISheet sheet, ref T detail) 8 { 9 string ret = string.Empty; 10 11 try 12 { 13 //第2行设置对应字段 14 var tempRow = sheet.GetRow(1); 15 16 for (int i = 0; i < tempRow.LastCellNum; i++) 17 { 18 var name = tempRow.GetCell(i).ToString(); 19 20 var property = detail.GetType().GetProperty(name); 21 var properType = property.PropertyType; 22 var underlyingType = Nullable.GetUnderlyingType(properType) ?? properType; 23 24 var value = GetCellValue(row.GetCell(i), sheet).Trim(); 25 26 if (!string.IsNullOrWhiteSpace(value)) 27 { 28 if (underlyingType.Name == "DateTime" || underlyingType.Name == "Date") 29 property.SetValue(detail, Convert.ChangeType(value, underlyingType), null); 30 else 31 property.SetValue(detail, Convert.ChangeType(value, underlyingType), null); 32 } 33 } 34 } 35 catch (Exception ex) 36 { 37 ret = ex.Message; 38 } 39 40 return ret; 41 }
从模板读取EXCEL
1 /// <summary> 2 /// 从模板读取EXCEL 3 /// </summary> 4 /// <param name="stream"></param> 5 /// <param name="ret"></param> 6 /// <returns></returns> 7 public static string GetEntityFromExcel<T>(string filePath,ref List<T> list) 8 { 9 string ret = ""; 10 11 // 处理文件,例如读取或显示 12 FileStream stream = new FileStream(filePath, FileMode.Open); 13 IWorkbook workbook = WorkbookFactory.Create(stream); 14 15 try 16 { 17 ISheet sheet = workbook.GetSheetAt(0); 18 19 if (sheet != null) 20 { 21 IRow row = null; 22 23 for (int i = 2; i <= sheet.LastRowNum; i++) 24 { 25 row = sheet.GetRow(i); 26 27 if (row == null) continue; 28 29 T detail = Activator.CreateInstance<T>(); 30 ret = GetDetailFromRow(row, sheet,ref detail); 31 32 list.Add(detail); 33 } 34 } 35 else 36 { 37 ret = "Excel无内容"; 38 } 39 40 } 41 catch (Exception ex) 42 { 43 ret = ex.Message; 44 } 45 46 return ret; 47 }
4.调用静态类方法实现导入功能
1 OpenFileDialog openFileDialog = new OpenFileDialog(); 2 //openFileDialog.InitialDirectory = "c:\\"; // 设置初始目录 3 openFileDialog.Filter = "txt files (*.xls)|*.xlsx|All files (*.*)|*.*"; // 设置文件过滤器 4 openFileDialog.FilterIndex = 2; 5 openFileDialog.RestoreDirectory = true; 6 7 if (openFileDialog.ShowDialog() == DialogResult.OK) // 显示对话框 8 { 9 // 获取选中的文件路径 10 string filePath = openFileDialog.FileName; 11 12 var list = new List<TestClass>(); 13 var msg = ExcelHelper.GetEntityFromExcel(filePath, ref list); 14 15 if (!string.IsNullOrWhiteSpace(msg)) 16 { 17 MessageBox.Show("导入失败:"+ msg); 18 } 19 else 20 { 21 dataGridView1.DataSource = list; 22 } 23 }
浙公网安备 33010602011771号