NPOI匯入匯出Excel
阿新 • • 發佈:2020-07-31
最近較忙,上一篇文章的其他交換機沒時間寫,我又遇到一個新需求NPOI匯入匯出Excel,不多廢話了,上原始碼:
簡介:
NPOI 是 POI 專案的 .NET 版本。POI是一個開源的Java讀寫Excel、WORD等微軟OLE2元件文件的專案, 使用 NPOI 你就可以在沒有安裝 Office 或者相應環境的機器上對 WORD/EXCEL 文件進行讀寫。NPOI是構建在POI 3.x版本之上的,它可以在沒有安裝Office的情況下對Word/Excel文件進行讀寫操作。
NPOI的優勢:
1、完全免費的框架 2、包含了大部分EXCEL的特性(單元格樣式、資料格式、公式等等) 3、專業的技術支援服務(24*7全天候) (非免費) 4、支援處理的檔案格式包括xls, xlsx, docx. 5、採用面向介面的設計架構( 可以檢視 NPOI.SS 的名稱空間) 6、同時支援檔案的匯入和匯出 7、基於.net 2.0 也支援xlsx 和 docx格式(當然也支援.net 4.0) 8、你不需要在伺服器上安裝微軟的Office,可以避免版權問題。 9、使用起來比Office PIA的API更加方便,更人性化。 10、你不用去花大力氣維護NPOI,NPOI Team會不斷更新、改善NPOI,絕對省成本。EXCEL匯入
/// <summary> /// 匯入 /// </summary> /// <returns></returns> public JsonResult ExcelImport() { //var files = Request.Files[0]; HttpPostedFileBase fileBase = Request.Files[0]; if (fileBase == null || fileBase.ContentLength <= 0) { return Json("只能上傳Excel檔案!"); } try { //獲取檔案字尾名 string FinName = Path.GetExtension(fileBase.FileName); //獲取檔案內容 Stream streamFile = fileBase.InputStream; DataTable dt= new DataTable(); if (FinName != ".xls" && FinName != ".xlsx") { return Json("只能上傳Excel檔案!"); } else { if (FinName == ".xls") { //建立一個webbook,對應一個Excel檔案(用於xls檔案匯入類) HSSFWorkbook book = new HSSFWorkbook(streamFile); dt = HSSFExcel(dt, book); } else { XSSFWorkbook book = new XSSFWorkbook(streamFile); dt = XSSFExcel(dt, book); } if (dt == null) { return Json("匯入失敗!"); } else { return Json("成功"); } } } catch (Exception ex) { return Json("匯入失敗! " + ex.Message); } }
/// <summary> /// .xls檔案匯入 /// </summary> /// <param name="dt"></param> /// <param name="book"></param> /// <returns></returns> public DataTable HSSFExcel(DataTable dt, HSSFWorkbook book) { // 在webbook中新增一個sheet,對應Excel檔案中的sheet,讀取當前表資料,索引是0 ISheet sheet = book.GetSheetAt(0); //讀取行資料 System.Collections.IEnumerator rows = sheet.GetRowEnumerator(); for (int i = 0; i < (sheet.GetRow(0).LastCellNum); i++) { dt.Columns.Add(sheet.GetRow(0).Cells[i].ToString()); } while (rows.MoveNext()) { HSSFRow row = (HSSFRow)rows.Current; DataRow dr = dt.NewRow(); for (int i = 0; i < row.LastCellNum; i++) { ICell cell = row.GetCell(i); if (cell == null) { dr[i] = null; } else { dr[i] = cell.ToString(); } if (cell != null) { if (cell.CellType == CellType.Numeric && DateUtil.IsCellDateFormatted(cell)) { dr[i] = cell.DateCellValue.ToString("yyyyMMdd HH:ss"); } else { dr[i] = row.GetCell(i).ToString(); } } } dt.Rows.Add(dr); } dt.Rows.RemoveAt(0); return dt; } /// <summary> /// .xlsx檔案匯入 /// </summary> /// <param name="dt"></param> /// <param name="book"></param> /// <returns></returns> public DataTable XSSFExcel(DataTable dt, XSSFWorkbook book) { ISheet sheet = book.GetSheetAt(0); System.Collections.IEnumerator rows = sheet.GetRowEnumerator(); for (int i = 0; i < (sheet.GetRow(0).LastCellNum); i++) { dt.Columns.Add(sheet.GetRow(0).Cells[i].ToString()); } while (rows.MoveNext()) { XSSFRow row = (XSSFRow)rows.Current; DataRow dr = dt.NewRow(); for (int i = 0; i < row.LastCellNum; i++) { ICell cell = row.GetCell(i); if (cell == null) { dr[i] = null; } else { dr[i] = cell.ToString(); } if (cell != null) { if (cell.CellType == CellType.Numeric && DateUtil.IsCellDateFormatted(cell)) dr[i] = cell.DateCellValue.ToString("yyyy/MM/dd HH:ss:mm"); else { dr[i] = row.GetCell(i).ToString(); } } } dt.Rows.Add(dr); } dt.Rows.RemoveAt(0); return dt; }
Excel匯出:
public JsonResult ExcelExport() { List<User> list = new List<User>() { new User (){ Id=1, Age=20, Name="yanboling", Sex="女"}, new User() { Id = 1, Age = 22, Name = "PANLIW", Sex = "男" }, new User() { Id = 1, Age = 21, Name = "CEHNGSHIQI", Sex = "女" }, new User() { Id = 1, Age = 23, Name = "WANGTAO", Sex = "男" } }; var dt = ToDataTable<User>(list); TableToExcel(dt, @"G:\狗糧管夠.xls"); return Json("成功"); }
public static void TableToExcel(DataTable dt, string file) { IWorkbook workbook; //建立workbook string fileExt = Path.GetExtension(file).ToLower(); if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(); } else { workbook = null; } if (workbook == null) { return; } ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("Sheet1") : workbook.CreateSheet(dt.TableName); //表頭 IRow row = sheet.CreateRow(0); for (int i = 0; i < dt.Columns.Count; i++) { ICell cell = row.CreateCell(i); cell.SetCellValue(dt.Columns[i].ColumnName); } //資料 for (int i = 0; i < dt.Rows.Count; i++) { IRow row1 = sheet.CreateRow(i + 1); for (int j = 0; j < dt.Columns.Count; j++) { ICell cell = row1.CreateCell(j); cell.SetCellValue(dt.Rows[i][j].ToString()); } } //轉為位元組陣列 MemoryStream stream = new MemoryStream(); workbook.Write(stream); var buf = stream.ToArray(); //儲存為Excel檔案 using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write)) { fs.Write(buf, 0, buf.Length); fs.Flush(); } }
list轉DataTable:
public static DataTable ToDataTable<T>(List<T> items) { var tb = new DataTable(typeof(T).Name); PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo prop in props) { Type t = prop.PropertyType;//GetCoreType(prop.PropertyType); tb.Columns.Add(prop.Name, t); } foreach (T item in items) { var values = new object[props.Length]; for (int i = 0; i < props.Length; i++) { values[i] = props[i].GetValue(item, null); } tb.Rows.Add(values); } return tb; } public static Type GetCoreType(Type t) { if (t != null && !"".Equals(t)) { if (!t.IsValueType) { return t; } else { return Nullable.GetUnderlyingType(t); } } else { return t; } }
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Sex { get; set; }
public int Age { get; set; }
}
原始碼:
百度網盤:
連結:https://pan.baidu.com/s/1m6Hv50AqhEJRudP6u7Jx1w
提取碼:2180