bootstraptable导出excel独立使用_使用DotNetCore.NPOI写通用的导出导入excel

前言

最近做项目使用上.Net Core,而且又要写一个excel的导出导入功能,以前我曾经写两篇关于http://asp.net上使用NPOI做导出导入功能文章--传送阵。
因为现在使用的框架是.Net core,因此以前引用的dll都要升级,以及写法上也有点点不同,所以就重新再写一文记录。

首先都是引入dll,到Nuget那里搜索DotNetCore.NPOI,然后下载安装即可。

ce1924cf96c614572875426199d6d8cc.png

导出篇

先引入这四个命名空间

using NPOI.HSSF.UserModel; 
using NPOI.XSSF.UserModel; 
using NPOI.SS.UserModel; 
using NPOI.HSSF.Util; 

接下就是正式的代码导入代码

public byte[] ExportToExcel<T>(List<T> entities, ExportModel model)
        {
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFPalette palette = workbook.GetCustomPalette();
            HSSFColor hssFColor;
            byte red, green, bule;

            if (model.DataFields == null || model.DataFields.Length == 0)
            {
                model.DataFields = model.ColumnNames;
            }

            #region 标题

            // 标题字体
            IFont titleFont = workbook.CreateFont();
            var titleColor = model.TitleRow.CellStyle.Font.Color;
            red = titleColor[0];
            green = titleColor[1];
            bule = titleColor[2];
            palette.SetColorAtIndex(8, red, green, bule);
            hssFColor = palette.FindColor(red, green, bule);
            titleFont.Color = hssFColor.Indexed;
            titleFont.FontHeightInPoints = model.TitleRow.CellStyle.Font.FontHeightInPoints;

            // 标题前景色
            var titleForegroundColor = model.TitleRow.CellStyle.FillForegroundColor;
            red = titleForegroundColor[0];
            green = titleForegroundColor[1];
            bule = titleForegroundColor[2];
            palette.SetColorAtIndex(9, red, green, bule);
            hssFColor = palette.FindColor(red, green, bule);

            // 标题
            ICellStyle titleStyle = workbook.CreateCellStyle();
            titleStyle.SetFont(titleFont);
            titleStyle.FillPattern = FillPattern.SolidForeground;
            titleStyle.FillForegroundColor = hssFColor.Indexed;
            titleStyle.Alignment = HorizontalAlignment.Center;
            titleStyle.VerticalAlignment = VerticalAlignment.Center;

            ISheet sheet = workbook.CreateSheet("Sheet1");
            IRow row = sheet.CreateRow(0);
            row.HeightInPoints = model.DataRow.HeightInPoints;
            ICell cell = null;
            for (int i = 0; i < model.ColumnNames.Length; i++)
            {
                cell = row.CreateCell(i);
                cell.CellStyle = titleStyle;
                cell.SetCellValue(model.ColumnNames[i]);
            }

            #endregion

            if (entities.Count > 0)
            {
                // 数据行
                object cellValue = string.Empty;
                ICellStyle cellStyle = workbook.CreateCellStyle();
                IFont cellFont = workbook.CreateFont();
                cellFont.FontHeightInPoints = model.DataRow.CellStyle.Font.FontHeightInPoints;
                cellStyle.SetFont(cellFont);
                cellStyle.VerticalAlignment = VerticalAlignment.Center;
                for (int i = 0; i < entities.Count; i++)
                {
                    row = sheet.CreateRow(i + 1);
                    row.HeightInPoints = model.DataRow.HeightInPoints;
                    object entity = entities[i];
                    for (int j = 0; j < model.DataFields.Length; j++)
                    {
                        cellValue = entity.GetType().GetProperty(model.DataFields[j]).GetValue(entity);
                        cell = row.CreateCell(j);
                        cell.CellStyle = cellStyle;
                        cell.SetCellValue(Convert.ToString(cellValue));
                    }
                }

                // 调整列宽
                for (int i = 0; i <= entities.Count; i++)
                {
                    sheet.AutoSizeColumn(i);
                }
                for (int columnNum = 0; columnNum <= model.ColumnNames.Length; columnNum++)
                {
                    int columnWidth = sheet.GetColumnWidth(columnNum) / 256;
                    for (int rowNum = 1; rowNum <= sheet.LastRowNum; rowNum++)
                    {
                        IRow currentRow;
                        if (sheet.GetRow(rowNum) == null)
                        {
                            currentRow = sheet.CreateRow(rowNum);
                        }
                        else
                        {
                            currentRow = sheet.GetRow(rowNum);
                        }

                        if (currentRow.GetCell(columnNum) != null)
                        {
                            ICell currentCell = currentRow.GetCell(columnNum);
                            int length = Encoding.Default.GetBytes(currentCell.ToString()).Length;
                            if (columnWidth < length)
                            {
                                columnWidth = length;
                            }
                        }
                    }
                    columnWidth = Math.Min(columnWidth, 255);
                    sheet.SetColumnWidth(columnNum, columnWidth * 256);
                }
            }

            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                return ms.GetBuffer();
            }
        }


