Create docx word document web api .net core 2.0
Asked Answered
A

1

10

I am developing a Web API project in Asp.net core 2.0. I am in need of a library or way to create Word document. I have searched an tried NPOI and DocX. Both are not as good as expected. Can anyone suggest me a tool?

Allain answered 6/4, 2018 at 5:1 Comment(0)
R
27

At first glance, the below link can help somehow:

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

Anyway, about DOCX - Word Document using Open XML SDK by Microsoft - you can install Open XML SDK into your solution using the version 2.8.1. It´s all free.

Documentation avaliable at:

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

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

ps: the MSDN documentation is all about the version SDK 2.5 instead of 2.8.1, but as explained in the GIT link there is no substancial changes.

Anyway to use it in a Web APP CORE 2.0 you can do the follow:

  1. INstall the Nuget Packgaes version SDK 2.8.1
  2. Reference the below namespaces within your controller:

    using DocumentFormat.OpenXml;
    using DocumentFormat.OpenXml.Packaging;
    using DocumentFormat.OpenXml.Wordprocessing;
    
  3. If you just want to save it in a folder locally do something like:

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

and call it like:

 public IActionResult GenerateDocx()
    {
        string filePath = @"c:\word\Invoice.docx";
        CreateWordprocessingDocument(filePath);
    }
  1. If you want to generate a docx to be saved into a users computer from their browsers, after hitting a link, do something like:

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

the above code even shows how to use the most important objects: body, paragraphs, runs and text. Remember to follow this order always!

Roxi answered 31/12, 2018 at 10:27 Comment(2)
Is it possible to generate .docx file from html and css ? I want to create an web api application which that generate docx files, and another applications which need to generate docx, call my docx generator application . in other word I want to create an docx generator which another applications can get help from that. and only way which I find to commiunicate between my applications ,is use html and css strings to generate files . offcourse, if is possible another better way to do this job, please explains that for me.Phonics
When I utilize the above from a web api return like the example above I get. "Word found unreadable content in [filename].docx. Do you want to recover the contents of this document? If you trust the source, click Yes.". Any thoughts on why this would happen?Whitfield

© 2022 - 2024 — McMap. All rights reserved.