NPOI List导入Excel

        public static bool ExportE<T>(string output, string fileName, List<T> datalist, Dictionary<string, string> name) where T : class
        {
            try
            {
                if (datalist.Count <= 0)
                {
                    return false;
                }
                //HSSFWorkbook => xls
                //XSSFWorkbook => xlsx
                IWorkbook workbook;
                string fileExt = Path.GetExtension(fileName).ToLower();
                if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(); } else { workbook = null; }
                if (workbook == null) { return false; }

                设置工作簿的名称
                //var sheetName = string.IsNullOrEmpty(fileName) ? "sheet1" : fileName;
                //创建工作表
                ISheet sheet = workbook.CreateSheet("Sheet1");//名称自定义

                PropertyInfo[] propertyInfos = datalist[0].GetType().GetProperties();//获取公共属性

                ICellStyle styleTitle = workbook.CreateCellStyle();
                styleTitle.WrapText = true;//自动换行

                IRow cellsColumn = null;
                IRow cellsData = null;
                int cellsIndex = 0;

                //列名标题
                cellsColumn = sheet.CreateRow(cellsIndex);
                int index = 0;
                Dictionary<string, int> columns = new Dictionary<string, int>();
                foreach (var item in name)
                {
                    cellsColumn.CreateCell(index).SetCellValue(item.Value);
                    sheet.SetColumnWidth(index, 10 * 256);//设置对应列宽(单元格索引从0开始,后面接宽度)
                    columns.Add(item.Value, index);
                    index++;
                }
                cellsIndex += 1;
                //循环数据
                foreach (var item in datalist)
                {
                    cellsData = sheet.CreateRow(cellsIndex);
                    for (int i = 0; i < propertyInfos.Length; i++)
                    {
                        if (!name.ContainsKey(propertyInfos[i].Name)) continue;
                        //这里可以也根据数据类型做不同的赋值,也可以根据不同的格式参考上面的ICellStyle设置不同的样式
                        object[] entityValues = new object[propertyInfos.Length];
                        entityValues[i] = propertyInfos[i].GetValue(item);
                        if(entityValues[i]!= null && 
                            ( propertyInfos[i].Name.Equals("Date", StringComparison.OrdinalIgnoreCase)
                            || propertyInfos[i].Name.Equals("StartDate", StringComparison.OrdinalIgnoreCase)
                            || propertyInfos[i].Name.Equals("EndDate", StringComparison.OrdinalIgnoreCase)))
                        {
                            entityValues[i] = string.Format("{0:yyyy/MM/dd}", entityValues[i]);
                        }
                        if (entityValues[i] == null)
                        {
                            continue;
                        }
                        //获取对应列下标
                        index = columns[name[propertyInfos[i].Name]];
                        sheet.SetColumnWidth(index, 20 * 256);//设置对应列宽(单元格索引从0开始,后面接宽度) 
                        cellsData.CreateCell(index).SetCellValue(entityValues[i].ToString());
                    }
                    cellsIndex++;
                }

                if (File.Exists(output))
                {
                    File.Delete(output);
                }
                using (FileStream fs = new FileStream(output, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
                {
                    workbook.Write(fs);
                    fs.Close();
                    fs.Dispose();
                    return true;
                }
            }
            catch(Exception ex)
            {
                throw ex;
            }
            
        }
    }

调用

var result1 = NPOIHelper.ExportE<Information>($@"{filePath}{FileName}", FileName, infoList, generateFile.GetDicInfo());


posted @ 2022-10-24 16:10  highlightyys  阅读(25)  评论(0编辑  收藏  举报