本篇博客园是被任务所逼,而已有的使用nopi技术的文档技术经验又不支持我需要的应对各种复杂需求的苛刻要求,只能自己造轮子封装了,由于需要应对很多总类型的数据采集需求,因此有了本篇博客的代码封装,下面一点点介绍吧:
收集excel你有没有遇到过一下痛点:
1-需要收集指定行标题位置的数据,我的标题行不一定在第一行。 这个和我的csv的文档需求是一致的
2-需要采集指定单元格位置的数据生成一个对象,而不是一个列表。 这里我的方案是制定一个单元格映射类解决问题。 单元格映射类,支持表达式数据采集(我可能需要一个单元格的数据+另一个单元格的数据作为一个属性等等)
3-应对不规范标题无法转出字符串进行映射时,能不能通过制定标题的列下标建立对应关系,进行列表数据采集呢? 本博客同时支持标题字符串数据采集和标题下标数据采集,这个就牛逼了。
4-存储含有表达式的数据,这个并不是难点,由于很重要,就在这里列一下
5-应对Excel模板文件的数据指定位置填入数据,该位置可能会变动的解决方案。本文为了应对该情况,借助了单元格映射关系,添加了模板参数名的属性处理,可以应对模板文件调整时的位置变动问题。
6-一个能同时处理excel新老版本(.xls和.xlsx),一个指定excel位置保存数据,保存含有表达式的数据,一个可以将多个不同的数据组合存放到一个excel中的需求都可以满足。
痛点大概就是上面这些了,下面写主要代码吧,供大家参考,不过封装的类方法有点多:
本文借助了NPOI程序包做了业务封装:
1-主要封装类-ExcelHelper:
该类包含很多辅助功能:比如自动帮助寻找含有指定标题名所在的位置、表达式元素A1,B2对应单元格位置的解析等等:

