如何使用ASP.NET MVC将数据从数据库导出到Excel工作表?

时间:2016-06-17 10:19:07

标签: c# asp.net-mvc

有没有人知道任何简单的NuGet包或将数据从数据库导出到Excel的其他方法?我有一些表,我想将每个表导出到其他工作表,但是在同一个Excel文件中。

后来我想将数据从Excel文件导入数据库。 对于这两种操作可能是不同的库。

我已经尝试this但是它不起作用。

@EDIT - 已解决

以下是一些有用的链接。我希望总有一天会帮助别人:)

http://epplus.codeplex.com/

http://techbrij.com/export-excel-xls-xlsx-asp-net-npoi-epplus

2 个答案:

答案 0 :(得分:1)

此代码来自EPPlus,对您的问题也有帮助::

private void ExcelExport(DataTable table)
        {
            using (ExcelPackage packge = new ExcelPackage())
            {
                //Create the worksheet
                ExcelWorksheet ws = packge.Workbook.Worksheets.Add("Demo");

                //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
                ws.Cells["A1"].LoadFromDataTable(table, true);

                //Format the header for column 1-3
                using (ExcelRange range = ws.Cells["A1:C1"])
                {
                    range.Style.Font.Bold = true;
                    range.Style.Fill.PatternType = ExcelFillStyle.Solid;                      //Set Pattern for the background to Solid
                    range.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(79, 129, 189)); //Set color to dark blue
                    range.Style.Font.Color.SetColor(Color.White);
                }

               //Example how to Format Column 1 as numeric 
                using (ExcelRange col = ws.Cells[2, 1, 2 + table.Rows.Count, 1])
                {
                    col.Style.Numberformat.Format = "#,##0.00";
                    col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
                }

                //Write it back to the client
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("content-disposition", "attachment;  filename=ExcelExport.xlsx");
                Response.BinaryWrite(packge.GetAsByteArray());
            }
        }

答案 1 :(得分:0)

有几种选择,如付费,免费或客户端转换解决方案,服务器端转换解决方案。

如果您只想导出到excel客户端而不影响服务器,则需要做出决定。这是演示(运行)解决方案。

http://www.itorian.com/2015/05/export-table-data-into-excel-file.html

单击结果选项卡,然后单击“将表数据导出到Excel中”按钮。如果这有帮助,请将此标记为答案。

修改

正如您所提到的,您需要将表导出到不同的Excel页面(但在同一文件中),这对您有用http://www.aspsnippets.com/Articles/Export-DataSet-DataTables-to-multiple-Excel-Sheets-Worksheets-in-ASPNet-using-C-and-VBNet.aspx