1. 程式人生 > 實用技巧 >.Net Core 讀取,匯入 excel資料 officeopenxml

.Net Core 讀取,匯入 excel資料 officeopenxml

        /// <summary>
        /// 匯出Excel
        /// </summary>
        /// <param name="path">路徑</param>
        /// <param name="tableHeaders">表頭,Dictionary<propname,name> propname屬性名 ,name表頭名稱</param>
        /// <param name="data"></param>
        /// <returns></returns>
public static string Export(string path, Dictionary<string, string> tableHeaders, Object[] data) { string fileName = $"{Guid.NewGuid()}.xlsx"; var filePath = $"{path}\\{fileName}"; FileInfo file = new FileInfo(filePath); try {
using (ExcelPackage package = new ExcelPackage(file)) { ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("exportdata"); var row = 1; for (int i = 0; i < tableHeaders.Count; i++) {
var headName = tableHeaders.ElementAt(i).Value; worksheet.Cells[row, i + 1].Value = headName; } foreach (object item in data) { row++; var propts = item.GetType().GetProperties(); for (int i = 0; i < tableHeaders.Count; i++) { var propName = tableHeaders.ElementAt(i).Key; var check = propts.FirstOrDefault(o => o.Name.ToLower() == propName.ToLower()); if (check == null) worksheet.Cells[row, i + 1].Value = ""; else { var value = check.GetValue(item); worksheet.Cells[row, i + 1].Value = value == null ? "" : value.ToString(); }; } } package.Save(); } } catch (Exception ex) { LogHelper.Singleton.Write(typeof(ExcelHelper), ex); return null; } return filePath; }
  /// <summary>
        /// 匯入資料
        /// </summary>
        /// <param name="filePath">檔案</param>
        /// <returns></returns>
        public static List<SchoolModel> ImportSchool(string filePath)
        {
            FileInfo file = new FileInfo(filePath);
            List<SchoolModel> result = new List<SchoolModel>();
            if (file.Length == 0) return null;
            using (ExcelPackage package = new ExcelPackage(file))
            {
                //訪問Excel的第一張表
                ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
                //獲取表格不為空的數
                int rowCount = worksheet.Cells.Where(o=>o.Value!=null).Count();
                //獲取表格列數
                int columnsCount = worksheet.Dimension.Columns;
          //跳過表頭從第二行,讀取資料
for (int row = 2; row <= rowCount; row++) { if (row < 2) return null; if (worksheet.Cells[row, 1].Value == null || worksheet.Cells[row, 2].Value == null || worksheet.Cells[row, 3].Value == null || worksheet.Cells[row, 4].Value == null || worksheet.Cells[row, 5].Value == null || worksheet.Cells[row, 6].Value == null) { continue; } result.Add(new SchoolModel() { SchoolName = worksheet.Cells[row, 1].Value.ToString(), SchoolCode = worksheet.Cells[row, 2].Value.ToString(), SubjectName = worksheet.Cells[row, 3].Value.ToString(), SubjectCode = worksheet.Cells[row, 4].Value.ToString(), SchoolSystem = worksheet.Cells[row, 5].Value.ToString(), TuitionStandard = decimal.Parse(worksheet.Cells[row, 6].Value.ToString()), }); } package.SaveAs(file); } return result; }
///資料模型類
public class SchoolModel
{
  public string SchoolName { get; set; }
  public string SchoolCode { get; set; }
  public string SubjectName { get; set; }
  public string SubjectCode { get; set; }
  public string SchoolSystem { get; set; }
  public decimal TuitionStandard { get; set; }
}