版權聲明:做者:真愛無限 出處:http://blog.csdn.net/pukuimin1226 本文爲博主原創文章版權歸做者全部,歡迎轉載,但未經做者贊成必須保留此段聲明,且在文章頁面明顯位置給出原文連接.ide
大部分功能邏輯都在,少許自定義異常類和擴展方法 ,可用相似代碼本身替換ui
//EpPlus讀取生成Excel幫助類+讀取csv幫助類,epplus只支持開放的Excel文件格式:xlsx,不支持 xls格式spa
- using OfficeOpenXml;
- using OfficeOpenXml.Style;
- using System;
- using System.Collections.Concurrent;
- using System.Collections.Generic;
- using System.Data;
- using System.Drawing;
- using System.IO;
- using System.Linq;
- using System.Linq.Expressions;
- using System.Reflection;
- using System.Text;
- using System.Text.RegularExpressions;
- using System.Threading.Tasks;
- using YCF.HRMS.Utilities.ExceptionHeper;
- using YCF.HRMS.Utilities.ExtensionHelper;
- namespace YCF.HRMS.Utilities.CommomHelper
- {
-
-
-
- public class EppHelper
- {
- #region 由List建立簡單Exel.列頭取字段的Description或字段名
-
-
-
-
-
-
- public static void CreateExcelByList<T>(string filePath, List<T> dataList) where T : class
- {
-
- string dirPath = Path.GetDirectoryName(filePath);
- string fileName = Path.GetFileName(filePath);
- FileInfo newFile = new FileInfo(filePath);
- if (newFile.Exists)
- {
- newFile.Delete();
- newFile = new FileInfo(filePath);
- }
- PropertyInfo[] properties = null;
- if (dataList.Count > 0)
- {
- Type type = dataList[0].GetType();
- properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
- var filedDescriptions = CommonFunctions.GetPropertyDescriptions<T>(true);
- using (ExcelPackage package = new ExcelPackage(newFile))
- {
- ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("sheet1");
-
- using (var range = worksheet.Cells[1, 1, 1, properties.Length])
- {
- range.Style.Font.Bold = true;
- range.Style.Fill.PatternType = ExcelFillStyle.Solid;
- range.Style.Fill.BackgroundColor.SetColor(Color.DarkBlue);
- range.Style.Font.Color.SetColor(Color.White);
- }
- int row = 1, col;
- object objColValue;
- string colValue;
-
- for (int j = 0; j < properties.Length; j++)
- {
- row = 1;
- col = j + 1;
- var description = filedDescriptions.Where(o => o.Key == properties[j].Name).Select(o => o.Value).FirstOrDefault();
- worksheet.Cells[row, col].Value = (description == null || description.Description.IsNullOrEmpty()) ? properties[j].Name : description.Description;
- }
- worksheet.View.FreezePanes(row + 1, 1);
-
- for (int i = 0; i < dataList.Count; i++)
- {
- row = i + 2;
- for (int j = 0; j < properties.Length; j++)
- {
- col = j + 1;
- objColValue = properties[j].GetValue(dataList[i], null);
- colValue = objColValue == null ? "" : objColValue.ToString();
- worksheet.Cells[row, col].Value = colValue;
- }
- }
- package.Save();
- }
-
- }
- }
- #endregion
-
- #region 讀取Excel數據到DataSet
-
-
-
-
-
- public static DataSet ReadExcelToDataSet(string filePath)
- {
- DataSet ds = new DataSet("ds");
- DataRow dr;
- object objCellValue;
- string cellValue;
- using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite))
- using (ExcelPackage package = new ExcelPackage())
- {
- package.Load(fs);
- foreach (var sheet in package.Workbook.Worksheets)
- {
- if (sheet.Dimension == null) continue;
- var columnCount = sheet.Dimension.End.Column;
- var rowCount = sheet.Dimension.End.Row;
- if (rowCount > 0)
- {
- DataTable dt = new DataTable(sheet.Name);
- for (int j = 0; j < columnCount; j++)
- {
- objCellValue = sheet.Cells[1, j + 1].Value;
- cellValue = objCellValue == null ? "" : objCellValue.ToString();
- dt.Columns.Add(cellValue, typeof(string));
- }
- for (int i = 2; i <= rowCount; i++)
- {
- dr = dt.NewRow();
- for (int j = 1; j <= columnCount; j++)
- {
- objCellValue = sheet.Cells[i, j].Value;
- cellValue = objCellValue == null ? "" : objCellValue.ToString();
- dr[j - 1] = cellValue;
- }
- dt.Rows.Add(dr);
- }
- ds.Tables.Add(dt);
- }
- }
- }
- return ds;
-
- }
- #endregion
-
- #region 讀取csv數據到List<T>,列頭與字段的Description對應
-
-
-
-
-
-
- public static List<T> ReadCsvToModelList<T>(string filePath, string uploadMonth, long userId) where T : class
- {
- List<T> list = new List<T>();
- object objCellValue;
- string cellValue;
- string columnName;
- var filedDescriptions = CommonFunctions.GetPropertyDescriptions<T>(false);
- var fieldIndexs = new List<KeyValuePair<int, FieldDescriptionModel>>();
- int lineCount = 1;
- string mes = "";
- Type type = typeof(T);
- int iUserId = int.Parse(userId.ToString());
- var properties = type.GetProperties();
- using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
- using (StreamReader sr = new StreamReader(fs, Encoding.Default))
- {
-
- string line;
- var columnCount = 0;
- bool isEmptyCellValue = false;
- while (true)
- {
- isEmptyCellValue = false;
- line = sr.ReadLine();
- if (string.IsNullOrWhiteSpace(line))
- {
- break;
- }
- string[] split = SplitCsvLine(line);
- if (lineCount == 1)
- {
- columnCount = split.Length;
- for (int j = 0; j < columnCount; j++)
- {
- objCellValue = split[j];
- cellValue = objCellValue == null ? "" : objCellValue.ToString();
- var cellFieldName = filedDescriptions.Where(o => o.Key == cellValue).Select(o => o.Value).FirstOrDefault();
- fieldIndexs.Add(new KeyValuePair<int, FieldDescriptionModel>(j, cellFieldName));
- }
- lineCount++;
- continue;
- }
-
-
- if (string.IsNullOrWhiteSpace(split[0]))
- {
- break;
- }
- if (split.Length > columnCount)
- {
- mes += lineCount.ToString() + ",";
- lineCount++;
- continue;
- }
- if (split.Length < columnCount)
- {
- mes += lineCount.ToString() + ",";
- lineCount++;
- continue;
- }
- T model = Activator.CreateInstance<T>();
-
- for (int j = 0; j < columnCount; j++)
- {
- objCellValue = split[j];
- var field = fieldIndexs.First(o => o.Key == j).Value;
- columnName = field.FieldName;
- if (columnName.IsNullOrEmpty()) continue;
- PropertyInfo p = properties.FirstOrDefault(o => string.Equals(o.Name, columnName, StringComparison.InvariantCultureIgnoreCase));
- if (p == null) continue;
- SetPropertyValue<T>(ref model, ref p, ref objCellValue, ref field, ref isEmptyCellValue);
- }
- if (isEmptyCellValue)
- {
- continue;
- }
- SetPropertyValueForKnowColumns<T>(ref model, ref properties, ref uploadMonth, ref userId, ref iUserId);
- list.Add(model);
- lineCount++;
- }
- }
- if (mes != "") throw new BusinessException("第" + mes.TrimEnd(',') + "行讀取有誤,請檢查該行單元格內是否有逗號");
- #region 判斷第一行數據是否合格,Excel列名和字段對不上的狀況,檢查一個就等於檢查所有
- var firstModel = list.FirstOrDefault();
- CheckModelRequiredData<T>(ref firstModel, ref properties, ref filedDescriptions);
- #endregion
- return list;
- }
-
- #endregion
-
- #region 設置字段屬性的值
-
-
-
-
-
-
-
-
-
-
- private static void SetPropertyValue<T>(ref T model, ref PropertyInfo p, ref object objCellValue, ref FieldDescriptionModel field, ref bool isEmptyCellValue) where T : class
- {
- var propertyType = p.PropertyType.ToString();
- switch (propertyType)
- {
- case "System.String":
- {
- if (objCellValue is string == false)
- {
- if (objCellValue == null) objCellValue = "";
- else objCellValue = objCellValue.ToString();
- if (field.IsRequire && objCellValue.ToString() == "")
- {
- isEmptyCellValue = true;
- break;
- }
- }
- if (objCellValue != null) objCellValue = objCellValue.ToString().Replace("\r\n", "").Trim();
- }
- break;
- case "System.Decimal":
- case "System.Nullable`1[System.Decimal]":
- {
- if (objCellValue is decimal == false)
- {
- if (objCellValue != null)
- {
- if (objCellValue.ToString().EndsWith("%"))
- {
- objCellValue = Convert.ToDecimal(objCellValue.ToString().TrimEnd('%')) / 100M;
- }
- else objCellValue = Convert.ToDecimal(objCellValue.ToString());
- }
- }
- }
- break;
- case "System.Int32":
- case "System.Nullable`1[System.Int32]":
- {
- if (objCellValue is int == false)
- {
- if (objCellValue != null) objCellValue = Convert.ToInt32(objCellValue);
- }
- }
- break;
- case "System.Int64":
- case "System.Nullable`1[System.Int64]":
- {
- if (objCellValue is long == false)
- {
- if (objCellValue != null) objCellValue = Convert.ToInt64(objCellValue);
- }
- }
- break;
- case "System.DateTime":
- case "System.Nullable`1[System.DateTime]":
- {
- if (objCellValue is DateTime == false)
- {
- if (objCellValue != null) objCellValue = ToDateTimeValue(objCellValue.ToString());
- }
- }
- break;
- case "System.Boolean":
- case "System.Nullable`1[System.Boolean]":
- {
- if (objCellValue is bool == false)
- {
-
- if (objCellValue != null)
- {
- var tempValue = objCellValue.ToString().Trim();
- if (tempValue == "#N/A") tempValue = "";
- else if (tempValue == "是") tempValue = "True";
- else if (tempValue == "否") tempValue = "False";
- if (tempValue != "") objCellValue = Convert.ToBoolean(tempValue);
- else objCellValue = null;
- }
- }
- }
- break;
- }
- try
- {
- p.SetValue(model, objCellValue, null);
- }
- catch (Exception ex)
- {
- throw new BusinessException("出錯,字段名:" + p.Name + ",類型:" + p.PropertyType.ToString() + ",數據:" + (objCellValue == null ? "" : objCellValue.ToString()) + ",錯誤信息:" + ex.Message);
- }
- }
- #endregion
-
- #region 其餘已知屬性賦默認值
-
-
-
-
-
-
-
-
-
- private static void SetPropertyValueForKnowColumns<T>(ref T model, ref PropertyInfo[] properties, ref string uploadMonth, ref long userId, ref int iUserId)
- {
- var monthProperty = properties.FirstOrDefault(o => string.Equals(o.Name, "Month", StringComparison.InvariantCultureIgnoreCase));
- if (monthProperty != null)
- {
- monthProperty.SetValue(model, uploadMonth, null);
- }
- var createTimeProperty = properties.FirstOrDefault(o => string.Equals(o.Name, "CreationTime", StringComparison.InvariantCultureIgnoreCase));
- if (createTimeProperty != null)
- {
- createTimeProperty.SetValue(model, DateTime.Now, null);
- }
- var modifyTimeProperty = properties.FirstOrDefault(o => string.Equals(o.Name, "LastModificationTime", StringComparison.InvariantCultureIgnoreCase));
- if (modifyTimeProperty != null)
- {
- modifyTimeProperty.SetValue(model, DateTime.Now, null);
- }
- var createUserIdProperty = properties.FirstOrDefault(o => string.Equals(o.Name, "CreatorUserId", StringComparison.InvariantCultureIgnoreCase));
- if (createUserIdProperty != null)
- {
- if (createTimeProperty.PropertyType.ToString() == "System.Int32") createUserIdProperty.SetValue(model, iUserId, null);
- else createUserIdProperty.SetValue(model, userId, null);
- }
- }
- #endregion
-
- #region 最後判斷第一行數據是否合格,Excel列名和字段對不上的狀況,檢查一個就等於檢查所有
-
-
-
-
-
-
- private static void CheckModelRequiredData<T>(ref T firstModel, ref PropertyInfo[] properties, ref List<KeyValuePair<string, FieldDescriptionModel>> filedDescriptions)
- {
- if (firstModel != null)
- {
- var fieldNameList = filedDescriptions.Where(o => o.Value != null).Select(o => o.Value).ToList();
-
- foreach (var p in properties)
- {
- var fieldNameModel = fieldNameList.FirstOrDefault(o => string.Equals(o.FieldName, p.Name, StringComparison.InvariantCultureIgnoreCase));
- if (fieldNameModel == null || fieldNameModel.IsRequire == false) continue;
- object objCellValue = p.GetValue(firstModel);
- if (objCellValue == null || objCellValue.ToString() == "")
- {
- throw new BusinessException("出錯,字段名:" + p.Name + ",類型:" + p.PropertyType.ToString() + " 必填字段數據爲空!");
- }
- }
- }
- }
- #endregion
-
- #region 讀取Excel數據到List<T>,列頭與字段的Description對應
-
-
-
-
-
-
- public static List<T> ReadExcelToModelList<T>(string filePath, string uploadMonth, long userId, out string log, int titleRow = 1) where T : class
- {
- ExcelPackage package = null;
- FileStream fs = null;
- try
- {
-
- List<T> list = new List<T>();
- log = string.Format("{0:yyyy-MM-dd HH:mm:ss}開始載入文件{1}\r\n", DateTime.Now, filePath);
- var filedDescriptions = CommonFunctions.GetPropertyDescriptions<T>(false);
- var fieldIndexs = new List<KeyValuePair<int, FieldDescriptionModel>>();
- fs = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite);
- package = new ExcelPackage();
- package.Load(fs);
- log += string.Format("{0:yyyy-MM-dd HH:mm:ss}完成載入文件{1},開始解析\r\n", DateTime.Now, filePath);
- if (package.Workbook.Worksheets.Count == 0)
- {
- throw new BusinessException("讀取的Excel中sheet數量爲0,請檢查文件格式是否爲xlsx!");
- }
- var sheet = package.Workbook.Worksheets[1];
-
- if (sheet.Dimension == null) return list.ToList();
- var columnCount = sheet.Dimension.End.Column;
- var rowCount = sheet.Dimension.End.Row;
- if (rowCount == 0) return list.ToList();
-
- for (int j = 1; j <= columnCount; j++)
- {
- object objCellValue = sheet.Cells[titleRow, j].Value;
- string cellValue = objCellValue == null ? "" : objCellValue.ToString();
- if (cellValue.Len() == 0) continue;
- var cellFieldName = filedDescriptions.Where(o => o.Key == cellValue).Select(o => o.Value).FirstOrDefault();
- fieldIndexs.Add(new KeyValuePair<int, FieldDescriptionModel>(j, cellFieldName));
-
- }
- Type type = typeof(T);
- int iUserId = int.Parse(userId.ToString());
- var properties = type.GetProperties();
-
-
- for (int i = titleRow + 1; i <= rowCount; i++)
- {
- #region 處理Excel每行數據
- object objCellValue = null;
- string columnName = null;
- bool isEmptyCellValue = false;
- T model = Activator.CreateInstance<T>();
- for (int j = 1; j <= columnCount; j++)
- {
- objCellValue = sheet.Cells[i, j].Value;
- var fieldPair = fieldIndexs.FirstOrDefault(o => o.Key == j);
- var field = fieldPair.Value;
- columnName = field == null ? "" : field.FieldName;
- if (columnName.IsNullOrEmpty()) continue;
- PropertyInfo p = properties.FirstOrDefault(o => string.Equals(o.Name, columnName, StringComparison.InvariantCultureIgnoreCase));
- if (p == null) continue;
- SetPropertyValue<T>(ref model, ref p, ref objCellValue, ref field, ref isEmptyCellValue);
-
- }
- if (!isEmptyCellValue)
- {
- SetPropertyValueForKnowColumns<T>(ref model, ref properties, ref uploadMonth, ref userId, ref iUserId);
- list.Add(model);
- }
-
- #endregion
- }
-
- #region 判斷第一行數據是否合格,Excel列名和字段對不上的狀況,檢查一個就等於檢查所有
- var firstModel = list.FirstOrDefault();
- CheckModelRequiredData<T>(ref firstModel, ref properties, ref filedDescriptions);
- #endregion
- log += string.Format("{0:yyyy-MM-dd HH:mm:ss}完成解析文件{1}\r\n", DateTime.Now, filePath);
- return list;
- }
- finally
- {
- if (package != null) package.Dispose();
- if (fs != null)
- {
- fs.Close(); fs.Dispose();
- }
- }
-
- }
- #endregion
-
- #region Splits the CSV line.
-
-
-
-
-
- private static string[] SplitCsvLine(string s)
- {
- Regex regex = new Regex("\".*?\"");
- var a = regex.Matches(s).Cast<Match>().Select(m => m.Value).ToList();
- var b = regex.Replace(s, "%_%");
- var c = b.Split(',');
- for (int i = 0, j = 0; i < c.Length && j < a.Count; i++)
- {
- if (c[i] == "%_%")
- {
- c[i] = a[j++];
- }
- }
- return c;
- }
- #endregion
-
- #region Excel中數字時間轉換成時間格式
-
-
-
-
-
- public static DateTime ToDateTimeValue(string strNumber)
- {
- if (!string.IsNullOrWhiteSpace(strNumber))
- {
- Decimal tempValue;
- DateTime tempret;
- if (DateTime.TryParse(strNumber, out tempret))
- {
- return tempret;
- }
- if (strNumber.Length == 8 && strNumber.Contains(".") == false)
- {
-
- strNumber = strNumber.Insert(4, "-").Insert(6 + 1, "-");
- if (DateTime.TryParse(strNumber, out tempret))
- {
- return tempret;
- }
- else return default(DateTime);
- }
-
- if (Decimal.TryParse(strNumber, out tempValue))
- {
-
- int day = Convert.ToInt32(Math.Truncate(tempValue));
-
-
-
- DateTime dt = new DateTime(1900, 1, 1).AddDays(day < 32 ? (day - 1) : (day - 2));
-
-
- Decimal hourTemp = (tempValue - day) * 24;
-
- int hour = Convert.ToInt32(Math.Truncate(hourTemp));
-
-
- Decimal minuteTemp = Math.Round((hourTemp - hour) * 60, 2);
- int minute = Convert.ToInt32(Math.Truncate(minuteTemp));
-
-
-
- Decimal secondTemp = Math.Round((minuteTemp - minute) * 60, 2);
- int second = Convert.ToInt32(Math.Truncate(secondTemp));
- if (second >= 60)
- {
- second -= 60;
- minute += 1;
- }
- if (minute >= 60)
- {
- minute -= 60;
- hour += 1;
- }
-
-
- string resultTimes = string.Format("{0}:{1}:{2}",
- (hour < 10 ? ("0" + hour) : hour.ToString()),
- (minute < 10 ? ("0" + minute) : minute.ToString()),
- (second < 10 ? ("0" + second) : second.ToString()));
- var str = string.Format("{0} {1}", dt.ToString("yyyy-MM-dd"), resultTimes);
- try
- {
- return DateTime.Parse(str);
- }
- catch (Exception ex)
- {
- throw new Exception("DateTime.Parse出錯,str:" + str, ex);
- }
-
- }
- }
- return default(DateTime);
- }
- #endregion
-
- }
- }
//Aspose.Cells生成xlsx文件幫助類.net
- using Aspose.Cells;
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.ComponentModel.DataAnnotations;
- using System.Linq;
- using System.Linq.Expressions;
- using System.Reflection;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace YCF.HRMS.Utilities.CommomHelper
- {
-
-
-
- public static class AsposeCellsHelper
- {
- public static void CreateExcel<T>(IEnumerable<T> content, string filePath, string sheetName, int startRow,bool setBorder = false, string getColorMethodName = null)
- {
- var columnsAccessor = CreateColumnsAccessor<T>();
- var colInvoker = ExpressionHelper.GetMemberAccessor(columnsAccessor);
- var t = typeof(T);
-
- Workbook workbook = new Workbook();
-
- var sheet = workbook.Worksheets[0]; ;
- sheet.Name = sheetName;
- var freezeAttr = t.GetCustomAttribute<ExcelFreezeAttribute>();
-
- if (freezeAttr != null)
- sheet.FreezePanes(startRow + 1, 0 + 1, freezeAttr.FreezeRowIndex + startRow + 1, freezeAttr.FreezeColumnIndex + 1);
-
- var cells = workbook.Worksheets[0].Cells;
- int rowIndex = startRow;
- int colIndex = 0;
- for (int i = 0; i < colInvoker.Count(); i++)
- {
- var col = colInvoker.ElementAt(i);
-
- var widthAttr = col.Key.GetCustomAttribute<ExcelColumnAttribute>();
- if (widthAttr != null)
- {
-
- if (widthAttr.Hide)
- {
- colInvoker.Remove(col.Key);
- i--;
- continue;
- }
- }
- var title = col.Key.Name;
- var desc = col.Key.GetCustomAttribute<DescriptionAttribute>();
- if (desc != null)
- title = desc.Description;
- else
- {
- var display = col.Key.GetCustomAttribute<DisplayAttribute>();
- if (display != null)
- title = display.Name;
- }
- var myCell = sheet.Cells[rowIndex, colIndex];
- Style style = myCell.GetStyle();
- myCell.PutValue(title);
- style.Font.IsBold = true;
- style.HorizontalAlignment = TextAlignmentType.Center;
- style.Font.Name = "宋體";
- style.Font.Size = 10;
- if (setBorder)
- {
- style.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;
- style.Borders[BorderType.BottomBorder].Color = System.Drawing.Color.Black;
- style.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin;
- style.Borders[BorderType.TopBorder].Color = System.Drawing.Color.Black;
- style.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin;
- style.Borders[BorderType.LeftBorder].Color = System.Drawing.Color.Black;
- style.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin;
- style.Borders[BorderType.RightBorder].Color = System.Drawing.Color.Black;
- }
- myCell.SetStyle(style);
- cells.SetColumnWidth(colIndex, 15);
- colIndex++;
- }
-
- rowIndex++;
-
- PropertyInfo[] properties = colInvoker.Keys.OfType<PropertyInfo>().ToArray();
- Func<T, string> getHtmlColorFunc = null;
- if(getColorMethodName != null)
- {
- MethodInfo getColorMethod = typeof(T).GetMethod(getColorMethodName);
- if (getColorMethod != null)
- {
- var parameter = Expression.Parameter(typeof(T));
- getHtmlColorFunc = Expression.Lambda<Func<T, string>>(Expression.Call(parameter, getColorMethod), parameter).Compile();
- }
- }
-
-
- Func<PropertyInfo, Cell, Style> colunmnStyles = (p, cell) =>
- {
- Style style = cell.GetStyle();
- var type = p.PropertyType;
- if (type.IsGenericType)
- {
- type = type.GetGenericArguments()[0];
- }
- if (type == typeof(DateTime))
- {
- style.Custom = "yyyyMMdd";
- }
- else if (type == typeof(double) || type == typeof(decimal))
- {
- style.Custom = "0.00";
- }
- style.Font.Name = "宋體";
- style.Font.Size = 10;
- return style;
- };
- var propertyValueSetter = properties.ToDictionary(p => p, p =>
- {
- Action<object, Cell> valueSetter;
- var type = p.PropertyType;
- if (type.IsGenericType)
- {
- type = type.GetGenericArguments()[0];
- }
- if (type == typeof(DateTime))
- {
- valueSetter = (o, cell) =>
- {
- if (o != null)
- {
- cell.PutValue(Convert.ToDateTime(o));
- }
- };
- }
- else if (type == typeof(double) || type == typeof(decimal) || type == typeof(int))
- {
- valueSetter = (o, cell) =>
- {
- if (o != null)
- {
- cell.PutValue(Convert.ToDouble(o));
- }
- };
- }
- else
- {
- valueSetter = (o, cell) =>
- {
- if (o != null)
- {
- cell.PutValue(o.ToString());
- }
- };
- }
- return valueSetter;
- });
-
-
- foreach (var item in content)
- {
- colIndex = 0;
-
- foreach (var propertyInfo in properties)
- {
- object value = propertyInfo.GetValue(item);
- var cell = sheet.Cells[rowIndex, colIndex++];
- propertyValueSetter[propertyInfo](value, cell);
- var style = colunmnStyles(propertyInfo, cell);
- if (getHtmlColorFunc != null)
- {
-
- style.ForegroundColor = System.Drawing.ColorTranslator.FromHtml(getHtmlColorFunc(item));
- style.Pattern = BackgroundType.Solid;
- }
- if (setBorder)
- {
- style.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;
- style.Borders[BorderType.BottomBorder].Color = System.Drawing.Color.Black;
- style.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin;
- style.Borders[BorderType.TopBorder].Color = System.Drawing.Color.Black;
- style.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin;
- style.Borders[BorderType.LeftBorder].Color = System.Drawing.Color.Black;
- style.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin;
- style.Borders[BorderType.RightBorder].Color = System.Drawing.Color.Black;
- }
- cell.SetStyle(style);
- }
- rowIndex++;
- }
-
- workbook.Save(filePath, new Aspose.Cells.OoxmlSaveOptions(Aspose.Cells.SaveFormat.Xlsx));
- workbook.Worksheets.Clear();
- }
-
- internal static Expression<Func<T, object>> CreateColumnsAccessor<T>()
- {
- var type = typeof(T);
- var ps = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
- var bindings = new List<MemberBinding>();
- var parameter = Expression.Parameter(type, "p");
- foreach (var p in ps)
- {
- bindings.Add(Expression.Bind(p, Expression.MakeMemberAccess(parameter, p)));
- }
- var creator = Expression.MemberInit(Expression.New(type), bindings);
- var columnsAccessor = Expression.Lambda<Func<T, object>>(creator, parameter);
- return columnsAccessor;
- }
- }
-
-
-
-
- [AttributeUsage(AttributeTargets.Property)]
- public class ExcelColumnAttribute : Attribute
- {
- public int Width { get; set; }
- public bool Hide { get; set; }
- }
-
-
-
-
- [AttributeUsage(AttributeTargets.Class)]
- public class ExcelCellStyleAttribute : Attribute
- {
- public string HtmlColorAccessor { get; set; }
- }
-
-
-
-
- [AttributeUsage(AttributeTargets.Class)]
- public class ExcelFreezeAttribute : Attribute
- {
- public int FreezeColumnIndex { get; set; }
- public int FreezeRowIndex { get; set; }
- }
- }
aspose引用:packages\Aspose.Cells\7.0.3(2011-11-12)\Aspose.Cells.dll
excel
以前寫過npoi的讀取excel的文章,如今epplus也能夠。orm
對比:xml
npoi可讀寫xls和xlsx,epplus只支持讀寫xlsx. 讀寫效率應該都差不了多少,寫入少許數據可用這兩個,大量數據寫的話最好要用aspose。對象
aspose寫入速度比npoi和epplus快。blog