OpenXml创建Word文档并下载 [英] OpenXml create word document and download

查看:173
本文介绍了OpenXml创建Word文档并下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始探索OpenXml,并且试图创建一个新的简单word文档,然后下载该文件

I'm just starting to explore OpenXml and I'm trying to create a new simple word document and then download the file

这是我的代码

[HttpPost]
        public ActionResult WordExport()
        {
            var stream = new MemoryStream();
            WordprocessingDocument doc = WordprocessingDocument.Create(stream, DocumentFormat.OpenXml.WordprocessingDocumentType.Document, true);

            MainDocumentPart mainPart = doc.AddMainDocumentPart();

            new Document(new Body()).Save(mainPart);

            Body body = mainPart.Document.Body;
            body.Append(new Paragraph(
                        new Run(
                            new Text("Hello World!"))));

            mainPart.Document.Save();


            return File(stream, "application/msword", "test.doc");


        }

我期望它会包含"Hello World!" 但是当我下载文件时,文件为空

I was expecting that it would contain 'Hello World!' But when I download the file, the file is empty

我想念什么? Tks

What am I missing? Tks

推荐答案

您似乎有两个主要问题.首先,您需要在WordprocessingDocument上调用Close方法,以便保存某些文档部分.最干净的方法是在WordprocessingDocument周围使用using语句.这将导致为您调用Close方法.其次,您需要Seekstream的开头,否则将得到空结果.

You seem to have two main issues. Firstly, you need to call the Close method on the WordprocessingDocument in order for some of the document parts to get saved. The cleanest way to do that is to use a using statement around the WordprocessingDocument. This will cause the Close method to get called for you. Secondly, you need to Seek to the beginning of the stream otherwise you'll get an empty result.

对于OpenXml文件,您还具有不正确的文件扩展名和内容类型,但这通常不会导致您遇到的问题.

You also have the incorrect file extension and content type for an OpenXml file but that won't typically cause you the problem you are seeing.

完整的代码清单应为:

var stream = new MemoryStream();
using (WordprocessingDocument doc = WordprocessingDocument.Create(stream, DocumentFormat.OpenXml.WordprocessingDocumentType.Document, true))
{
    MainDocumentPart mainPart = doc.AddMainDocumentPart();

    new Document(new Body()).Save(mainPart);

    Body body = mainPart.Document.Body;
    body.Append(new Paragraph(
                new Run(
                    new Text("Hello World!"))));

    mainPart.Document.Save();

    //if you don't use the using you should close the WordprocessingDocument here
    //doc.Close();
}
stream.Seek(0, SeekOrigin.Begin);

return File(stream, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "test.docx");

这篇关于OpenXml创建Word文档并下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