这里需要注意的是,我使用的是对象是HSSFWorkbook,因此生成的文档是03版excel即xls类型的文档。如果想生成07版的excel即xlsx类型的文档,则需要使用XSSFWorkbook对象。其他的写法都基本一致。
还有一点就是ExportModel这个对象属于我自己封装的,是一些关于生成excel文档的一些基本配置,后面我给出这个对象代码属性。

调用

 public IActionResult ExportToExcel()
        {
            IExcelService _IExcelService = new ExcelService();
            //var result = _IPostingStatusService.GetExcelData(model).ToList();
            List<string> result = new List<string>();
            ExportModel excelModel = new ExportModel();
            excelModel.DataFields = new string[] { "Department", "JobTitle", "Folio" };
            excelModel.ColumnNames = new string[] { "Department", "Job Title", "Request No." };

            var buffer = _IExcelService.ExportToExcel(result, excelModel);

            return File(buffer, MediaTypeNames.Application.Octet, "111.xls");
        }

ExportMode

 public class ExportModel
    {
        public string[] DataFields { get; set; }

        public string[] ColumnNames { get; set; }

        public RowModel TitleRow { get; set; } = new RowModel()
        {
            HeightInPoints = 22,
            CellStyle = new CellStyleModel
            {
                FillForegroundColor = new byte[] { 0, 74, 134 },
                Font = new FontModel
                {
                    FontHeightInPoints = 12,
                    Color = new byte[] { 255, 255, 255 }
                }
            }
        };

        public RowModel DataRow { get; set; } = new RowModel()
        {
            HeightInPoints = 22,
            CellStyle = new CellStyleModel
            {
                FillForegroundColor = new byte[] { 255, 255, 255 },
                Font = new FontModel
                {
                    FontHeightInPoints = 10,
                    Color = new byte[] { 0, 0, 0 }
                }
            }
        };
    }

public class RowModel
    {
        public CellStyleModel CellStyle { get; set; }

        public float HeightInPoints { get; set; }
    }

 public class CellStyleModel
    {
        public byte[] FillForegroundColor { get; set; }

        public FontModel Font { get; set; }
    }

public class FontModel
    {
        public short FontHeightInPoints { get; set; }

        /// <summary>
        /// R,G,B
        /// </summary>
        public byte[] Color { get; set; }
    }

导入篇

直接上代码

