如何解决生成的Docx文件已损坏-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,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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。