using NLog; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; namespace PPPayReportTools.Excel { ////// EXCEL帮助类 /// /// 泛型类 /// 泛型类集合 public class ExcelHelper { private static Logger _Logger = LogManager.GetCurrentClassLogger(); #region 创建工作表 /// /// 将列表数据生成工作表 /// /// 要导出的数据集 /// 键值对集合(键:字段名,值:显示名称) /// 更新时添加:要更新的工作表 /// 指定要创建的sheet名称时添加 /// 读取或插入定制需求时添加 /// public static IWorkbook CreateOrUpdateWorkbook (List tList, Dictionary<string, string> fieldNameAndShowNameDic, IWorkbook workbook = null, string sheetName = "sheet1", ExcelFileDescription excelFileDescription = null) where T : new() { List titleMapperList = ExcelTitleFieldMapper.GetModelFieldMapper (fieldNameAndShowNameDic); workbook = ExcelHelper.CreateOrUpdateWorkbook (tList, titleMapperList, workbook, sheetName, excelFileDescription); return workbook; } /// /// 将列表数据生成工作表(T的属性需要添加:属性名列名映射关系) /// /// 要导出的数据集 /// 更新时添加:要更新的工作表 /// 指定要创建的sheet名称时添加 /// 读取或插入定制需求时添加 /// public static IWorkbook CreateOrUpdateWorkbook (List tList, IWorkbook workbook = null, string sheetName = "sheet1", ExcelFileDescription excelFileDescription = null) where T : new() { List titleMapperList = ExcelTitleFieldMapper.GetModelFieldMapper (); workbook = ExcelHelper.CreateOrUpdateWorkbook (tList, titleMapperList, workbook, sheetName, excelFileDescription); return workbook; } private static IWorkbook CreateOrUpdateWorkbook (List tList, List titleMapperList, IWorkbook workbook, string sheetName, ExcelFileDescription excelFileDescription = null) { //xls文件格式属于老版本文件,一个sheet最多保存65536行;而xlsx属于新版文件类型; //Excel 07 - 2003一个工作表最多可有65536行,行用数字1—65536表示; 最多可有256列,列用英文字母A—Z,AA—AZ,BA—BZ,……,IA—IV表示;一个工作簿中最多含有255个工作表,默认情况下是三个工作表; //Excel 2007及以后版本,一个工作表最多可有1048576行,16384列; if (workbook == null) { workbook = new XSSFWorkbook(); //workbook = new HSSFWorkbook(); } ISheet worksheet = null; if (workbook.GetSheetIndex(sheetName) >= 0) { worksheet = workbook.GetSheet(sheetName); } else { worksheet = workbook.CreateSheet(sheetName); } IRow row1 = null; ICell cell = null; int defaultBeginTitleIndex = 0; if (excelFileDescription != null) { defaultBeginTitleIndex = excelFileDescription.TitleRowIndex; } PropertyInfo propertyInfo = null; T t = default(T); int tCount = tList.Count; int currentRowIndex = 0; int dataIndex = 0; do { row1 = worksheet.GetRow(currentRowIndex); if (row1 == null) { row1 = worksheet.CreateRow(currentRowIndex); } if (currentRowIndex >= defaultBeginTitleIndex) { //到达标题行 if (currentRowIndex == defaultBeginTitleIndex) { int cellIndex = 0; foreach (var titleMapper in titleMapperList) { cell = row1.GetCell(cellIndex); if (cell == null) { cell = row1.CreateCell(cellIndex); } ExcelHelper.SetCellValue(cell, titleMapper.ExcelTitle, outputFormat: null); cellIndex++; } } //到达内容行 else { dataIndex = currentRowIndex - defaultBeginTitleIndex - 1; if (dataIndex <= tCount - 1) { t = tList[dataIndex]; int cellIndex = 0; foreach (var titleMapper in titleMapperList) { propertyInfo = titleMapper.PropertyInfo; cell = row1.GetCell(cellIndex); if (cell == null) { cell = row1.CreateCell(cellIndex); } ExcelHelper.SetCellValue (cell, t, titleMapper); cellIndex++; } //重要:设置行宽度自适应(大批量添加数据时,该行代码需要注释,否则会极大减缓Excel添加行的速度!) //worksheet.AutoSizeColumn(i, true); } } } currentRowIndex++; } while (dataIndex < tCount - 1); //设置表达式重算(如果不添加该代码,表达式更新不出结果值) worksheet.ForceFormulaRecalculation = true; return workbook; } /// /// 将单元格数据列表生成工作表 /// /// 所有的单元格数据列表 /// 更新时添加:要更新的工作表 /// 指定要创建的sheet名称时添加 /// public static IWorkbook CreateOrUpdateWorkbook(CommonCellModelColl commonCellList, IWorkbook workbook = null, string sheetName = "sheet1") { //xls文件格式属于老版本文件,一个sheet最多保存65536行;而xlsx属于新版文件类型; //Excel 07 - 2003一个工作表最多可有65536行,行用数字1—65536表示; 最多可有256列,列用英文字母A—Z,AA—AZ,BA—BZ,……,IA—IV表示;一个工作簿中最多含有255个工作表,默认情况下是三个工作表; //Excel 2007及以后版本,一个工作表最多可有1048576行,16384列; if (workbook == null) { workbook = new XSSFWorkbook(); //workbook = new HSSFWorkbook(); } ISheet worksheet = null; if (workbook.GetSheetIndex(sheetName) >= 0) { worksheet = workbook.GetSheet(sheetName); } else { worksheet = workbook.CreateSheet(sheetName); } //设置首列显示 IRow row1 = null; int rowIndex = 0; int columnIndex = 0; int maxColumnIndex = 0; Dictionary<int, CommonCellModel> rowColumnIndexCellDIC = null; ICell cell = null; object cellValue = null; do { rowColumnIndexCellDIC = commonCellList.GetRawCellList(rowIndex).ToDictionary(m => m.ColumnIndex); maxColumnIndex = rowColumnIndexCellDIC.Count > 0 ? rowColumnIndexCellDIC.Keys.Max() : 0; if (rowColumnIndexCellDIC != null && rowColumnIndexCellDIC.Count > 0) { row1 = worksheet.GetRow(rowIndex); if (row1 == null) { row1 = worksheet.CreateRow(rowIndex); } columnIndex = 0; do { cell = row1.GetCell(columnIndex); if (cell == null) { cell = row1.CreateCell(columnIndex); } if (rowColumnIndexCellDIC.ContainsKey(columnIndex)) { cellValue = rowColumnIndexCellDIC[columnIndex].CellValue; ExcelHelper.SetCellValue(cell, cellValue, outputFormat: null, rowColumnIndexCellDIC[columnIndex].IsCellFormula); } columnIndex++; } while (columnIndex <= maxColumnIndex); } rowIndex++; } while (rowColumnIndexCellDIC != null && rowColumnIndexCellDIC.Count > 0); //设置表达式重算(如果不添加该代码,表达式更新不出结果值) worksheet.ForceFormulaRecalculation = true; return workbook; } /// /// 更新模板文件数据:将使用单元格映射的数据T存入模板文件中 /// /// 所有的单元格数据列表 /// 添加了单元格参数映射的数据对象 /// public static IWorkbook CreateOrUpdateWorkbook (string filePath, T t) { //该方法默认替换模板数据在首个sheet里 IWorkbook workbook = null; CommonCellModelColl commonCellColl = ExcelHelper._ReadCellList(filePath, out workbook); ISheet worksheet = workbook.GetSheetAt(0); //获取t的单元格映射列表 Dictionary<string, ExcelCellFieldMapper> tParamMapperDic = ExcelCellFieldMapper.GetModelFieldMapper ().ToDictionary(m => m.CellParamName); var rows = worksheet.GetRowEnumerator(); IRow row; ICell cell; string cellValue; ExcelCellFieldMapper cellMapper; while (rows.MoveNext()) { row = (XSSFRow)rows.Current; int cellCount = row.Cells.Count; for (int i = 0; i < cellCount; i++) { cell = row.Cells[i]; cellValue = cell.ToString(); if (tParamMapperDic.ContainsKey(cellValue)) { cellMapper = tParamMapperDic[cellValue]; ExcelHelper.SetCellValue (cell, t, cellMapper); } } } if (tParamMapperDic.Count > 0) { //循环所有单元格数据替换指定变量数据 foreach (var cellItem in commonCellColl) { cellValue = cellItem.CellValue.ToString(); if (tParamMapperDic.ContainsKey(cellValue)) { cellItem.CellValue = tParamMapperDic[cellValue].PropertyInfo.GetValue(t); } } } //设置表达式重算(如果不添加该代码,表达式更新不出结果值) worksheet.ForceFormulaRecalculation = true; return workbook; } #endregion #region 保存工作表到文件 /// /// 保存Workbook数据为文件 /// /// /// /// public static void SaveWorkbookToFile(IWorkbook workbook, string filePath) { //xls文件格式属于老版本文件,一个sheet最多保存65536行;而xlsx属于新版文件类型; //Excel 07 - 2003一个工作表最多可有65536行,行用数字1—65536表示; 最多可有256列,列用英文字母A—Z,AA—AZ,BA—BZ,……,IA—IV表示;一个工作簿中最多含有255个工作表,默认情况下是三个工作表; //Excel 2007及以后版本,一个工作表最多可有1048576行,16384列; MemoryStream ms = new MemoryStream(); //这句代码非常重要,如果不加,会报:打开的EXCEL格式与扩展名指定的格式不一致 ms.Seek(0, SeekOrigin.Begin); workbook.Write(ms); byte[] myByteArray = ms.GetBuffer(); string fileDirectoryPath = filePath.Split('\\')[0]; if (!Directory.Exists(fileDirectoryPath)) { Directory.CreateDirectory(fileDirectoryPath); } string fileName = filePath.Replace(fileDirectoryPath, ""); if (File.Exists(filePath)) { File.Delete(filePath); } File.WriteAllBytes(filePath, myByteArray); } #endregion #region 读取Excel数据 /// /// 读取Excel数据1_手动提供属性信息和标题对应关系 /// /// /// /// /// /// public static List ReadTitleDataList (string filePath, Dictionary<string, string> fieldNameAndShowNameDic, ExcelFileDescription excelFileDescription) where T : new() { //标题属性字典列表 List titleMapperList = ExcelTitleFieldMapper.GetModelFieldMapper (fieldNameAndShowNameDic); List tList = ExcelHelper._GetTList (filePath, titleMapperList, excelFileDescription); return tList ?? new List (0); } /// /// 读取Excel数据2_使用Excel标记特性和文件描述自动创建关系 /// /// /// /// public static List ReadTitleDataList (string filePath, ExcelFileDescription excelFileDescription) where T : new() { //标题属性字典列表 List titleMapperList = ExcelTitleFieldMapper.GetModelFieldMapper (); List tList = ExcelHelper._GetTList (filePath, titleMapperList, excelFileDescription); return tList ?? new List (0); } private static List _GetTList (string filePath, List titleMapperList, ExcelFileDescription excelFileDescription) where T : new() { List tList = new List (500 * 10000); T t = default(T); using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { IWorkbook workbook = null; IFormulaEvaluator formulaEvaluator = null; try { workbook = new XSSFWorkbook(fileStream); formulaEvaluator = new XSSFFormulaEvaluator(workbook); } catch (Exception) { workbook = new HSSFWorkbook(fileStream); formulaEvaluator = new HSSFFormulaEvaluator(workbook); } int sheetCount = workbook.NumberOfSheets; int currentSheetIndex = 0; int currentSheetRowTitleIndex = -1; do { var sheet = workbook.GetSheetAt(currentSheetIndex); //标题下标属性字典 Dictionary<int, ExcelTitleFieldMapper> sheetTitleIndexPropertyDic = new Dictionary<int, ExcelTitleFieldMapper>(0); //如果没有设置标题行,则通过自动查找方法获取 if (excelFileDescription.TitleRowIndex < 0) { string[] titleArray = titleMapperList.Select(m => m.ExcelTitle).ToArray(); currentSheetRowTitleIndex = ExcelHelper.GetSheetTitleIndex(sheet, titleArray); } else { currentSheetRowTitleIndex = excelFileDescription.TitleRowIndex; } var rows = sheet.GetRowEnumerator(); bool isHaveTitleIndex = false; //含有Excel行下标 if (titleMapperList.Count > 0 && titleMapperList[0].ExcelTitleIndex >= 0) { isHaveTitleIndex = true; foreach (var titleMapper in titleMapperList) { sheetTitleIndexPropertyDic.Add(titleMapper.ExcelTitleIndex, titleMapper); } } PropertyInfo propertyInfo = null; int currentRowIndex = 0; while (rows.MoveNext()) { IRow row = (IRow)rows.Current; currentRowIndex = row.RowNum; //到达标题行 if (isHaveTitleIndex == false && currentRowIndex == currentSheetRowTitleIndex) { ICell cell = null; string cellValue = null; Dictionary<string, ExcelTitleFieldMapper> titleMapperDic = titleMapperList.ToDictionary(m => m.ExcelTitle); for (int i = 0; i < row.Cells.Count; i++) { cell = row.Cells[i]; cellValue = cell.StringCellValue; if (titleMapperDic.ContainsKey(cellValue)) { sheetTitleIndexPropertyDic.Add(i, titleMapperDic[cellValue]); } } } //到达内容行 if (currentRowIndex > currentSheetRowTitleIndex) { t = new T(); ExcelTitleFieldMapper excelTitleFieldMapper = null; foreach (var titleIndexItem in sheetTitleIndexPropertyDic) { ICell cell = row.GetCell(titleIndexItem.Key); excelTitleFieldMapper = titleIndexItem.Value; //没有数据的单元格默认为null string cellValue = cell?.ToString() ?? ""; propertyInfo = excelTitleFieldMapper.PropertyInfo; try { if (excelTitleFieldMapper.IsCheckContentEmpty) { if (string.IsNullOrEmpty(cellValue)) { t = default(T); break; } } if (excelTitleFieldMapper.IsCoordinateExpress || cell.CellType == CellType.Formula) { //读取含有表达式的单元格值 cellValue = formulaEvaluator.Evaluate(cell).StringValue; propertyInfo.SetValue(t, Convert.ChangeType(cellValue, propertyInfo.PropertyType)); } else if (propertyInfo.PropertyType.IsEnum) { object enumObj = propertyInfo.PropertyType.InvokeMember(cellValue, BindingFlags.GetField, null, null, null); propertyInfo.SetValue(t, Convert.ChangeType(enumObj, propertyInfo.PropertyType)); } else { propertyInfo.SetValue(t, Convert.ChangeType(cellValue, propertyInfo.PropertyType)); } } catch (Exception e) { ExcelHelper._Logger.Debug($"文件_{filePath}读取{currentRowIndex + 1}行内容失败!"); t = default(T); break; } } if (t != null) { tList.Add(t); } } } currentSheetIndex++; } while (currentSheetIndex + 1 <= sheetCount); } return tList ?? new List (0); } /// /// 读取文件的所有单元格数据 /// /// 文件路径 /// public static CommonCellModelColl ReadCellList(string filePath) { IWorkbook workbook = null; CommonCellModelColl commonCellColl = ExcelHelper._ReadCellList(filePath, out workbook); return commonCellColl; } /// /// 读取文件的所有单元格数据 /// /// 文件路径 /// public static CommonCellModelColl ReadCellList(string filePath, out IWorkbook workbook) { CommonCellModelColl commonCellColl = ExcelHelper._ReadCellList(filePath, out workbook); return commonCellColl; } private static CommonCellModelColl _ReadCellList(string filePath, out IWorkbook workbook) { CommonCellModelColl commonCellColl = new CommonCellModelColl(10000); CommonCellModel cellModel = null; workbook = null; using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { try { workbook = new XSSFWorkbook(fileStream); } catch (Exception) { workbook = new HSSFWorkbook(fileStream); } var sheet = workbook.GetSheetAt(0); var rows = sheet.GetRowEnumerator(); List cellList = null; ICell cell = null; //从第1行数据开始获取 while (rows.MoveNext()) { IRow row = (IRow)rows.Current; cellList = row.Cells; int cellCount = cellList.Count; for (int i = 0; i < cellCount; i++) { cell = cellList[i]; cellModel = new CommonCellModel { RowIndex = row.RowNum, ColumnIndex = i, CellValue = cell.ToString(), IsCellFormula = cell.CellType == CellType.Formula ? true : false }; commonCellColl.Add(cellModel); } } } return commonCellColl; } /// /// 获取文件单元格数据对象 /// /// T的属性必须标记了ExcelCellAttribute /// 文建路径 /// public static T ReadCellData (string filePath) where T : new() { T t = new T(); ExcelHelper._Logger.Info($"开始读取{filePath}的数据..."); CommonCellModelColl commonCellColl = ExcelHelper.ReadCellList(filePath); Dictionary propertyMapperDic = ExcelCellFieldMapper.GetModelFieldMapper ().ToDictionary(m => m.PropertyInfo); string cellExpress = null; string pValue = null; PropertyInfo propertyInfo = null; foreach (var item in propertyMapperDic) { cellExpress = item.Value.CellCoordinateExpress; propertyInfo = item.Key; pValue = ExcelHelper.GetVByExpress(cellExpress, propertyInfo, commonCellColl).ToString(); if (!string.IsNullOrEmpty(pValue)) { propertyInfo.SetValue(t, Convert.ChangeType(pValue, propertyInfo.PropertyType)); } } return t; } /// /// 获取文件首个sheet的标题位置 /// /// T必须做了标题映射 /// /// public static int FileFirstSheetTitleIndex (string filePath) { int titleIndex = 0; if (File.Exists(filePath)) { using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { IWorkbook workbook = null; try { workbook = new XSSFWorkbook(fileStream); } catch (Exception) { workbook = new HSSFWorkbook(fileStream); } string[] titleArray = ExcelTitleFieldMapper.GetModelFieldMapper ().Select(m => m.ExcelTitle).ToArray(); ISheet sheet = workbook.GetSheetAt(0); titleIndex = ExcelHelper.GetSheetTitleIndex(sheet, titleArray); } } return titleIndex; } /// /// 获取文件首个sheet的标题位置 /// /// /// /// public static int FileFirstSheetTitleIndex(string filePath, params string[] titleNames) { int titleIndex = 0; if (File.Exists(filePath)) { using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { IWorkbook workbook = null; try { workbook = new XSSFWorkbook(fileStream); } catch (Exception) { workbook = new HSSFWorkbook(fileStream); } ISheet sheet = workbook.GetSheetAt(0); titleIndex = ExcelHelper.GetSheetTitleIndex(sheet, titleNames); } } return titleIndex; } #endregion #region 辅助方法 /// /// 返回单元格坐标横坐标 /// /// 单元格坐标(A1,B15...) /// 带回:纵坐标 /// private static int GetValueByZM(string cellPoint, out int columnIndex) { int rowIndex = 0; columnIndex = 0; Regex columnIndexRegex = new Regex("[a-zA-Z]+", RegexOptions.IgnoreCase); string columnZM = columnIndexRegex.Match(cellPoint).Value; rowIndex = Convert.ToInt32(cellPoint.Replace(columnZM, "")) - 1; int zmLen = 0; if (!string.IsNullOrEmpty(columnZM)) { zmLen = columnZM.Length; } for (int i = zmLen - 1; i > -1; i--) { columnIndex += (int)Math.Pow((int)columnZM[i] - 64, (zmLen - i)); } columnIndex = columnIndex - 1; return rowIndex; } /// /// 根据单元格表达式和单元格数据集获取数据 /// /// 单元格表达式 /// 单元格数据集 /// private static object GetVByExpress(string cellExpress, PropertyInfo propertyInfo, CommonCellModelColl commonCellColl) { object value = null; //含有单元格表达式的取表达式值,没有表达式的取单元格字符串 if (!string.IsNullOrEmpty(cellExpress)) { MatchCollection matchCollection = Regex.Matches(cellExpress, "\\w+"); string point = null; int rowIndex = 0; int columnIndex = 0; string cellValue = null; System.Data.DataTable dt = new System.Data.DataTable(); foreach (var item in matchCollection) { point = item.ToString(); rowIndex = ExcelHelper.GetValueByZM(point, out columnIndex); cellValue = commonCellColl[rowIndex, columnIndex]?.CellValue?.ToString() ?? ""; if (propertyInfo.PropertyType == typeof(decimal) || propertyInfo.PropertyType == typeof(double) || propertyInfo.PropertyType == typeof(int)) { if (!string.IsNullOrEmpty(cellValue)) { cellValue = cellValue.Replace(",", ""); } else { cellValue = "0"; } } else { cellValue = $"'{cellValue}'"; } cellExpress = cellExpress.Replace(item.ToString(), cellValue); } //执行字符和数字的表达式计算(字符需要使用单引号包裹,数字需要移除逗号) value = dt.Compute(cellExpress, ""); } return value ?? ""; } /// /// 将数据放入单元格中 /// /// 泛型类 /// 单元格对象 /// 泛型类数据 /// 单元格映射信息 private static void SetCellValue (ICell cell, T t, ExcelCellFieldMapper cellFieldMapper) { object cellValue = cellFieldMapper.PropertyInfo.GetValue(t); ExcelHelper.SetCellValue(cell, cellValue, cellFieldMapper?.OutputFormat); } /// /// 将数据放入单元格中 /// /// 泛型类 /// 单元格对象 /// 泛型类数据 /// 单元格映射信息 private static void SetCellValue (ICell cell, T t, ExcelTitleFieldMapper cellFieldMapper) { object cellValue = cellFieldMapper.PropertyInfo.GetValue(t); ExcelHelper.SetCellValue(cell, cellValue, cellFieldMapper?.OutputFormat, cellFieldMapper?.IsCoordinateExpress ?? false); } /// /// 将数据放入单元格中 /// /// 单元格对象 /// 数据 /// 格式化字符串 /// 是否是表达式数据 private static void SetCellValue(ICell cell, object cellValue, string outputFormat, bool isCoordinateExpress = false) { if (cell != null) { if (isCoordinateExpress) { cell.SetCellFormula(cellValue.ToString()); } else { if (!string.IsNullOrEmpty(outputFormat)) { string formatValue = null; IFormatProvider formatProvider = null; if (cellValue is DateTime) { formatProvider = new DateTimeFormatInfo(); ((DateTimeFormatInfo)formatProvider).ShortDatePattern = outputFormat; } formatValue = ((IFormattable)cellValue).ToString(outputFormat, formatProvider); cell.SetCellValue(formatValue); } else { if (cellValue is decimal || cellValue is double || cellValue is int) { cell.SetCellValue(Convert.ToDouble(cellValue)); } else if (cellValue is DateTime) { cell.SetCellValue((DateTime)cellValue); } else if (cellValue is bool) { cell.SetCellValue((bool)cellValue); } else { cell.SetCellValue(cellValue.ToString()); } } } } } /// /// 根据标题名称获取标题行下标位置 /// /// 要查找的sheet /// 标题名称 /// private static int GetSheetTitleIndex(ISheet sheet, params string[] titleNames) { int titleIndex = -1; if (sheet != null && titleNames != null && titleNames.Length > 0) { var rows = sheet.GetRowEnumerator(); List cellList = null; List<string> rowValueList = null; //从第1行数据开始获取 while (rows.MoveNext()) { IRow row = (IRow)rows.Current; cellList = row.Cells; rowValueList = new List<string>(cellList.Count); foreach (var cell in cellList) { rowValueList.Add(cell.ToString()); } bool isTitle = true; foreach (var title in titleNames) { if (!rowValueList.Contains(title)) { isTitle = false; break; } } if (isTitle) { titleIndex = row.RowNum; break; } } } return titleIndex; } #endregion } }
2-自定义单元格类:

using NPOI.SS.UserModel; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PPPayReportTools.Excel { public class CommonCellModel { public CommonCellModel() { } public CommonCellModel(int rowIndex, int columnIndex, object cellValue, bool isCellFormula = false) { this.RowIndex = rowIndex; this.ColumnIndex = columnIndex; this.CellValue = cellValue; this.IsCellFormula = isCellFormula; } public int RowIndex { get; set; } public int ColumnIndex { get; set; } public object CellValue { get; set; } ////// 是否是单元格公式 /// public bool IsCellFormula { get; set; } } public class CommonCellModelColl : List , IList { public CommonCellModelColl() { } public CommonCellModelColl(int capacity) : base(capacity) { } /// /// 根据行下标,列下标获取单元格数据 /// /// /// /// public CommonCellModel this[int rowIndex, int columnIndex] { get { CommonCellModel cell = this.FirstOrDefault(m => m.RowIndex == rowIndex && m.ColumnIndex == columnIndex); return cell; } set { CommonCellModel cell = this.FirstOrDefault(m => m.RowIndex == rowIndex && m.ColumnIndex == columnIndex); if (cell != null) { cell.CellValue = value.CellValue; } } } /// /// 所有一行所有的单元格数据 /// /// 行下标 /// public List GetRawCellList(int rowIndex) { List cellList = null; cellList = this.FindAll(m => m.RowIndex == rowIndex); return cellList ?? new List (0); } /// /// 所有一列所有的单元格数据 /// /// 列下标 /// public List GetColumnCellList(int columnIndex) { List cellList = null; cellList = this.FindAll(m => m.ColumnIndex == columnIndex); return cellList ?? new List (0); } } }
3-单元格特性类:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PPPayReportTools.Excel { ////// Excel单元格标记特性 /// [System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple = false)] public class ExcelCellAttribute : System.Attribute { /// /// 该参数用于收集数据存于固定位置的单元格数据(单元格坐标表达式(如:A1,B2,C1+C2...横坐标使用26进制字母,纵坐标使用十进制数字)) /// public string CellCoordinateExpress { get; set; } /// /// 该参数用于替换模板文件的预定义变量使用({A} {B}) /// public string CellParamName { get; set; } /// /// 字符输出格式(数字和日期类型需要) /// public string OutputFormat { get; set; } public ExcelCellAttribute(string cellCoordinateExpress = null, string cellParamName = null) { CellCoordinateExpress = cellCoordinateExpress; CellParamName = cellParamName; } public ExcelCellAttribute(string cellCoordinateExpress, string cellParamName, string outputFormat) : this(cellCoordinateExpress, cellParamName) { OutputFormat = outputFormat; } } }
4-单元格属性映射帮助类:

using System.Collections.Generic; using System.Linq; using System.Reflection; namespace PPPayReportTools.Excel { ////// 单元格字段映射类 /// internal class ExcelCellFieldMapper { /// /// 属性信息 /// public PropertyInfo PropertyInfo { get; set; } /// /// 该参数用于收集数据存于固定位置的单元格数据(单元格坐标表达式(如:A1,B2,C1+C2...横坐标使用26进制字母,纵坐标使用十进制数字)) /// public string CellCoordinateExpress { get; set; } /// /// 该参数用于替换模板文件的预定义变量使用({A} {B}) /// public string CellParamName { get; set; } /// /// 字符输出格式(数字和日期类型需要) /// public string OutputFormat { get; set; } /// /// 获取对应关系_T属性添加了单元格映射关系 /// /// /// public static List GetModelFieldMapper () { List fieldMapperList = new List (100); List tPropertyInfoList = typeof(T).GetProperties().ToList(); ExcelCellAttribute cellExpress = null; foreach (var item in tPropertyInfoList) { cellExpress = item.GetCustomAttribute (); if (cellExpress != null) { fieldMapperList.Add(new ExcelCellFieldMapper { CellCoordinateExpress = cellExpress.CellCoordinateExpress, CellParamName = cellExpress.CellParamName, OutputFormat = cellExpress.OutputFormat, PropertyInfo = item }); } } return fieldMapperList; } } }
5-Excel文件描述类:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PPPayReportTools.Excel { public class ExcelFileDescription { ////// 默认从第1行数据开始读取标题数据 /// public ExcelFileDescription() : this(0) { } public ExcelFileDescription(int titleRowIndex) { this.TitleRowIndex = titleRowIndex; } /// /// 标题所在行位置(默认为0,没有标题填-1) /// public int TitleRowIndex { get; set; } } }
6-Excel标题特性类:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PPPayReportTools.Excel { ////// Excel标题标记特性 /// [System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple = false)] public class ExcelTitleAttribute : System.Attribute { /// /// Excel行标题(标题和下标选择一个即可) /// public string RowTitle { get; set; } /// /// Excel行下标(标题和下标选择一个即可,默认值-1) /// public int RowTitleIndex { get; set; } /// /// 单元格是否要检查空数据(true为检查,为空的行数据不添加) /// public bool IsCheckContentEmpty { get; set; } /// /// 字符输出格式(数字和日期类型需要) /// public string OutputFormat { get; set; } /// /// 是否是公式列 /// public bool IsCoordinateExpress { get; set; } /// /// 标题特性构造方法 /// /// 标题 /// 单元格是否要检查空数据 /// 是否是公式列 /// 是否有格式化输出要求 public ExcelTitleAttribute(string title, bool isCheckEmpty = false, bool isCoordinateExpress = false, string outputFormat = "") { RowTitle = title; IsCheckContentEmpty = isCheckEmpty; IsCoordinateExpress = isCoordinateExpress; OutputFormat = outputFormat; RowTitleIndex = -1; } public ExcelTitleAttribute(int titleIndex, bool isCheckEmpty = false, bool isCoordinateExpress = false, string outputFormat = "") { RowTitleIndex = titleIndex; IsCheckContentEmpty = isCheckEmpty; IsCoordinateExpress = isCoordinateExpress; OutputFormat = outputFormat; } } }
7-Ecel标题属性映射帮助类:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PPPayReportTools.Excel { ////// Excel标题标记特性 /// [System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple = false)] public class ExcelTitleAttribute : System.Attribute { /// /// Excel行标题(标题和下标选择一个即可) /// public string RowTitle { get; set; } /// /// Excel行下标(标题和下标选择一个即可,默认值-1) /// public int RowTitleIndex { get; set; } /// /// 单元格是否要检查空数据(true为检查,为空的行数据不添加) /// public bool IsCheckContentEmpty { get; set; } /// /// 字符输出格式(数字和日期类型需要) /// public string OutputFormat { get; set; } /// /// 是否是公式列 /// public bool IsCoordinateExpress { get; set; } /// /// 标题特性构造方法 /// /// 标题 /// 单元格是否要检查空数据 /// 是否是公式列 /// 是否有格式化输出要求 public ExcelTitleAttribute(string title, bool isCheckEmpty = false, bool isCoordinateExpress = false, string outputFormat = "") { RowTitle = title; IsCheckContentEmpty = isCheckEmpty; IsCoordinateExpress = isCoordinateExpress; OutputFormat = outputFormat; RowTitleIndex = -1; } public ExcelTitleAttribute(int titleIndex, bool isCheckEmpty = false, bool isCoordinateExpress = false, string outputFormat = "") { RowTitleIndex = titleIndex; IsCheckContentEmpty = isCheckEmpty; IsCoordinateExpress = isCoordinateExpress; OutputFormat = outputFormat; } } }
示例代码1-单元格映射类:

////// 账户_多币种交易报表_数据源 /// public class AccountMultiCurrencyTransactionSource { /// /// 期初 /// [ExcelCellAttribute("B9")] public decimal BeginingBalance { get; set; } /// /// 收款 /// [ExcelCellAttribute("B19+C19")] public decimal TotalTransactionPrice { get; set; } /// /// 收到非EBay款项_主要指从其他账户转给当前账户的钱 /// [ExcelCellAttribute("B21+C21")] public decimal TransferAccountInPrice { get; set; } /// /// 退款(客户不提交争议直接退款) /// [ExcelCellAttribute("B23+C23")] public decimal TotalRefundPrice { get; set; } /// /// 手续费 /// [ExcelCellAttribute("B25+C25")] public decimal TotalFeePrice { get; set; } /// /// 争议退款 /// [ExcelCellAttribute("B37+C37")] public decimal TotalChargebackRefundPrice { get; set; } /// /// 转账与提现(币种转换) /// [ExcelCellAttribute("B45+C45")] public decimal CurrencyChangePrice { get; set; } /// /// 转账与提现(转账到paypal账户)_提现失败退回金额 /// [ExcelCellAttribute("B47+C47")] public decimal CashWithdrawalInPrice { get; set; } /// /// 转账与提现(从paypal账户转账)_提现金额 /// [ExcelCellAttribute("B49+C49")] public decimal CashWithdrawalOutPrice { get; set; } /// /// 购物_主要指从当前账户转给其他账户的钱 /// [ExcelCellAttribute("B51+C51")] public decimal TransferAccountOutPrice { get; set; } /// /// 其他活动 /// [ExcelCellAttribute("B85+C85")] public decimal OtherPrice { get; set; } /// /// 期末 /// [ExcelCellAttribute("C9")] public decimal EndingBalance { get; set; } }
示例代码2-标题映射类(标题映射分类字符串映射和下标位置映射,这里使用下标位置映射):

////// 美元币种转换_数据源 /// public class CurrencyChangeUSDSource { /// /// 日期[y/M/d] /// [ExcelTitleAttribute(0, true)] public DateTime Date { get; set; } /// /// 类型 /// [ExcelTitleAttribute(1, true)] public string Type { get; set; } /// /// 交易号 /// [ExcelTitleAttribute(2)] public string TX { get; set; } /// /// 商家/接收人姓名地址第1行地址第2行/区发款账户名称_发款账户简称 /// [ExcelTitleAttribute(3)] public string SendedOrReceivedName { get; set; } /// /// 电子邮件编号_发款账户全称 /// [ExcelTitleAttribute(4)] public string SendedOrReceivedAccountName { get; set; } /// /// 币种 /// [ExcelTitleAttribute(5)] public string CurrencyCode { get; set; } /// /// 总额 /// [ExcelTitleAttribute(6)] public decimal TotalPrice { get; set; } /// /// 净额 /// [ExcelTitleAttribute(7)] public decimal NetPrice { get; set; } /// /// 费用 /// [ExcelTitleAttribute(8)] public decimal FeePrice { get; set; } }
示例代码3-模板文件数据替换-单元格映射类:

////// 多账户美元汇总金额_最终模板使用展示类 /// public class AccountUSDSummaryTransaction { /// /// 期初 /// [ExcelCellAttribute(cellParamName: "{DLZ_BeginingBalance}")] public decimal DLZ_BeginingBalance { get; set; } /// /// 收款 /// [ExcelCellAttribute(cellParamName: "{DLZ_TotalTransactionPrice}")] public decimal DLZ_TotalTransactionPrice { get; set; } /// /// 收到非EBay款项_主要指从其他账户转给当前账户的钱 /// [ExcelCellAttribute(cellParamName: "{DLZ_TransferAccountInPrice}")] public decimal DLZ_TransferAccountInPrice { get; set; } /// /// 退款(客户不提交争议直接退款) /// [ExcelCellAttribute(cellParamName: "{DLZ_TotalRefundPrice}")] public decimal DLZ_TotalRefundPrice { get; set; } /// /// 手续费 /// [ExcelCellAttribute(cellParamName: "{DLZ_TotalFeePrice}")] public decimal DLZ_TotalFeePrice { get; set; } /// /// 争议退款 /// [ExcelCellAttribute(cellParamName: "{DLZ_TotalChargebackRefundPrice}")] public decimal DLZ_TotalChargebackRefundPrice { get; set; } /// /// 转账与提现(币种转换) /// [ExcelCellAttribute(cellParamName: "{DLZ_CurrencyChangePrice}")] public decimal DLZ_CurrencyChangePrice { get; set; } /// /// 转账与提现(转账到paypal账户)_提现失败退回金额 /// [ExcelCellAttribute(cellParamName: "{DLZ_CashWithdrawalInPrice}")] public decimal DLZ_CashWithdrawalInPrice { get; set; } /// /// 转账与提现(从paypal账户转账)_提现金额 /// [ExcelCellAttribute(cellParamName: "{DLZ_CashWithdrawalOutPrice}")] public decimal DLZ_CashWithdrawalOutPrice { get; set; } /// /// 购物_主要指从当前账户转给其他账户的钱 /// [ExcelCellAttribute(cellParamName: "{DLZ_TransferAccountOutPrice}")] public decimal DLZ_TransferAccountOutPrice { get; set; } /// /// 其他活动 /// [ExcelCellAttribute(cellParamName: "{DLZ_OtherPrice}")] public decimal DLZ_OtherPrice { get; set; } /// /// 期末 /// [ExcelCellAttribute(cellParamName: "{DLZ_EndingBalance}")] public decimal DLZ_EndingBalance { get { decimal result = this.DLZ_BeginingBalance + this.DLZ_TotalTransactionPrice + this.DLZ_TransferAccountInPrice + this.DLZ_TotalRefundPrice + this.DLZ_TotalFeePrice + this.DLZ_TotalChargebackRefundPrice + this.DLZ_CurrencyChangePrice + this.DLZ_CashWithdrawalInPrice + this.DLZ_CashWithdrawalOutPrice + this.DLZ_TransferAccountOutPrice + this.DLZ_OtherPrice; return result; } } /// /// 期末汇率差 /// [ExcelCellAttribute(cellParamName: "{DLZ_EndingBalanceDifferenceValue}")] public decimal DLZ_EndingBalanceDifferenceValue { get { return this.DLZ_RealRateEndingBalance - this.DLZ_EndingBalance; } } /// /// 真实汇率计算的期末余额 /// [ExcelCellAttribute(cellParamName: "{DLZ_RealRateEndingBalance}")] public decimal DLZ_RealRateEndingBalance { get; set; } }
示例代码4-存储多个数据源到一个Excel中(这里我是保持到了不同的sheet页里,当然也可以保持到同一个sheet的不同位置):
IWorkbook workbook = null; workbook = ExcelHelper.CreateOrUpdateWorkbook(dlzShopList, workbook, "独立站"); workbook = ExcelHelper.CreateOrUpdateWorkbook(ebayShopList, workbook, "EBay"); ExcelHelper.SaveWorkbookToFile(workbook, ConfigSetting.SaveReceivedNonEBayReportFile);