public List<T> ExcelToList<T>(Stream stream, string fileName) where T : class, new()
        {
            IWorkbook workbook = null;
            string _ext = fileName.Substring(fileName.LastIndexOf("."), fileName.Length - fileName.LastIndexOf("."));
            if (_ext == ".xlsx")
            {
                workbook = new XSSFWorkbook(stream);
            }
            else
            {
                workbook = new HSSFWorkbook(stream);
            }

            ISheet sheet = workbook.GetSheetAt(0);
            IRow ITitleRow = sheet.GetRow(0);
            int totalColumn = ITitleRow.LastCellNum;
            int totalRow = sheet.LastRowNum;

            Dictionary<string, int> dic = new Dictionary<string, int>();
            var properties = typeof(T).GetProperties();
            for (int i = 0, len = properties.Length; i < len; i++)
            {
                object[] _attributes = properties[i].GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (_attributes.Length == 0)
                {
                    continue;
                }
                string _description = ((DescriptionAttribute)_attributes[0]).Description;
                if (!string.IsNullOrWhiteSpace(_description))
                {
                    dic.Add(_description, i);
                }
            }

            string _value = string.Empty;
            string _type = string.Empty;
            int index = 0;
            List<T> list = new List<T>();
            for (int i = 1; i <= totalRow; i++)
            {
                IRow row = sheet.GetRow(i);
                if (row == null)
                {
                    continue;
                }
                var obj = new T();
                for (int j = 0; j < totalColumn; j++)
                {
                    if (dic.TryGetValue(ITitleRow.GetCell(j).ToString(), out index) && row.GetCell(j) != null)
                    {
                        _type = (properties[index].PropertyType).FullName;
                        _value = row.GetCell(j).ToString();
                        if (_type == "System.String")
                        {
                            properties[index].SetValue(obj, _value, null);
                        }
                        else if (_type == "System.DateTime")
                        {
                            DateTime pdt = Convert.ToDateTime(_value, CultureInfo.InvariantCulture);
                            properties[index].SetValue(obj, pdt, null);
                        }
                        else if (_type == "System.Boolean")
                        {
                            bool pb = Convert.ToBoolean(_value);
                            properties[index].SetValue(obj, pb, null);
                        }
                        else if (_type == "System.Int16")
                        {
                            short pi16 = Convert.ToInt16(_value);
                            properties[index].SetValue(obj, pi16, null);
                        }
                        else if (_type == "System.Int32")
                        {
                            int pi32 = Convert.ToInt32(_value);
                            properties[index].SetValue(obj, pi32, null);
                        }
                        else if (_type == "System.Int64")
                        {
                            long pi64 = Convert.ToInt64(_value);
                            properties[index].SetValue(obj, pi64, null);
                        }
                        else if (_type == "System.Byte")
                        {
                            byte pb = Convert.ToByte(_value);
                            properties[index].SetValue(obj, pb, null);
                        }
                        else
                        {
                            properties[index].SetValue(obj, null, null);
                        }
                    }
                }
                list.Add(obj);
            }
            return list;
        }

调用

 public IActionResult LoadExcel(IFormFile file)
        {
            IExcelService _IExcelService = new ExcelService();
            try
            {
                var rows = _IExcelService.ExcelToList<ImportExcelModel>(file.OpenReadStream(), file.FileName);


                return Content("导入成功!");
            }
            catch (Exception e) { return Content("导入失败"); }
        }

说明ImportExcelModel其实也就是自己建的一个保存数据对象,这个对象可以跟你的表对应,这样导入的数据就能与表关联起来再保存到数据库。

最后

