|
- 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<T> where T : class, new()
- {
- /// <summary>
- /// 导入xlsx
- /// </summary>
- /// <param name="stream"></param>
- /// <returns></returns>
- public List<T> RedXml(Stream stream)
- {
- DataTable dtTable = new DataTable();
- List<string> rowList = new List<string>();
- 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<T>(dtTable);
- return data;
- }
- /// <summary>
- /// Excel转为List
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="fileStream"></param>
- /// <param name="sheetname"></param>
- /// <returns></returns>
- public List<T> ExcelToList(Stream fileStream, Mapper mapper, string sheetname = "")
- {
- List<T> ModelList = new List<T>();
- // var mapper = new Mapper(fileStream);
- List<RowInfo<T>> DataList = new List<RowInfo<T>>();
- if (!string.IsNullOrEmpty(sheetname))
- {
- DataList = mapper.Take<T>(sheetname).ToList();
- }
- else
- {
- DataList = mapper.Take<T>().ToList();
- }
- if (DataList != null && DataList.Count > 0)
- {
- foreach (var item in DataList)
- {
- ModelList.Add(item.Value);
- }
- }
-
- return ModelList;
- }
- /// <summary>
- /// List转Excel
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="list">数据</param>
- /// <param name="sheetName">表名</param>
- /// <param name="overwrite">true,覆盖单元格,false追加内容(list和创建的excel或excel模板)</param>
- /// <param name="xlsx">true-xlsx,false-xls</param>
- /// <returns>返回文件</returns>
- public MemoryStream ListToExcel(List<T> list, string sheetName = "sheet1", bool overwrite = true, bool xlsx = true)
- {
- var mapper = new Mapper();
- MemoryStream ms = new MemoryStream();
- mapper.Save<T>(ms, list, sheetName, overwrite, xlsx);
- return ms;
- }
- }
- }
|