生成的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