C# 如何使用asp.net创建和下载excel文档

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/643643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 11:30:46  来源:igfitidea点击:

how to create and download excel document using asp.net

c#asp.netexcelopenxml

提问by belaz

How to create and download excel document using asp.net ?

如何使用asp.net创建和下载excel文档?

The purpose is to use xml, linq or whatever to send an excel document to a customer via a browser.

目的是使用 xml、linq 或其他任何方式通过浏览器向客户发送 excel 文档。

Edit : Use case

编辑:用例

The customer load a gridview ( made with ajax framework ) in a browser, the gridview is directly linked to an sql database. I put a button 'export to excel' to let customer save this gridview data on his computer ansd i would like to launch a clean download of an excel.

客户在浏览器中加载一个 gridview(用 ajax 框架制作),gridview 直接链接到一个 sql 数据库。我放了一个“导出到 excel”按钮,让客户将此 gridview 数据保存在他的计算机上,我想启动一个干净的 excel 下载。

The solutions proposed here are not clean, like send an html document and change the header to excel document etc, i'm searching a simple solution on codeplex right now, i will let you know.

这里提出的解决方案并不干净,比如发送一个html文档并将标题更改为excel文档等,我现在正在codeplex上搜索一个简单的解决方案,我会告诉你的。

采纳答案by belaz

Starter kit

入门套件

First i have downloaded the Open XML Format SDK 2.0.

首先,我下载了Open XML Format SDK 2.0

It comes with 3 useful tools in :

它带有 3 个有用的工具:

C:\Program Files\Open XML Format SDK\V2.0\tools

C:\Program Files\Open XML Format SDK\V2.0\tools

  • DocumentReflector.exewich auto generate the c# to build a spreadsheet from the code.
  • OpenXmlClassesExplorer.exedisplay Ecma specification and the class documentation (using an MSDN style format).
  • OpenXmlDiff.exegraphically compare two Open XML files and search for errors.
  • DocumentReflector.exe至极自动生成 C# 以从代码构建电子表格。
  • OpenXmlClassesExplorer.exe显示 Ecma 规范和类文档(使用 MSDN 样式格式)。
  • OpenXmlDiff.exe以图形方式比较两个 Open XML 文件并搜索错误。

I suggest anyone who begin to rename.xlsxto.zip, so you can see the XML files who drive our spreadsheet ( for the example our sheets are in "xl\worksheets" ).

我建议任何开始.xlsx重命名.zip,因此您可以查看驱动我们电子表格的 XML 文件(例如,我们的工作表位于 "xl\worksheets" 中)。



The code

编码

Disclaimer: I have stolen all the code from an MSDN technical article;D

免责声明:我从MSDN 技术文章中窃取了所有代码;D

The following code use an *.xlsx template i made manually to be able to modify it.

以下代码使用我手动制作的 *.xlsx 模板,以便能够对其进行修改。

Namespaces references

命名空间引用

using System.IO;
using System.Xml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;


// Database object
        DataClassesDataContext db = new DataClassesDataContext();

        // Make a copy of the template file.
        File.Copy(@"C:\inetpub\wwwroot\project.Web\Clients\Handlers\oxml-tpl\livreurs.xlsx", @"C:\inetpub\wwwroot\project.Web\Clients\Handlers\oxml-tpl\generated.xlsx", true);

        // Open the copied template workbook. 
        using (SpreadsheetDocument myWorkbook = SpreadsheetDocument.Open(@"C:\inetpub\wwwroot\project.Web\Clients\Handlers\oxml-tpl\generated.xlsx", true))
        {
            // Access the main Workbook part, which contains all references.
            WorkbookPart workbookPart = myWorkbook.WorkbookPart;

            // Get the first worksheet. 
            WorksheetPart worksheetPart = workbookPart.WorksheetParts.ElementAt(2);

            // The SheetData object will contain all the data.
            SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();

            // Begining Row pointer                       
            int index = 2;

            // Database results
            var query = from t in db.Clients select t;

            // For each item in the database, add a Row to SheetData.
            foreach (var item in query)
            {
                // Cell related variable
                string Nom = item.Nom;

                // New Row
                Row row = new Row();
                row.RowIndex = (UInt32)index;

                // New Cell
                Cell cell = new Cell();
                cell.DataType = CellValues.InlineString;
                // Column A1, 2, 3 ... and so on
                cell.CellReference = "A"+index;

                // Create Text object
                Text t = new Text();
                t.Text = Nom;

                // Append Text to InlineString object
                InlineString inlineString = new InlineString();
                inlineString.AppendChild(t);

                // Append InlineString to Cell
                cell.AppendChild(inlineString);

                // Append Cell to Row
                row.AppendChild(cell);

                // Append Row to SheetData
                sheetData.AppendChild(row);

                // increase row pointer
                index++;                

            }

            // save
            worksheetPart.Worksheet.Save();

        }

I havent finished yet, my second job is to auto download the spreadsheet after modification.

我还没有完成,我的第二个工作是修改后自动下载电子表格。



Finally, i redirect the user to my generated spredsheet (from my aspx)

最后,我将用户重定向到我生成的电子表格(来自我的 aspx)

 context.Response.Redirect("Oxml-tpl/generated.xlsx");

回答by Binoj Antony

just set Response.ContentType = "application/vnd.ms-excel" and your page will rendered as an excel sheet on the clients browser

只需设置 Response.ContentType = "application/vnd.ms-excel",您的页面将在客户端浏览器上呈现为 Excel 表格

Sample code here

示例代码在这里

回答by Gregory A Beamer

There are quite a few ways of handling this, depending on how extensive the Excel functionality is. Binoj's answer works if the Excel is just a spreadsheet and has no direct Excel functionality built in. The client can add functionality, concats, etc. These are "dumb" excel docs until the client does soemthing.

有很多方法可以处理此问题,具体取决于 Excel 功能的广泛程度。如果 Excel 只是一个电子表格并且没有内置的直接 Excel 功能,Binoj 的答案就有效。客户端可以添加功能、连接等。这些是“愚蠢的”excel 文档,直到客户端执行某些操作。

To create a more full featured Excel doc, you havve two basic choices that I can think of offhand.

要创建功能更全面的 Excel 文档,您有两个我能想到的基本选择。

  1. Use either the office components (re: bad) to create an excel document, or a third party component, like SoftArtisan's ExcelWriter. Great component, but there is a cost.

  2. Use a control on the page that allows export to Excel. Most vendors of ASSP.NET controls have this functionality on their grids.

  1. 使用 office 组件(re: bad)创建 Excel 文档,或使用第三方组件,如 SoftArtisan 的 ExcelWriter。伟大的组件,但有成本。

  2. 在页面上使用允许导出到 Excel 的控件。大多数 ASSP.NET 控件供应商在他们的网格上都有这个功能。

Option #1 allows you pretty much all functionality of Excel. Option #2 is a bit more limited, at least in the controls I have tried.

选项 #1 允许您使用 Excel 的几乎所有功能。选项#2 有一点限制,至少在我尝试过的控件中是这样。