2

我有在控制台中创建文件的基本代码(见下文)。但我正在编写一个 MVC 应用程序,所以我需要将该 XML 文档作为 ActionResult 返回......我已经在网上搜索了 2 个小时,寻找一个简单的没有运气的例子..

我要添加什么以使其成为 ActionResult ?

       string filePath = @"C:\temp\OpenXMLTest.docx";
        using (WordprocessingDocument doc = WordprocessingDocument.Create(filePath, WordprocessingDocumentType.Document))
        {
            //// Creates the MainDocumentPart and add it to the document (doc)     
            MainDocumentPart mainPart = doc.AddMainDocumentPart();
            mainPart.Document = new Document(
                new Body(
                    new Paragraph(
                        new Run(
                            new Text("Hello World!!!!!")))));
        }
4

1 回答 1

5

这是一些示例代码。请注意,此代码不会从磁盘加载文件,它会即时创建文件并写入 MemoryStream。写入磁盘所需的更改很少。

    public ActionResult DownloadDocx()
    {
        MemoryStream ms;

        using (ms = new MemoryStream())
        {
            using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(ms, WordprocessingDocumentType.Document))
            {
                MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();

                mainPart.Document = new Document(
                    new Body(
                        new Paragraph(
                            new Run(
                                new Text("Hello world!")))));
            }
        }

        return File(ms.ToArray(), "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "Test.docx");
    }
于 2013-05-23T14:45:38.587 回答