使用.NET Core 2.0创建docx Word文档的Web API。

10

我正在开发一个Asp.net core 2.0的Web API项目。我需要一种库或方法来创建Word文档。我已经尝试了NPOI和DocX,但它们都不如预期好用。有人能推荐一个工具吗?

1个回答

26

一开始看起来,下面的链接可能有所帮助:

https://asp.net-hacker.rocks/2017/02/23/word-document-formatter-in-aspnetcore.html

无论如何,关于使用Microsoft的Open XML SDK创建DOCX - Word文档 - 你可以使用版本2.8.1将Open XML SDK安装到你的解决方案中。它是完全免费的。

文档可在以下链接中找到:

GIT上 => https://github.com/OfficeDev/Open-XML-SDK ;

MSDN上 => https://learn.microsoft.com/en-us/office/open-xml/open-xml-sdk

PS:MSDN文档都是关于SDK 2.5而不是2.8.1的,但正如GIT链接中所解释的那样,没有实质性的变化。

无论如何,在Web APP CORE 2.0中使用它,你可以按照以下步骤进行:

  1. 安装Nuget Packages版本SDK 2.8.1;
  2. 在你的控制器中引用以下命名空间:

    using DocumentFormat.OpenXml;
    using DocumentFormat.OpenXml.Packaging;
    using DocumentFormat.OpenXml.Wordprocessing;
    
  3. 如果您只想将其保存在本地文件夹中,请执行以下操作:

  4. 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);
    }
  • 如果您想要在用户点击链接后从他们的浏览器生成一个docx文件并保存到他们的计算机中,可以执行以下操作:

  • // 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");
        }
    
    }
    

    上述代码甚至展示了如何使用最重要的对象:body、段落、运行和文本。记得始终遵循这个顺序!


    3
    是否可以从HTML和CSS生成.docx文件?我想创建一个Web API应用程序,以生成docx文件,并创建另一个需要生成docx文件的应用程序来调用我的docx生成器应用程序。换句话说,我想创建一个docx生成器,让其他应用程序能够从中获取帮助。而我找到的唯一沟通方式,就是使用HTML和CSS字符串来生成文件。当然,如果有更好的方法来完成这项工作,请为我解释一下。 - Mohammad RN
    当我从Web API返回类似上面示例的内容时,我会得到以下提示:"Word在[文件名].docx中发现不可读内容。您是否要恢复此文档的内容?如果您信任该来源,请单击“是”。"。你有什么想法为什么会发生这种情况吗? - BRogers

    网页内容由stack overflow 提供, 点击上面的
    可以查看英文原文,
    原文链接