下载asp.net C#后损坏的.docx文件

时间:2017-12-09 14:47:05

标签: c# asp.net

我正在尝试将带有图像的aspx页面导出到word文档中。当我尝试用.doc格式实现这个时,然后在单词doc上出现破碎的图像。我尝试以.docx格式下载它但在修改.docx的代码后,它会在打开时给出文件损坏的错误。以下是我的代码:

<body>
        <form id="form1" runat="server">
           <asp:Panel ID="tblReport" runat="server">
          <div class="boxed1a">
                    <img class="images4" src="Images/Penguins.jpg" width="640" height="45" />
                    <table class="tb3">
                    <tr>
                    <td>Leasehold & Functional Programs</td>

                    </tr>
                    <tr>
                    <td>N/A</td>

                    </tr>
                    <tr>
                    <td>Acquis Maint & Renov</td>

                    </tr>
                    </table>

                </div>
    </asp:Panel>
            <asp:Button runat="server" ID="btnExport" Text="Export" OnClick="btnExport_Click" />
        </form>
    </body>



    protected void btnExport_Click(object sender, EventArgs e)
            {
                Response.Clear();
                Response.Buffer = true;
                Response.Charset = "";

                Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                Response.AppendHeader("content-disposition", "attachment;  filename=report.docx");

                StringWriter sw = new StringWriter();
                HtmlTextWriter htw = new HtmlTextWriter(sw);
                tblReport.RenderControl(htw);
                Response.Write(sw.ToString());
                Response.Flush();
                Response.End();
            }

请告诉我如何使用.docx格式实现此目的。

1 个答案:

答案 0 :(得分:1)

HTML文本编写器不是在.net中创建Word文档的正确方法。

您可以使用以下代码创建简单的Word文档,并从链接https://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.aspx中获取参考。

以上链接将帮助您在.net。

中创建高效的Word文档
 Microsoft.Office.Interop.Word._Application objWord;
 object oMissing = System.Reflection.Missing.Value;
 object oEndOfDoc = "\\endofdoc";
 FolderBrowserDialog ff = new FolderBrowserDialog();
 ff.ShowDialog();
 string filename = "Sample";
 Microsoft.Office.Interop.Word._Document objDoc;
 objWord = new Microsoft.Office.Interop.Word.Application();
 objWord.Visible = true;
 objDoc = objWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
 Microsoft.Office.Interop.Word.Range wrdRng = objDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
 wrdRng.Text = "Simple Word";
 this.Close();
 string fp = ff.SelectedPath + "\\" + filename + ".docx";
 objDoc.SaveAs2(fp);

希望这有帮助!