在ASP.NET中生成HTML Excel文件并以zip文件打包

时间:2015-08-12 05:23:45

标签: asp.net .net excel

我正在处理生成HTML Excel文件并将其写入响应的页面。我想修改该页面以生成许多HTML Excel文件并将其打包为zip。

我已经使用了,但是当我尝试从zip文件打开Excel文件时,它会显示纯HTML而不是正确格式化,就像我将HTML Excel文件直接提供给响应时那样。

我正在使用DotNetZip库作为zip组件:

如何让Excel正确显示文件?

这是我的代码:

Response.ClearContent();
Response.AppendHeader("Content-Disposition", "attachment;filename=" + progName + "_" + teacher.GetSchoolId() + ".zip");
Response.ContentType = "application/zip";

byte[] strBytes = String.Format(@"
    <table>
    <tr><td colspan='8'><h1>{0} - {1}</h1></td></tr>
    <tr><td><b>Activity: </b>{2}</td></tr>
    <tr><td>&nbsp;</td></tr>
    <tr><td><b>Teacher: </b>{4}</td></tr>
    <tr><td><b>School: </b>{3}</td></tr>
    <tr><td><b>School ID: </b></td><td>{7}</td></tr>
    <tr><td><b>School Address: </b>{8}</td></tr>
    <tr><td>&nbsp;</td></tr>
    </table>
    <table>
    {5}
    <tr><td>&nbsp;</td></tr>
    </table>
    <table>
    {6}
    </table>
    <br />
    <p>The averages above are calculated as a percentage of the students who have <b>submitted</b> answers from your school and nationally.</p>
    ",
        DateTime.Now.Year.ToString(),
        ProgramId.SelectedItem.Text,
        ProgramActivityId.SelectedItem.Text,
        teacher.GetSchoolName(),
        teacher.GetFullName(),
        awardKey,
        xls,
        teacher.GetSchoolId(),
        teacher.GetSchoolAddress()
        ).GetBytes();

using (var zip = new ZipFile())
{
    zip.AddEntry(progName + "_" + teacher.GetSchoolId() + ".xls", strBytes);
    zip.Save(Response.OutputStream);
}

Response.End();

1 个答案:

答案 0 :(得分:0)

非常简单;我需要正确编码字符串,然后才能工作。

using (var zip = new ZipFile())
{
    zip.AddEntry(progName + "_" + teacher.GetSchoolId() + ".xls", System.Text.Encoding.UTF8.GetBytes(sReport));
    zip.Save(Response.OutputStream);
}