【发布时间】:2023-03-26 23:32:01
【问题描述】:
private void ConvertHTMLtoDOCX(string txtcode)
{
System.Text.StringBuilder strBody = new System.Text.StringBuilder("");
strBody.Append("<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>Time</title>");
//The setting specifies document's view after it is downloaded as Print
//instead of the default Web Layout
strBody.Append("<!--[if gte mso 9]>" + "<xml>" + "<w:WordDocument>" + "<w:View>Print</w:View>" + "<w:DoNotOptimizeForBrowser/>" + "</w:WordDocument>" + "</xml>" + "<![endif]-->");
strBody.Append("<style>" + "<!-- /* Style Definitions */" + "@page Section1" + " {size:8.5in 11.0in; " + " margin:1.0in 1.25in 1.0in 1.25in ; " + " mso-header-margin:.5in; " + " mso-footer-margin:.5in; mso-paper-source:0;}" + " div.Section1" + " {page:Section1;}" + "-->" + "</style></head>");
strBody.Append("<body lang=EN-US style='tab-interval:.5in'>" + "<div class=Section1>" + Html_editor.Content + "</div></body></html>");
//Force this content to be downloaded
//as a Word document with the name of your choice
string FullFilePath = @"C:\Users\ravikant\Desktop\AR GitHub\07-05-2014\FinalTestARGithub\LetterTemplate\"+ txtcode+ ".docx";
FileInfo file = new FileInfo(FullFilePath);
if (file.Exists)
{
ClientScript.RegisterStartupScript(this.GetType(), "disExp", "<script>alert('File Already Exists');</script>");
}
else
{
Response.AppendHeader("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
Response.AppendHeader("Content-disposition", "inline; filename="+txtcode+".docx");
Response.Write(strBody);
}
}
这是使用 .DOCX “application/vnd.openxmlformats-officedocument.wordprocessingml.document”的 CONTENT-TYPE 的代码,打开文件时内容已损坏。
【问题讨论】:
-
检查文件的文件大小。看起来是否有任何实际保存到文件中的内容?另外我认为您的
file.Exists支票是错误的。这将检查文件是否存在于服务器上,当您保存到客户端时。在您的开发机器上可能是相同的,但是一旦您发布到远程服务器,您就会遇到问题。 -
文件大小200kb还好,说明内容有问题。不知道为什么会发生这种情况,当我制作 .doc 或 .xlsx 时,这很容易。编译代码也没有报错,请关注此事。
-
第一步,我会从您保存的内容中删除编辑器内容。在其位置放置一个基本的
<p>Hello World</p>。如果可行,您就知道问题出在编辑器的内容上。检查 html、xml、doctype、head 和 body 标记的内容。如果它不起作用,则说明您的保存过程有问题。 -
file.exists 工作正常,从那里没有问题。我也以不同的格式创建文件,文件很容易创建,但对于 .DOCX 我不知道。
-
另一个可能有帮助的技巧,我已经使用原生单词 .docx 完成了此操作,但不是以这种方式生成的 .docx,因此它可能有效,也可能无效。制作保存文件的副本,将其扩展名从 .docx 更改为 .zip。尝试打开它。我们试图找到一个文件
document.xml,它通常位于“word”文件夹中。在文本编辑器中打开它,看看是否有任何错误或尝试通过 XML 验证器。 VisualStudio 应该足以显示任何格式错误。