本篇博客園是被任務所逼,而已有的使用nopi技術的文檔技術經驗又不支持我須要的應對各類複雜需求的苛刻要求,只能本身造輪子封裝了,因爲須要應對不少總類型的數據採集需求,所以有了本篇博客的代碼封裝,下面一點點介紹吧:app
收集excel你有沒有遇到過一下痛點:ide
1-須要收集指定行標題位置的數據,個人標題行不必定在第一行。 這個和個人csv的文檔需求是一致的this
2-須要採集指定單元格位置的數據生成一個對象,而不是一個列表。 這裏個人方案是制定一個單元格映射類解決問題。 單元格映射類,支持表達式數據採集(我可能須要一個單元格的數據+另外一個單元格的數據做爲一個屬性等等)lua
3-應對不規範標題沒法轉出字符串進行映射時,能不能經過制定標題的列下標創建對應關係,進行列表數據採集呢? 本博客同時支持標題字符串數據採集和標題下標數據採集,這個就牛逼了。spa
4-存儲含有表達式的數據,這個並非難點,因爲很重要,就在這裏列一下3d
5-應對Excel模板文件的數據指定位置填入數據,該位置可能會變更的解決方案。本文爲了應對該狀況,藉助了單元格映射關係,添加了模板參數名的屬性處理,能夠應對模板文件調整時的位置變更問題。excel
6-一個能同時處理excel新老版本(.xls和.xlsx),一個指定excel位置保存數據,保存含有表達式的數據,一個能夠將多個不一樣的數據組合存放到一個excel中的需求均可以知足。 code
痛點大概就是上面這些了,下面寫主要代碼吧,供你們參考,不過封裝的類方法有點多:orm
本文藉助了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 { /// <summary> /// EXCEL幫助類 /// </summary> /// <typeparam name="T">泛型類</typeparam> /// <typeparam name="TCollection">泛型類集合</typeparam> public class ExcelHelper { private static Logger _Logger = LogManager.GetCurrentClassLogger(); #region 建立工做表 /// <summary> /// 將列表數據生成工做表 /// </summary> /// <param name="tList">要導出的數據集</param> /// <param name="fieldNameAndShowNameDic">鍵值對集合(鍵:字段名,值:顯示名稱)</param> /// <param name="workbook">更新時添加:要更新的工做表</param> /// <param name="sheetName">指定要建立的sheet名稱時添加</param> /// <param name="excelFileDescription">讀取或插入定製需求時添加</param> /// <returns></returns> public static IWorkbook CreateOrUpdateWorkbook<T>(List<T> tList, Dictionary<string, string> fieldNameAndShowNameDic, IWorkbook workbook = null, string sheetName = "sheet1", ExcelFileDescription excelFileDescription = null) where T : new() { List<ExcelTitleFieldMapper> titleMapperList = ExcelTitleFieldMapper.GetModelFieldMapper<T>(fieldNameAndShowNameDic); workbook = ExcelHelper.CreateOrUpdateWorkbook<T>(tList, titleMapperList, workbook, sheetName, excelFileDescription); return workbook; } /// <summary> /// 將列表數據生成工做表(T的屬性須要添加:屬性名列名映射關係) /// </summary> /// <param name="tList">要導出的數據集</param> /// <param name="workbook">更新時添加:要更新的工做表</param> /// <param name="sheetName">指定要建立的sheet名稱時添加</param> /// <param name="excelFileDescription">讀取或插入定製需求時添加</param> /// <returns></returns> public static IWorkbook CreateOrUpdateWorkbook<T>(List<T> tList, IWorkbook workbook = null, string sheetName = "sheet1", ExcelFileDescription excelFileDescription = null) where T : new() { List<ExcelTitleFieldMapper> titleMapperList = ExcelTitleFieldMapper.GetModelFieldMapper<T>(); workbook = ExcelHelper.CreateOrUpdateWorkbook<T>(tList, titleMapperList, workbook, sheetName, excelFileDescription); return workbook; } private static IWorkbook CreateOrUpdateWorkbook<T>(List<T> tList, List<ExcelTitleFieldMapper> 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<T>(cell, t, titleMapper); cellIndex++; } //重要:設置行寬度自適應(大批量添加數據時,該行代碼須要註釋,不然會極大減緩Excel添加行的速度!) //worksheet.AutoSizeColumn(i, true); } } } currentRowIndex++; } while (dataIndex < tCount - 1); //設置表達式重算(若是不添加該代碼,表達式更新不出結果值) worksheet.ForceFormulaRecalculation = true; return workbook; } /// <summary> /// 將單元格數據列表生成工做表 /// </summary> /// <param name="commonCellList">全部的單元格數據列表</param> /// <param name="workbook">更新時添加:要更新的工做表</param> /// <param name="sheetName">指定要建立的sheet名稱時添加</param> /// <returns></returns> 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; } /// <summary> /// 更新模板文件數據:將使用單元格映射的數據T存入模板文件中 /// </summary> /// <param name="filePath">全部的單元格數據列表</param> /// <param name="t">添加了單元格參數映射的數據對象</param> /// <returns></returns> public static IWorkbook CreateOrUpdateWorkbook<T>(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<T>().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<T>(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 保存工做表到文件 /// <summary> /// 保存Workbook數據爲文件 /// </summary> /// <param name="workbook"></param> /// <param name="fileDirectoryPath"></param> /// <param name="fileName"></param> 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數據 /// <summary> /// 讀取Excel數據1_手動提供屬性信息和標題對應關係 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="filePath"></param> /// <param name="fieldNameAndShowNameDic"></param> /// <param name="excelFileDescription"></param> /// <returns></returns> public static List<T> ReadTitleDataList<T>(string filePath, Dictionary<string, string> fieldNameAndShowNameDic, ExcelFileDescription excelFileDescription) where T : new() { //標題屬性字典列表 List<ExcelTitleFieldMapper> titleMapperList = ExcelTitleFieldMapper.GetModelFieldMapper<T>(fieldNameAndShowNameDic); List<T> tList = ExcelHelper._GetTList<T>(filePath, titleMapperList, excelFileDescription); return tList ?? new List<T>(0); } /// <summary> /// 讀取Excel數據2_使用Excel標記特性和文件描述自動建立關係 /// </summary> /// <param name="filePath"></param> /// <param name="excelFileDescription"></param> /// <returns></returns> public static List<T> ReadTitleDataList<T>(string filePath, ExcelFileDescription excelFileDescription) where T : new() { //標題屬性字典列表 List<ExcelTitleFieldMapper> titleMapperList = ExcelTitleFieldMapper.GetModelFieldMapper<T>(); List<T> tList = ExcelHelper._GetTList<T>(filePath, titleMapperList, excelFileDescription); return tList ?? new List<T>(0); } private static List<T> _GetTList<T>(string filePath, List<ExcelTitleFieldMapper> titleMapperList, ExcelFileDescription excelFileDescription) where T : new() { List<T> tList = new List<T>(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<T>(0); } /// <summary> /// 讀取文件的全部單元格數據 /// </summary> /// <param name="filePath">文件路徑</param> /// <returns></returns> public static CommonCellModelColl ReadCellList(string filePath) { IWorkbook workbook = null; CommonCellModelColl commonCellColl = ExcelHelper._ReadCellList(filePath, out workbook); return commonCellColl; } /// <summary> /// 讀取文件的全部單元格數據 /// </summary> /// <param name="filePath">文件路徑</param> /// <returns></returns> 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<ICell> 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; } /// <summary> /// 獲取文件單元格數據對象 /// </summary> /// <typeparam name="T">T的屬性必須標記了ExcelCellAttribute</typeparam> /// <param name="filePath">文建路徑</param> /// <returns></returns> public static T ReadCellData<T>(string filePath) where T : new() { T t = new T(); ExcelHelper._Logger.Info($"開始讀取{filePath}的數據..."); CommonCellModelColl commonCellColl = ExcelHelper.ReadCellList(filePath); Dictionary<PropertyInfo, ExcelCellFieldMapper> propertyMapperDic = ExcelCellFieldMapper.GetModelFieldMapper<T>().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; } /// <summary> /// 獲取文件首個sheet的標題位置 /// </summary> /// <typeparam name="T">T必須作了標題映射</typeparam> /// <param name="filePath"></param> /// <returns></returns> public static int FileFirstSheetTitleIndex<T>(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<T>().Select(m => m.ExcelTitle).ToArray(); ISheet sheet = workbook.GetSheetAt(0); titleIndex = ExcelHelper.GetSheetTitleIndex(sheet, titleArray); } } return titleIndex; } /// <summary> /// 獲取文件首個sheet的標題位置 /// </summary> /// <param name="filePath"></param> /// <param name="titleNames"></param> /// <returns></returns> 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 輔助方法 /// <summary> /// 返回單元格座標橫座標 /// </summary> /// <param name="cellPoint">單元格座標(A1,B15...)</param> /// <param name="columnIndex">帶回:縱座標</param> /// <returns></returns> 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; } /// <summary> /// 根據單元格表達式和單元格數據集獲取數據 /// </summary> /// <param name="cellExpress">單元格表達式</param> /// <param name="commonCellColl">單元格數據集</param> /// <returns></returns> 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 ?? ""; } /// <summary> /// 將數據放入單元格中 /// </summary> /// <typeparam name="T">泛型類</typeparam> /// <param name="cell">單元格對象</param> /// <param name="t">泛型類數據</param> /// <param name="cellFieldMapper">單元格映射信息</param> private static void SetCellValue<T>(ICell cell, T t, ExcelCellFieldMapper cellFieldMapper) { object cellValue = cellFieldMapper.PropertyInfo.GetValue(t); ExcelHelper.SetCellValue(cell, cellValue, cellFieldMapper?.OutputFormat); } /// <summary> /// 將數據放入單元格中 /// </summary> /// <typeparam name="T">泛型類</typeparam> /// <param name="cell">單元格對象</param> /// <param name="t">泛型類數據</param> /// <param name="cellFieldMapper">單元格映射信息</param> private static void SetCellValue<T>(ICell cell, T t, ExcelTitleFieldMapper cellFieldMapper) { object cellValue = cellFieldMapper.PropertyInfo.GetValue(t); ExcelHelper.SetCellValue(cell, cellValue, cellFieldMapper?.OutputFormat, cellFieldMapper?.IsCoordinateExpress ?? false); } /// <summary> /// 將數據放入單元格中 /// </summary> /// <param name="cell">單元格對象</param> /// <param name="cellValue">數據</param> /// <param name="outputFormat">格式化字符串</param> /// <param name="isCoordinateExpress">是不是表達式數據</param> 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()); } } } } } /// <summary> /// 根據標題名稱獲取標題行下標位置 /// </summary> /// <param name="sheet">要查找的sheet</param> /// <param name="titleNames">標題名稱</param> /// <returns></returns> 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<ICell> 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; } /// <summary> /// 是不是單元格公式 /// </summary> public bool IsCellFormula { get; set; } } public class CommonCellModelColl : List<CommonCellModel>, IList<CommonCellModel> { public CommonCellModelColl() { } public CommonCellModelColl(int capacity) : base(capacity) { } /// <summary> /// 根據行下標,列下標獲取單元格數據 /// </summary> /// <param name="rowIndex"></param> /// <param name="columnIndex"></param> /// <returns></returns> 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; } } } /// <summary> /// 全部一行全部的單元格數據 /// </summary> /// <param name="rowIndex">行下標</param> /// <returns></returns> public List<CommonCellModel> GetRawCellList(int rowIndex) { List<CommonCellModel> cellList = null; cellList = this.FindAll(m => m.RowIndex == rowIndex); return cellList ?? new List<CommonCellModel>(0); } /// <summary> /// 全部一列全部的單元格數據 /// </summary> /// <param name="columnIndex">列下標</param> /// <returns></returns> public List<CommonCellModel> GetColumnCellList(int columnIndex) { List<CommonCellModel> cellList = null; cellList = this.FindAll(m => m.ColumnIndex == columnIndex); return cellList ?? new List<CommonCellModel>(0); } } }
3-單元格特性類:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PPPayReportTools.Excel { /// <summary> /// Excel單元格標記特性 /// </summary> [System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple = false)] public class ExcelCellAttribute : System.Attribute { /// <summary> /// 該參數用於收集數據存於固定位置的單元格數據(單元格座標表達式(如:A1,B2,C1+C2...橫座標使用26進制字母,縱座標使用十進制數字)) /// </summary> public string CellCoordinateExpress { get; set; } /// <summary> /// 該參數用於替換模板文件的預約義變量使用({A} {B}) /// </summary> public string CellParamName { get; set; } /// <summary> /// 字符輸出格式(數字和日期類型須要) /// </summary> 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 { /// <summary> /// 單元格字段映射類 /// </summary> internal class ExcelCellFieldMapper { /// <summary> /// 屬性信息 /// </summary> public PropertyInfo PropertyInfo { get; set; } /// <summary> /// 該參數用於收集數據存於固定位置的單元格數據(單元格座標表達式(如:A1,B2,C1+C2...橫座標使用26進制字母,縱座標使用十進制數字)) /// </summary> public string CellCoordinateExpress { get; set; } /// <summary> /// 該參數用於替換模板文件的預約義變量使用({A} {B}) /// </summary> public string CellParamName { get; set; } /// <summary> /// 字符輸出格式(數字和日期類型須要) /// </summary> public string OutputFormat { get; set; } /// <summary> /// 獲取對應關係_T屬性添加了單元格映射關係 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static List<ExcelCellFieldMapper> GetModelFieldMapper<T>() { List<ExcelCellFieldMapper> fieldMapperList = new List<ExcelCellFieldMapper>(100); List<PropertyInfo> tPropertyInfoList = typeof(T).GetProperties().ToList(); ExcelCellAttribute cellExpress = null; foreach (var item in tPropertyInfoList) { cellExpress = item.GetCustomAttribute<ExcelCellAttribute>(); 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 { /// <summary> /// 默認從第1行數據開始讀取標題數據 /// </summary> public ExcelFileDescription() : this(0) { } public ExcelFileDescription(int titleRowIndex) { this.TitleRowIndex = titleRowIndex; } /// <summary> /// 標題所在行位置(默認爲0,沒有標題填-1) /// </summary> 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 { /// <summary> /// Excel標題標記特性 /// </summary> [System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple = false)] public class ExcelTitleAttribute : System.Attribute { /// <summary> /// Excel行標題(標題和下標選擇一個便可) /// </summary> public string RowTitle { get; set; } /// <summary> /// Excel行下標(標題和下標選擇一個便可,默認值-1) /// </summary> public int RowTitleIndex { get; set; } /// <summary> /// 單元格是否要檢查空數據(true爲檢查,爲空的行數據不添加) /// </summary> public bool IsCheckContentEmpty { get; set; } /// <summary> /// 字符輸出格式(數字和日期類型須要) /// </summary> public string OutputFormat { get; set; } /// <summary> /// 是不是公式列 /// </summary> public bool IsCoordinateExpress { get; set; } /// <summary> /// 標題特性構造方法 /// </summary> /// <param name="title">標題</param> /// <param name="isCheckEmpty">單元格是否要檢查空數據</param> /// <param name="isCoordinateExpress">是不是公式列</param> /// <param name="outputFormat">是否有格式化輸出要求</param> 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 { /// <summary> /// Excel標題標記特性 /// </summary> [System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple = false)] public class ExcelTitleAttribute : System.Attribute { /// <summary> /// Excel行標題(標題和下標選擇一個便可) /// </summary> public string RowTitle { get; set; } /// <summary> /// Excel行下標(標題和下標選擇一個便可,默認值-1) /// </summary> public int RowTitleIndex { get; set; } /// <summary> /// 單元格是否要檢查空數據(true爲檢查,爲空的行數據不添加) /// </summary> public bool IsCheckContentEmpty { get; set; } /// <summary> /// 字符輸出格式(數字和日期類型須要) /// </summary> public string OutputFormat { get; set; } /// <summary> /// 是不是公式列 /// </summary> public bool IsCoordinateExpress { get; set; } /// <summary> /// 標題特性構造方法 /// </summary> /// <param name="title">標題</param> /// <param name="isCheckEmpty">單元格是否要檢查空數據</param> /// <param name="isCoordinateExpress">是不是公式列</param> /// <param name="outputFormat">是否有格式化輸出要求</param> 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-單元格映射類:
/// <summary> /// 帳戶_多幣種交易報表_數據源 /// </summary> public class AccountMultiCurrencyTransactionSource { /// <summary> /// 期初 /// </summary> [ExcelCellAttribute("B9")] public decimal BeginingBalance { get; set; } /// <summary> /// 收款 /// </summary> [ExcelCellAttribute("B19+C19")] public decimal TotalTransactionPrice { get; set; } /// <summary> /// 收到非EBay款項_主要指從其餘帳戶轉給當前帳戶的錢 /// </summary> [ExcelCellAttribute("B21+C21")] public decimal TransferAccountInPrice { get; set; } /// <summary> /// 退款(客戶不提交爭議直接退款) /// </summary> [ExcelCellAttribute("B23+C23")] public decimal TotalRefundPrice { get; set; } /// <summary> /// 手續費 /// </summary> [ExcelCellAttribute("B25+C25")] public decimal TotalFeePrice { get; set; } /// <summary> /// 爭議退款 /// </summary> [ExcelCellAttribute("B37+C37")] public decimal TotalChargebackRefundPrice { get; set; } /// <summary> /// 轉帳與提現(幣種轉換) /// </summary> [ExcelCellAttribute("B45+C45")] public decimal CurrencyChangePrice { get; set; } /// <summary> /// 轉帳與提現(轉帳到paypal帳戶)_提現失敗退回金額 /// </summary> [ExcelCellAttribute("B47+C47")] public decimal CashWithdrawalInPrice { get; set; } /// <summary> /// 轉帳與提現(從paypal帳戶轉帳)_提現金額 /// </summary> [ExcelCellAttribute("B49+C49")] public decimal CashWithdrawalOutPrice { get; set; } /// <summary> /// 購物_主要指從當前帳戶轉給其餘帳戶的錢 /// </summary> [ExcelCellAttribute("B51+C51")] public decimal TransferAccountOutPrice { get; set; } /// <summary> /// 其餘活動 /// </summary> [ExcelCellAttribute("B85+C85")] public decimal OtherPrice { get; set; } /// <summary> /// 期末 /// </summary> [ExcelCellAttribute("C9")] public decimal EndingBalance { get; set; } }
示例代碼2-標題映射類(標題映射分類字符串映射和下標位置映射,這裏使用下標位置映射):
/// <summary> /// 美圓幣種轉換_數據源 /// </summary> public class CurrencyChangeUSDSource { /// <summary> /// 日期[y/M/d] /// </summary> [ExcelTitleAttribute(0, true)] public DateTime Date { get; set; } /// <summary> /// 類型 /// </summary> [ExcelTitleAttribute(1, true)] public string Type { get; set; } /// <summary> /// 交易號 /// </summary> [ExcelTitleAttribute(2)] public string TX { get; set; } /// <summary> /// 商家/接收人姓名地址第1行地址第2行/區發款帳戶名稱_發款帳戶簡稱 /// </summary> [ExcelTitleAttribute(3)] public string SendedOrReceivedName { get; set; } /// <summary> /// 電子郵件編號_發款帳戶全稱 /// </summary> [ExcelTitleAttribute(4)] public string SendedOrReceivedAccountName { get; set; } /// <summary> /// 幣種 /// </summary> [ExcelTitleAttribute(5)] public string CurrencyCode { get; set; } /// <summary> /// 總額 /// </summary> [ExcelTitleAttribute(6)] public decimal TotalPrice { get; set; } /// <summary> /// 淨額 /// </summary> [ExcelTitleAttribute(7)] public decimal NetPrice { get; set; } /// <summary> /// 費用 /// </summary> [ExcelTitleAttribute(8)] public decimal FeePrice { get; set; } }
示例代碼3-模板文件數據替換-單元格映射類:
/// <summary> /// 多帳戶美圓彙總金額_最終模板使用展現類 /// </summary> public class AccountUSDSummaryTransaction { /// <summary> /// 期初 /// </summary> [ExcelCellAttribute(cellParamName: "{DLZ_BeginingBalance}")] public decimal DLZ_BeginingBalance { get; set; } /// <summary> /// 收款 /// </summary> [ExcelCellAttribute(cellParamName: "{DLZ_TotalTransactionPrice}")] public decimal DLZ_TotalTransactionPrice { get; set; } /// <summary> /// 收到非EBay款項_主要指從其餘帳戶轉給當前帳戶的錢 /// </summary> [ExcelCellAttribute(cellParamName: "{DLZ_TransferAccountInPrice}")] public decimal DLZ_TransferAccountInPrice { get; set; } /// <summary> /// 退款(客戶不提交爭議直接退款) /// </summary> [ExcelCellAttribute(cellParamName: "{DLZ_TotalRefundPrice}")] public decimal DLZ_TotalRefundPrice { get; set; } /// <summary> /// 手續費 /// </summary> [ExcelCellAttribute(cellParamName: "{DLZ_TotalFeePrice}")] public decimal DLZ_TotalFeePrice { get; set; } /// <summary> /// 爭議退款 /// </summary> [ExcelCellAttribute(cellParamName: "{DLZ_TotalChargebackRefundPrice}")] public decimal DLZ_TotalChargebackRefundPrice { get; set; } /// <summary> /// 轉帳與提現(幣種轉換) /// </summary> [ExcelCellAttribute(cellParamName: "{DLZ_CurrencyChangePrice}")] public decimal DLZ_CurrencyChangePrice { get; set; } /// <summary> /// 轉帳與提現(轉帳到paypal帳戶)_提現失敗退回金額 /// </summary> [ExcelCellAttribute(cellParamName: "{DLZ_CashWithdrawalInPrice}")] public decimal DLZ_CashWithdrawalInPrice { get; set; } /// <summary> /// 轉帳與提現(從paypal帳戶轉帳)_提現金額 /// </summary> [ExcelCellAttribute(cellParamName: "{DLZ_CashWithdrawalOutPrice}")] public decimal DLZ_CashWithdrawalOutPrice { get; set; } /// <summary> /// 購物_主要指從當前帳戶轉給其餘帳戶的錢 /// </summary> [ExcelCellAttribute(cellParamName: "{DLZ_TransferAccountOutPrice}")] public decimal DLZ_TransferAccountOutPrice { get; set; } /// <summary> /// 其餘活動 /// </summary> [ExcelCellAttribute(cellParamName: "{DLZ_OtherPrice}")] public decimal DLZ_OtherPrice { get; set; } /// <summary> /// 期末 /// </summary> [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; } } /// <summary> /// 期末匯率差 /// </summary> [ExcelCellAttribute(cellParamName: "{DLZ_EndingBalanceDifferenceValue}")] public decimal DLZ_EndingBalanceDifferenceValue { get { return this.DLZ_RealRateEndingBalance - this.DLZ_EndingBalance; } } /// <summary> /// 真實匯率計算的期末餘額 /// </summary> [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);