using Microsoft.VisualBasic; using Npoi.Mapper; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BPA.SAAS.Manage.Comm.Util { public class ReadExcel where T : class, new() { /// /// 导入xlsx /// /// /// public List RedXml(Stream stream) { DataTable dtTable = new DataTable(); List rowList = new List(); ISheet sheet; stream.Position = 0; XSSFWorkbook xssWorkbook = new XSSFWorkbook(stream); sheet = xssWorkbook.GetSheetAt(0); IRow headerRow = sheet.GetRow(0); int cellCount = headerRow.LastCellNum; for (int j = 0; j < cellCount; j++) { ICell cell = headerRow.GetCell(j); if (cell == null || string.IsNullOrWhiteSpace(cell.ToString())) continue; { dtTable.Columns.Add(cell.ToString()); } } for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) { IRow row = sheet.GetRow(i); if (row == null) continue; if (row.Cells.All(d => d.CellType == CellType.Blank)) continue; for (int j = row.FirstCellNum; j < cellCount; j++) { if (row.GetCell(j) != null) { if (!string.IsNullOrEmpty(row.GetCell(j).ToString()) && !string.IsNullOrWhiteSpace(row.GetCell(j).ToString())) { rowList.Add(row.GetCell(j).ToString()); } } } if (rowList.Count > 0) dtTable.Rows.Add(rowList.ToArray()); rowList.Clear(); } var data = DataTableUitity.DatatTableToList(dtTable); return data; } /// /// Excel转为List /// /// /// /// /// public List ExcelToList(Stream fileStream, Mapper mapper, string sheetname = "") { List ModelList = new List(); // var mapper = new Mapper(fileStream); List> DataList = new List>(); if (!string.IsNullOrEmpty(sheetname)) { DataList = mapper.Take(sheetname).ToList(); } else { DataList = mapper.Take().ToList(); } if (DataList != null && DataList.Count > 0) { foreach (var item in DataList) { ModelList.Add(item.Value); } } return ModelList; } /// /// List转Excel /// /// /// 数据 /// 表名 /// true,覆盖单元格,false追加内容(list和创建的excel或excel模板) /// true-xlsx,false-xls /// 返回文件 public MemoryStream ListToExcel(List list, string sheetName = "sheet1", bool overwrite = true, bool xlsx = true) { var mapper = new Mapper(); MemoryStream ms = new MemoryStream(); mapper.Save(ms, list, sheetName, overwrite, xlsx); return ms; } } }