zoukankan      html  css  js  c++  java
  • 在ASP.NET Core中使用EPPlus导入出Excel文件

    在ASP.NET Core中使用EPPlus导入出Excel文件

     
     

    这篇文章说明了如何使用EPPlus在ASP.NET Core中导入和导出.xls/.xlsx文件(Excel)。在考虑使用.NET处理excel时,我们总是寻找第三方库或组件。使用Open Office Xml格式(xlsx)读取和写入Excel 2007/2010文件的最流行的.net库之一是EPPlus。这个库现在已经支持.NET Core许久了。这适用于Windows,Linux和Mac。

    因此,让我们创建一个新的ASP.NET Core WEB API应用程序并安装EPPlus.Core。要安装EPPlus.Core,请在程序包管理器控制台中运行以下命令:

    PM->Install-Package EPPlus.Core

    或者您可以通过UI界面来安装它.

     一切就绪,现在创建一个控制器,命名为: ImportExportController ,添加后,让我们编写导出方法。

    为了方便演示,我在wwwroot文件夹中创建了一个excel文件,所以我们就需要去获取我们的项目的绝对路径。

    复制代码
        public class ImportExportController : ControllerBase
        {
            private readonly IHostingEnvironment _hostingEnvironment;
    
            public ImportExportController(IHostingEnvironment hostingEnvironment)
            {
                _hostingEnvironment = hostingEnvironment;
            }
        }
    复制代码

     ExcelPackage 在 OfficeOpenXml 命名空间中可用的类将用于读写xlsx。定义名为“Export”的新Web api操作方法,该方法返回生成的xlsx文件的URL。所以这是将数据导出到xlsx的完整代码。其中您需要 using OfficeOpenXml; 

    复制代码
            [HttpGet]
            public string Export()
            {
                string sWebRootFolder = _hostingEnvironment.WebRootPath;
                string sFileName = @"demo.xlsx";
                string URL = string.Format("{0}://{1}/{2}", Request.Scheme, Request.Host, sFileName);
                FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
                if (file.Exists)
                {
                    file.Delete();
                    file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
                }
                using (ExcelPackage package = new ExcelPackage(file))
                {
                    // add a new worksheet to the empty workbook
                    ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Employee");
                    //First add the headers
                    worksheet.Cells[1, 1].Value = "ID";
                    worksheet.Cells[1, 2].Value = "Name";
                    worksheet.Cells[1, 3].Value = "Gender";
                    worksheet.Cells[1, 4].Value = "Salary (in $)";
    
                    //Add values
                    worksheet.Cells["A2"].Value = 1000;
                    worksheet.Cells["B2"].Value = "Jon";
                    worksheet.Cells["C2"].Value = "M";
                    worksheet.Cells["D2"].Value = 5000;
    
                    worksheet.Cells["A3"].Value = 1001;
                    worksheet.Cells["B3"].Value = "Graham";
                    worksheet.Cells["C3"].Value = "M";
                    worksheet.Cells["D3"].Value = 10000;
    
                    worksheet.Cells["A4"].Value = 1002;
                    worksheet.Cells["B4"].Value = "Jenny";
                    worksheet.Cells["C4"].Value = "F";
                    worksheet.Cells["D4"].Value = 5000;
    
                    package.Save(); //Save the workbook.
                }
                return URL;
            }
    复制代码

    就这样。现在,当您运行此应用程序并调用export方法时。完成后,访问wwwroot您的应用程序的文件夹。您应该在系统上看到“demo.xlsx”。当你打开它时,你应该看到以下内容。

    您还可以对标题进行加粗,这些并不是EPPlus.Core给我们提供的,你需要引用 using OfficeOpenXml; using OfficeOpenXml.Style; 

    using (var cells = worksheet.Cells[1, 1, 1, 4])
                    {
                        cells.Style.Font.Bold = true;
                        cells.Style.Fill.PatternType = ExcelFillStyle.Solid;
                        cells.Style.Fill.BackgroundColor.SetColor(Color.LightGray);
                    }

     

     关于导入,其实真实的情况还是比较复杂的,我们这里就不进行验证了,对于演示,我们只是读取刚刚保存的文件。 ImportAPI 将读取文件并以格式化的字符串返回文件内容。以下是导入API的完整代码,用于读取xlsx,创建文件内容的格式化字符串并返回相同的内容。

    复制代码
    [HttpGet]
            [Route("Import")]
            public string Import()
            {
                string sWebRootFolder = _hostingEnvironment.WebRootPath;
                string sFileName = @"demo.xlsx";
                FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
                try
                {
                    using (ExcelPackage package = new ExcelPackage(file))
                    {
                        StringBuilder sb = new StringBuilder();
                        ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
                        int rowCount = worksheet.Dimension.Rows;
                        int ColCount = worksheet.Dimension.Columns;
                        bool bHeaderRow = true;
                        for (int row = 1; row <= rowCount; row++)
                        {
                            for (int col = 1; col <= ColCount; col++)
                            {
                                if (bHeaderRow)
                                {
                                    sb.Append(worksheet.Cells[row, col].Value.ToString() + "	");
                                }
                                else
                                {
                                    sb.Append(worksheet.Cells[row, col].Value.ToString() + "	");
                                }
                            }
                            sb.Append(Environment.NewLine);
                        }
                        return sb.ToString();
                    }
                }
                catch (Exception ex)
                {
                    return "Some error occured while importing." + ex.Message;
                }
            }
    复制代码

    希望可以帮助到你。

     
     
  • 相关阅读:
    旧VC项目dpiAware支持
    小鹤双拼win10一键恢复布局
    Win10强制程序高DPI缩放设置
    dotnet部署出现Failed to load the dll from [ ... hostfxr.dll], HRESULT: 0x80070057
    linux下快速安装pyenv管理多版本python
    利用docker-compose快速部署测试用数据库服务器
    elastic query match_all 数据目标超过10000条出错 Result window is too large
    Docker for Windows 启动失败,提示Kubernetes证书无效
    windows 下 pyinstaller distutils not included with latest virtualenv (16.4.0)
    windows下python3.7.2内置venv虚拟环境下pyinstaller错误问题
  • 原文地址:https://www.cnblogs.com/webenh/p/13496613.html
Copyright © 2011-2022 走看看