上面的代码就是.NetCore使用NPOI做的导出导入功能的通用写法,是可以直接复制到自己代码,稍微更改一下就能直接使用,希望对大家有所帮助。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: WPF是一种用于开发桌面应用程序的技术,而NPOI是一个用于处理Excel文件的开源库。通过结合使用WPF和NPOI,我们可以在WPF应用程序中实现Excel文件的导入导出功能。 要使用NPOI导入Excel文件,首先需要引入NPOI库。我们可以通过NuGet包管理器将NPOI库添加到我们的WPF项目中。然后,我们可以使用NPOI的API来读取和解析Excel文件。我们需要创建一个Workbook对象,并选择要读取的特定Sheet,然后使用循环遍历每一行,并读取每个单元格的值。 在WPF中,我们可以创建一个界面并添加一个按钮,用于触发Excel文件导入功能。当用户点击按钮时,我们将使用NPOI库打开文件选择对话框,允许用户选择要导入Excel文件。一旦我们获取了用户选择的文件路径,我们可以使用NPOI的API来读取Excel文件,然后将数据绑定到WPF应用程序中的相应控件上。 要使用NPOI导出Excel文件,在WPF中,我们可以将数据绑定到DataGrid或ListView等控件上。当用户点击导出按钮时,我们可以使用NPOI的API来创建一个Workbook对象,并选择要导出的Sheet。然后,我们可以使用循环遍历来将数据从WPF控件中导出Excel文件的每一行。 最后,我们可以将导出Excel文件保存到硬盘上的特定路径。使用NPOI的API,我们可以设置导出文件的格式和样式,例如设置单元格的字体、颜色、边框等。 总之,通过使用NPOI库,我们可以在WPF应用程序中实现Excel文件的导入导出功能。这个过程涉及到引入NPOI库、读取和解析Excel文件、将数据绑定到WPF控件上、使用NPOI导出数据到Excel文件等步骤。 ### 回答2: WPF是一种用于构建Windows应用程序的开发框架,而NPOI是一个支持读取和入Microsoft Office格式文件的库。使用NPOI库可以在WPF应用程序中实现Excel文件的导入导出功能。 首先需要在WPF项目中引用NPOI库,可以通过NuGet包管理器或手动引用DLL文件的方式进行添加。 要导入Excel文件,我们可以使用NPOI库提供的类来读取和解析文件。首先需要创建一个ExcelWorkbook对象,然后通过获取工作表和行、单元格的方式来获取数据。可以使用循环遍历的方法将数据导入到WPF应用程序中的数据结构中,如数据表或集合。 要导出Excel文件,我们可以使用NPOI库提供的类来创建和Excel文件。首先需要创建一个ExcelWorkbook对象,然后创建工作表和行对象,并将数据入到单元格中。最后,可以使用流将Excel文件保存到指定的位置。 需要注意的是,导入导出Excel文件时需要处理一些异常情况,如文件格式错误、IO异常等,可以使用try-catch语句来捕获并处理这些异常。 总结来说,使用NPOI库可以方便地在WPF应用程序中实现Excel文件的导入导出功能。通过引用NPOI库,并使用它提供的类和方法,我们可以读取和解析Excel文件的数据,以及创建和Excel文件。这使得我们可以更加灵活和高效地处理Excel文件,满足特定的需求。 ### 回答3: WPF是一种使用XAML语言和.NET框架开发桌面应用程序的技术。NPOI是一个用于操作Microsoft Office格式文件的开源库,可以在WPF应用程序中使用NPOI来实现Excel文件的导入导出。 在使用NPOI导入Excel文件时,首先需要引入NPOI的相关命名空间,然后通过创建一个Workbook对象来加载Excel文件。可以使用Workbook的GetSheetAt方法获取具体的工作表,并通过遍历行和列的方式获取单元格的数据。再通过将数据存储到一个集合或数据表中,便可以在WPF应用程序中进行进一步的处理和展示。 在使用NPOI导出Excel文件时,首先需要创建一个Workbook对象,并在其中创建一个工作表。然后通过遍历数据集合或数据表,使用NPOI提供的方法在工作表中添加行和列,并设置相应的单元格数值。最后,使用Workbook的Write方法将数据入到Excel文件中,并通过保存文件的方式实现导出功能。 此外,还可以根据需求设置单元格的样式、字体、颜色等属性,以及合并单元格、设置边框等操作。通过熟悉NPOI库的API文档,可以灵活地操作Excel文件,并在WPF应用程序中实现导入导出Excel的功能。 总之,通过使用NPOI库,可以在WPF应用程序中方便地实现Excel文件的导入导出功能,提高了应用程序的灵活性和用户体验。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值