Generating docx file from HTML file using OpenXML

后端 未结 3 397
别那么骄傲
别那么骄傲 2020-12-18 06:24

I\'m using this method for generating docx file:

public static void CreateDocument(string documentFileName, string text)
{
    using (Wordproces         


        
3条回答
  •  南方客
    南方客 (楼主)
    2020-12-18 06:50

    I could successfully convert HTML content to docx file using OpenXML in an .net Core using this code

    string html = "Hello World";
    using (MemoryStream generatedDocument = new MemoryStream()){
       using (WordprocessingDocument package = 
                      WordprocessingDocument.Create(generatedDocument,
                      WordprocessingDocumentType.Document)){
       MainDocumentPart mainPart = package.MainDocumentPart;
       if (mainPart == null){
        mainPart = package.AddMainDocumentPart();
        new Document(new Body()).Save(mainPart);
    }
    HtmlConverter converter = new HtmlConverter(mainPart);
    converter.ParseHtml(html);
    mainPart.Document.Save();
    }
    

    To save on disk

    System.IO.File.WriteAllBytes("filename.docx", generatedDocument.ToArray());
    

    To return the file for download in net core mvc, use

    return File(generatedDocument.ToArray(), 
              "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
              "filename.docx");
    

提交回复
热议问题