Hướng dẫn convert html to word using openxml c# - chuyển html sang word sử dụng openxml C#

Tôi nhận ra tôi trễ 7 năm ở đây.Tuy nhiên, đối với những người trong tương lai đang tìm kiếm cách chuyển đổi từ HTML sang Word Doc, blog này đăng trên trang web Microsoft MSDN cung cấp hầu hết các thành phần cần thiết để thực hiện việc này bằng OpenXML.Tôi thấy bài đăng này là khó hiểu, nhưng mã nguồn mà anh ấy đã bao gồm làm rõ tất cả cho tôi.

Phần duy nhất bị thiếu là làm thế nào để xây dựng một tệp docx từ đầu, thay vì làm thế nào để hợp nhất thành một tệp hiện có như ví dụ của anh ta cho thấy.Tôi thấy rằng Tidbit từ đây.

Thật không may, dự án tôi đã sử dụng điều này được viết bằng vb.net.Vì vậy, tôi sẽ chia sẻ mã VB.NET trước, sau đó chuyển đổi C# tự động của nó, có thể hoặc không chính xác.

Mã vb.net:

Imports DocumentFormat.OpenXml
Imports DocumentFormat.OpenXml.Packaging
Imports DocumentFormat.OpenXml.Wordprocessing
Imports System.IO

Dim ms As IO.MemoryStream
Dim mainPart As MainDocumentPart
Dim b As Body
Dim d As Document
Dim chunk As AlternativeFormatImportPart
Dim altChunk As AltChunk

Const altChunkID As String = "AltChunkId1"

ms = New MemoryStream()

Using myDoc = WordprocessingDocument.Create(ms,WordprocessingDocumentType.Document)
    mainPart = myDoc.MainDocumentPart

    If mainPart Is Nothing Then
        mainPart = myDoc.AddMainDocumentPart()

        b = New Body()
        d = New Document(b)
        d.Save(mainPart)
    End If

    chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Xhtml, altChunkID)

    Using chunkStream As Stream = chunk.GetStream(FileMode.Create, FileAccess.Write)
        Using stringStream As StreamWriter = New StreamWriter(chunkStream)
            stringStream.Write("YOUR HTML HERE")
        End Using
    End Using

    altChunk = New AltChunk()
    altChunk.Id = altChunkID
    mainPart.Document.Body.InsertAt(Of AltChunk)(altChunk, 0)
    mainPart.Document.Save()
End Using

Mã C#:

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System.IO;

IO.MemoryStream ms;
MainDocumentPart mainPart;
Body b;
Document d;
AlternativeFormatImportPart chunk;
AltChunk altChunk;

string altChunkID = "AltChunkId1";

ms = new MemoryStream();

Using (myDoc = WordprocessingDocument.Create(ms, WordprocessingDocumentType.Document))
{
    mainPart = myDoc.MainDocumentPart;

    if (mainPart == null) 
    {
         mainPart = myDoc.AddMainDocumentPart();
         b = new Body();
         d = new Document(b);
         d.Save(mainPart);
    }

    chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Xhtml, altChunkID);

    Using (Stream chunkStream = chunk.GetStream(FileMode.Create, FileAccess.Write)
    {
         Using (StreamWriter stringStream = new StreamWriter(chunkStream))         
         {
              stringStream.Write("YOUR HTML HERE");
         }
    }    

    altChunk = new AltChunk();
    altChunk.Id = altChunkID;
    mainPart.Document.Body.InsertAt(Of, AltChunk)[altChunk, 0];
    mainPart.Document.Save();
}

Lưu ý rằng tôi đang sử dụng luồng bộ nhớ ms trong một thói quen khác, đó là nơi nó được xử lý sau khi sử dụng.

Tôi mong điều này giúp được người nào khác!

Hi comunidadmexi...,

Kiểm tra ví dụ dưới đây.

Không gian tên

C#

using System.Data;
using System.IO;
using System.Text;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

VB.Net

Imports System.Data
Imports System.IO
Imports System.Text
Imports DocumentFormat.OpenXml
Imports DocumentFormat.OpenXml.Packaging
Imports DocumentFormat.OpenXml.Wordprocessing

Mã số

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[]
        {
            new DataColumn("contents"),
            new DataColumn("image"),
            new DataColumn("ppt"),
            new DataColumn("xls"),
            new DataColumn("pdf")
        });
        dt.Rows.Add("

- Near

", "b8fa9493.jpg", "rtfghb8fa9493.ppt", "kioplb8fa9493.xls", "xqab8fa9493.pdf"); dt.Rows.Add("

- Miss

", "b8fa9493.jpg", "rtfghb8fa9493.ppt", "kioplb8fa9493.xls", "xqab8fa9493.pdf"); using (MemoryStream ms = new MemoryStream()) { using (WordprocessingDocument doc = WordprocessingDocument.Create(ms, WordprocessingDocumentType.Document)) { MainDocumentPart mainPart = doc.AddMainDocumentPart(); mainPart.Document = new Document(); Body body = mainPart.Document.AppendChild(new Body()); for (int i = 0; i < dt.Rows.Count; i++) { string altChunkId = "AltChunkId" + (i + 1); AlternativeFormatImportPart afip = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, altChunkId); string html = ""; html += ""; html += ""; html += ""; html += ""; html += ""; html += "
" + dt.Rows[i]["contents"].ToString() + "" + dt.Rows[i]["image"].ToString() + "PPTExcelPDF
"; afip.FeedData(new MemoryStream(Encoding.UTF8.GetBytes(html))); AltChunk altChunk = new AltChunk(); altChunk.Id = altChunkId; mainPart.Document.Body.Append(altChunk); } } Response.AppendHeader("Content-Disposition", "attachment;filename=HTML.docx"); Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; Response.BinaryWrite(ms.ToArray()); Response.End(); } } }

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim dt As DataTable = New DataTable()
        dt.Columns.AddRange(New DataColumn() {New DataColumn("contents"), New DataColumn("image"), New DataColumn("ppt"), New DataColumn("xls"), New DataColumn("pdf")})
        dt.Rows.Add("

- Near

", "b8fa9493.jpg", "rtfghb8fa9493.ppt", "kioplb8fa9493.xls", "xqab8fa9493.pdf") dt.Rows.Add("

- Miss

", "b8fa9493.jpg", "rtfghb8fa9493.ppt", "kioplb8fa9493.xls", "xqab8fa9493.pdf") Using ms As MemoryStream = New MemoryStream() Using doc As WordprocessingDocument = WordprocessingDocument.Create(ms, WordprocessingDocumentType.Document) Dim mainPart As MainDocumentPart = doc.AddMainDocumentPart() mainPart.Document = New Document() Dim body As Body = mainPart.Document.AppendChild(New Body()) For i As Integer = 0 To dt.Rows.Count - 1 Dim altChunkId As String = "AltChunkId" & (i + 1) Dim afip As AlternativeFormatImportPart = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, altChunkId) Dim html As String = "" html += "" html += "" html += "" html += "" html += "" html += "
" & dt.Rows(i)("contents").ToString() & "" + dt.Rows(i)("image").ToString() & "PPTExcelPDF
" afip.FeedData(New MemoryStream(Encoding.UTF8.GetBytes(html))) Dim altChunk As AltChunk = New AltChunk() altChunk.Id = altChunkId mainPart.Document.Body.Append(altChunk) Next End Using Response.AppendHeader("Content-Disposition", "attachment;filename=HTML.docx") Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document" Response.BinaryWrite(ms.ToArray()) Response.End() End Using End If End Sub