ASP.NET Core使用Web API通过Open XML SDK生成Word文件模板

本文主要介绍ASP.NET Core中,使用Web API后台接口通过Open XML SDK生成Word(.doc、.docx)文件模板,并且返回输出到浏览器端的方法,以及实现相关的示例代码。

1、使用Open XML SDK的文档

 https://github.com/OfficeDev/Open-XML-SDK

https://docs.microsoft.com/zh-cn/office/open-xml/open-xml-sdk

2、Nuget安装引用DocumentFormat.OpenXml

1)使用Nuget界面管理器

搜索"DocumentFormat.OpenXml",在列表中找到它,点击"安装"

相关文档VS(Visual Studio)中Nuget的使用

2)使用Package Manager命令安装

PM> Install-Package DocumentFormat.OpenXml

3)使用.NET CLI命令安装

> dotnet add TodoApi.csproj package DocumentFormat.OpenXml

3、引用如下命名空间

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

4、生成Word文件模板保存在服务器的方法

public static void CreateWordprocessingDocument(string filepath)
{
    // Create a document by supplying the filepath. 
    using (WordprocessingDocument wordDocument =
        WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
    {
        // Add a main document part. 
        MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
        // Create the document structure and add some text.
        mainPart.Document = new Document();
        Body body = mainPart.Document.AppendChild(new Body());
        Paragraph para = body.AppendChild(new Paragraph());
        Run run = para.AppendChild(new Run());
        run.AppendChild(new Text("Create text in body - CreateWordprocessingDocument"));
    }
}

调用代码:

 public IActionResult GenerateDocx()
    {
        string filePath = @"c:\word\Invoice.docx";
        CreateWordprocessingDocument(filePath);
    }

5、生成Word文件模板输出到浏览器的方法

// GET verb
public IActionResult GenerateDocxBrowser()
{
    // open xml sdk - docx
    using (MemoryStream mem = new MemoryStream())
    {
        using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(mem, DocumentFormat.OpenXml.WordprocessingDocumentType.Document, true))
        {
            wordDoc.AddMainDocumentPart();
            // siga a ordem
            Document doc = new Document();
            Body body = new Body();
            // 1 paragrafo
            Paragraph para = new Paragraph();
            ParagraphProperties paragraphProperties1 = new ParagraphProperties();
            ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId() { Val = "Normal" };
            Justification justification1 = new Justification() { Val = JustificationValues.Center };
            ParagraphMarkRunProperties paragraphMarkRunProperties1 = new ParagraphMarkRunProperties();
            paragraphProperties1.Append(paragraphStyleId1);
            paragraphProperties1.Append(justification1);
            paragraphProperties1.Append(paragraphMarkRunProperties1);
            Run run = new Run();
            RunProperties runProperties1 = new RunProperties();
            Text text = new Text() { Text = "The OpenXML SDK rocks!" };
            // siga a ordem 
            run.Append(runProperties1);
            run.Append(text);
            para.Append(paragraphProperties1);
            para.Append(run);
            // 2 paragrafo
            Paragraph para2 = new Paragraph();
            ParagraphProperties paragraphProperties2 = new ParagraphProperties();
            ParagraphStyleId paragraphStyleId2 = new ParagraphStyleId() { Val = "Normal" };
            Justification justification2 = new Justification() { Val = JustificationValues.Start };
            ParagraphMarkRunProperties paragraphMarkRunProperties2 = new ParagraphMarkRunProperties();
            paragraphProperties2.Append(paragraphStyleId2);
            paragraphProperties2.Append(justification2);
            paragraphProperties2.Append(paragraphMarkRunProperties2);
            Run run2 = new Run();
            RunProperties runProperties3 = new RunProperties();
            Text text2 = new Text();
            text2.Text = "Teste aqui";
            run2.AppendChild(new Break());
            run2.AppendChild(new Text("Hello"));
            run2.AppendChild(new Break());
            run2.AppendChild(new Text("world"));
            para2.Append(paragraphProperties2);
            para2.Append(run2);
            // todos os 2 paragrafos no main body
            body.Append(para);
            body.Append(para2);
            doc.Append(body);
            wordDoc.MainDocumentPart.Document = doc;
            wordDoc.Close();
        }
        return File(mem.ToArray(), "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "ABC.docx");
    }
}


推荐阅读
cjavapy编程之路首页