2019-08-31
using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using System; using System.IO; using System.Text; using System.Windows.Forms; namespace WindowsFormsApp1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Button1_Click(object sender, EventArgs e) { //FileStream fs = // new FileStream(System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) // + @"C:\\Temp\\Test.docx", FileMode.Open); FileStream fs = new FileStream(@"C:\\Temp\\Test.docx", FileMode.Open); Body body = null; MainDocumentPart mainPart = null; using (WordprocessingDocument wdDoc = WordprocessingDocument.Open(fs, false)) { mainPart = wdDoc.MainDocumentPart; body = wdDoc.MainDocumentPart.Document.Body; if (body != null) { richTextBox1.Text = ConvertWordToHTML(body, mainPart); } } fs.Flush(); fs.Close(); } private string ConvertWordToHTML(Body content, MainDocumentPart wDoc) { string htmlConvertedString = string.Empty; foreach (Paragraph par in content.Descendants<Paragraph>()) { foreach (Run run in par.Descendants<Run>()) { RunProperties props = run.RunProperties; htmlConvertedString += ApplyTextFormatting(run.InnerText, props); } } return htmlConvertedString; } private string ApplyTextFormatting(string content, RunProperties property) { StringBuilder buildString = new StringBuilder(content); if (property != null) { if (property.Bold != null) { buildString.Insert(0, "<b>"); buildString.Append("</b>"); } if (property.Italic != null) { buildString.Insert(0, "<i>"); buildString.Append("</i>"); } if (property.Underline != null) { buildString.Insert(0, "<u>"); buildString.Append("</u>"); } if (property.Color != null && property.Color.Val != null) { buildString.Insert(0, "<span style=\"color: #" + property.Color.Val + "\">"); buildString.Append("</span>"); } if (property.Highlight != null && property.Highlight.Val != null) { buildString.Insert(0, "<span style=\"background-color: " + property.Highlight.Val + "\">"); buildString.Append("</span>"); } if (property.Strike != null) { buildString.Insert(0, "<s>"); buildString.Append("</s>"); } } return buildString.ToString(); } } } |
(完)
參考
https://pinkhatcode.com/2017/09/02/convert-word-document-text-html-c/
沒有留言:
張貼留言