如何在c#中将HTML文件转换为Word文档而不使用任何API和doc.spire
本文关键字:任何 API spire doc 文档 Word 中将 HTML 转换 文件 | 更新日期: 2023-09-27 18:13:32
我已经用这段代码创建了一个word文件。
System.Text.StringBuilder strHTMLContent = new System.Text.StringBuilder();
strHTMLContent.Append("<html xmlns:v='"urn:schemas-microsoft-com:vml'" xmlns:o='"urn:schemas-microsoft-com:office:office'" xmlns:x='"urn:schemas-microsoft-com:office:word'" xmlns='"http://www.w3.org/TR/REC-html40'"><head></head><body>");
strHTMLContent.Append(var);
strHTMLContent.Append("</body></html>");
File.WriteAllText(@"E:'doc2.html", strHTMLContent.ToString());
现在我使用下面的代码将这个文件转换为word
HttpContext.Current.Response.Write(strHTMLContent);
HttpContext.Current.Response.End();
HttpContext.Current.Response.Flush();
但问题是它直接显示下载选项。但我想把它存储在Server
中
如何做到不使用任何API?
我不确定这是否适用于每种类型的网页,但如果你想只存储文本部分(我刚刚测试过),你可以这样做:
- 创建该HTML文件的副本。(如果需要原始HTML,可选步骤)
- 将副本的扩展名更改为
.doc
,自动将其转换为文档文件
创建一个将html文件转换为word文件的函数…
private string generateWordDoc(){
object filename1 = @"E:'doc3.html";//path of html file
object oMissing = System.Reflection.Missing.Value;
object readOnly = false;
object oFalse = false;
Microsoft.Office.Interop.Word.Application oWord = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document oDoc = new Microsoft.Office.Interop.Word.Document();
oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
oWord.Visible = false;
oDoc = oWord.Documents.Open(ref filename1, ref oMissing, 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);
filename1 = @"E:'new.doc"; // new document path
object fileFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument;
oDoc.SaveAs(ref filename1, 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 oMissing, ref oMissing, ref oMissing);
oDoc.Close(ref oFalse, ref oMissing, ref oMissing);
oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
return "Success";
}