EPPlus是一個使用Open Office XML(xlsx)文件格式,能讀寫Excel 2007/2010 文件的開源組件,在導出Excel的時候不須要電腦上安裝office,它的一個缺點就是不支持導出2003版的Excel(xls)。app
在此以前,先引入nuget包:EPPlus.Core 測試
1 [HttpGet] 2 public IActionResult Export() 3 { 4 string sWebRootFolder = hostingEnv.WebRootPath; 5 string sFileName = $@"qmhuangtext{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx"; 6 var path = Path.Combine(sWebRootFolder, sFileName); 7 FileInfo file = new FileInfo(path); 8 //構建數據 9 List<Person> list1 = new List<Person>() 10 { 11 new Person{Name = "123",Sex="男"}, 12 new Person{Name = "234",Sex="男"}, 13 new Person{Name = "345",Sex="女"} 14 }; 15 if (file.Exists) 16 { 17 file.Delete(); 18 file = new FileInfo(path); 19 } 20 using (ExcelPackage package = new ExcelPackage(file)) 21 { 22 //建立sheet 23 ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(「sheetname」); 25 worksheet.Cells.LoadFromCollection(list1 ,true); 26 package.Save(); //Save the workbook. 27 } 28 return File(new FileStream(Path.Combine(sWebRootFolder, sFileName), FileMode.Open), "application/octet-stream", $"excel導出測試{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx"); 29 }
在導出時有不少種數據Resource能夠選擇,好比上面的 LoadFromCollection ,還有 LoadFromDataTable , LoadFromText 等方法spa
worksheet.Cells.LoadFromCollection(list1 ,true); //此方法第二個參數決定是否打印表頭,第一行標題欄
1 /// <summary> 2 /// 讀取sheet 內的數據進入實體 3 /// </summary> 4 /// <param name="worksheet"></param> 5 /// <returns></returns> 6 public List<Person> GetSheetValues(string filepath) 7 { 8 FileInfo file = new FileInfo(filepath); 9 if (file != null) 10 { 11 using (ExcelPackage package = new ExcelPackage(file)) 12 { 13 14 ExcelWorksheet worksheet = package.Workbook.Worksheets[0]; 15 //獲取表格的列數和行數 16 int rowCount = worksheet.Dimension.Rows; 17 int ColCount = worksheet.Dimension.Columns; 18 var persons = new List<Person>(); 19 for (int row = 1; row <= rowCount; row++) 20 { 21 Person person = new Person(); 22 person.Name = worksheet.Cells[row, 1].Value.ToString(); 23 person.Sex = worksheet.Cells[row, 2].Value.ToString(); 24 persons.Add(person); 25 } 26 return persons; 27 } 28 } 29 return null; 30 }
注:你會發現上面在取數據時,遍歷worksheet時座標是從(1,1)開始的。epplus的頂點就是這個位置,若是你試圖讀取0位置,則會報錯excel