繁体   English   中英

生成的 Docx 文件已损坏 - C#

[英]Generated Docx File is Corrupt - C#

我正在用我的应用程序创建一个 docx 文件,但我被Response.End()卡住了。 我收到此错误:

威胁已经被清除了

我收到此错误,但无论如何仍会创建该文件。 当我尝试打开文件时,它总是损坏。 我没有成功编写.docx文件。 请让我知道我做错了什么。

HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document; charset=utf-8";
HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment;filename={0}", "mydoc.docx"));
HttpContext.Current.Response.BinaryWrite(ourString);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();

请注意,您不应将Response.End放在 try-catch 块中,因为它会抛出该异常。 参见HttpResponse.End方法的说明:

为了模仿 ASP 中 End 方法的行为,此方法尝试引发 ThreadAbortException 异常。

您可以使用以下方法避免这种情况:

var response = HttpContext.Current.Response;
response.Clear();
response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document;
response.AddHeader("Content-Disposition", "attachment;filename=mydoc.docx");
response.OutputStream.Write(ourString, 0, ourString.Length);
response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();

请注意,在上面的代码中,我假设您的ourString变量是字节数组,因为您将它传递给代码片段中的BinaryWrite方法。

但是,这个名称让我相信您刚刚将string转换为byte[] ,对吗?

如果是,请注意这不是有效的 DOCX 文件,DOCX 格式不是纯文本,您需要使用 Office Open XML 格式 (WordprocessingML) 正确编写。

spire.doc 可以用C#创建一个docx文件,参考链接: https ://www.e-iceblue.com/Tutorials/Spire.Doc/Spire.Doc-Program-Guide/Create-Write-and-Save-Word -in-C-and-VB.NET.html

暂无
暂无

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

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