当前位置: 移动技术网 > IT编程>开发语言>.net > 在ASP.NET Core中使用EPPlus导入出Excel文件

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

2019年02月24日  | 移动技术网IT编程  | 我要评论

全能仙君,回到明朝当王爷笔趣阁,中央电视台元旦晚会

这篇文章说明了如何使用epplus在asp.net core中导入和导出.xls/.xlsx文件(excel)。在考虑使用.net处理excel时,我们总是寻找第三方库或组件。使用open office xml格式(xlsx)读取和写入excel 2007/2010文件的最流行的.net库之一是。这个库现在已经支持.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() + "\t");
                            }
                            else
                            {
                                sb.append(worksheet.cells[row, col].value.tostring() + "\t");
                            }
                        }
                        sb.append(environment.newline);
                    }
                    return sb.tostring();
                }
            }
            catch (exception ex)
            {
                return "some error occured while importing." + ex.message;
            }
        }

希望可以帮助到你。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网