如何返回OPENXML Word文档的MVC ActionResult?

时间:2013-03-21 16:59:50

标签: asp.net-mvc ms-word openxml

我有一个在控制台中创建文件的基本代码(见下文)..但我正在编写一个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!!!!!")))));
        }

1 个答案:

答案 0 :(得分: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");
    }