繁体   English   中英

使用c#将html转换为word

[英]Convert html to word using c#

我正在使用 Microsoft.Office.Interop.Word 将 html 转换为 word。我在本地机器上创建 html 文件,然后将其转换为 word 文件。但是 word 文件没有显示正确的格式。 它只是显示图像。 我已经提到了 stackoverflow 问题。但我没有找到运气。 我的示例 html 文件如下所示:-

 <!doctype html> <html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word' xmlns='http://www.w3.org/TR/REC-html40'> <head> <title="Device Information" /> <style> table.main { width: 700px; height: 450px; background: radial-gradient(#1367AB 0%, #154075 60%); } td.firsttablerow1 { width: 190px; } td.firsttablerow2 { width: auto; color: white; } tr.image1 { margin: "15px,20px,30px,40px"; align-items: stretch; height: 100px; } tr.image2 { margin: "0px,20px,30px,40px"; align-items: stretch; } tr.text1 { color: #DDE9F2; align-items: flex-end; font-size: 9; } </style> </head> <body> <table align="center" class="main"> <tr> <td class="firsttablerow1"> <table> <tr class="image1"> <td> <img src='C:\\Jellyfish.jpg' width='200' height='90'> </td> </tr> <tr class="image2"> <td> <img src='C:\\Desert.jpg' width='150' height='90'> </td> </tr> <tr class="text1"> <td>"abc"</td> </tr> </table> </td> <td class="firsttablerow2">"xyz"</td> </tr> </table> </body> </html>

我将 html 转换为 word 的 C# 代码如下所示。

MSWord.Application word = new MSWord.Application { Visible = false };
        word.Documents.Open("htmlfilename", Format: WdOpenFormat.wdOpenFormatWebPages);
        MSWord.Document doc = word.Documents[@"htmlfilename"];
        doc.SaveAs2(@"wordFileName", WdSaveFormat.wdFormatDocument);
        doc.Close();
        doc = null;
        word.Quit();
        word = null;

编辑:-进一步调查后,我发现这个词正在被创建。但是它无法通过使用径向渐变来改变背景。还有其他方法可以添加径向背景吗?

使用 OpenXml。

在 .NET 5.0 上

Install-Package HtmlToOpenXml.dll -Version 2.1.0
Install-Package DocumentFormat.OpenXml -Version 2.11.3

出口服务

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

public MemoryStream ExportToWord()
{
    string htmlValue = "myHtmlCodes";
    
    using MemoryStream stream = new MemoryStream();
    using WordprocessingDocument package = WordprocessingDocument.Create(stream, 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(htmlValue);

    mainPart.Document.Save();

    return stream;
}

出口控制器

return File(
        fileContents: stream.ToArray(),
        contentType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        fileDownloadName: $"{fileName}.docx");

可以试试这个

Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document wordDoc = new Microsoft.Office.Interop.Word.Document();
            Object oMissing = System.Reflection.Missing.Value;
            wordDoc = word.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
            word.Visible = false;
            Object filepath = "c:\\page.html";
            Object confirmconversion = System.Reflection.Missing.Value;
            Object readOnly = false;
            Object saveto = "c:\\doc.pdf";
            Object oallowsubstitution = System.Reflection.Missing.Value;

            wordDoc = word.Documents.Open(ref filepath, ref confirmconversion, ref readOnly, ref oMissing,
                                          ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                          ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                          ref oMissing, ref oMissing, ref oMissing, ref oMissing);
            object fileFormat = WdSaveFormat.wdFormatPDF;
            wordDoc.SaveAs(ref saveto, ref fileFormat, ref oMissing, ref oMissing, ref oMissing,
                           ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                           ref oMissing, ref oMissing, ref oMissing, ref oallowsubstitution, ref oMissing,
                           ref oMissing);

希望此解决方案有助于转换和创建 Word Docs。

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Xceed.Words.NET;
using System.Diagnostics;
using System.IO;

namespace MVC_WordDocument.Controllers
{
    public class GenerateDocumentController : Controller
    {
        // GET: GenerateDocument
        public ActionResult GenerateDocument()
        {
            return View();
        }
        [HttpPost]
        public void GenerateDocument(string generate)
        {
            DocX doc = null;

            doc = DocX.Create(Server.MapPath("~/ StudentInformation.docx"), DocumentTypes.Document);

            string Text = @"Student Information";
            doc.InsertParagraph(Text, false).Alignment = Alignment.both;
            doc.InsertParagraph(" ");

            Table table = doc.AddTable(8, 7);
            table.Alignment = Alignment.center;
            table.Design = TableDesign.LightGridAccent2;

            table.Rows[0].Cells[0].Paragraphs.First().Append("Student Number");
            table.Rows[0].Cells[1].Paragraphs.First().Append("Name");
            table.Rows[0].Cells[2].Paragraphs.First().Append("Surname");
            table.Rows[0].Cells[3].Paragraphs.First().Append("Email");
            table.Rows[0].Cells[4].Paragraphs.First().Append("Telephone No:");
            table.Rows[0].Cells[5].Paragraphs.First().Append("Mobile Number");
            table.Rows[0].Cells[6].Paragraphs.First().Append("Active");

            doc.InsertTable(table);
            doc.Save();


            MemoryStream ms = new MemoryStream();
            doc.SaveAs(ms);
            byte[] byteArray = ms.ToArray();
            ms.Flush();
            ms.Close();
            ms.Dispose();
            Response.Clear();
            Response.AddHeader("Content-Disposition", "attachment; filename=StudentINFO.docx");
            Response.AddHeader("Content-Length", byteArray.Length.ToString());
            Response.ContentType = "application/msword";
            Response.BinaryWrite(byteArray);
            Response.End();
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM