C#将gridview导出为ex​​cel - 文件无法打开

时间:2014-04-10 00:11:51

标签: c# excel gridview export-to-excel

我正在使用excel 2010.我收到一条错误,指出“您尝试打开的文件格式与指定的格式不同.....”

我要打开的文件超过10mb。我可以打开一个从不同的gridview导出的小得多的文件,我得到与上述相同的错误。我相信如果没有做一些注册表魔法,这个错误是不可避免的。

这是我的代码和我尝试过的一些事情。任何人都可以协助我为什么不能打开它?它可能是我的gridview中的东西吗?

编辑:我发布的第二个我发现了罪魁祸首。 Checkboxfield是问题的原因。我在stackoverflow上找到了这个。将尝试使用它或找到另一种方式。 Gridview export utility

protected void btnExport_Click(object sender, EventArgs e)
    {
        //render the gridview in Excel
        //tried: filename=completereport.xlsx
        string attachment = "attachment; filename=completereport.xls";
        Response.ClearContent();

        //Tried: Response.Clear();

        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        //Tried: Response.ContentType = "application/ms-excel";
        //Tried: Response.ContentType = "application/vnd.xls";

        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        gvCompleteReport.RenderControl(htw);
        //remove hyperlinks from headers of sortable columns and write output
        Response.Write(Regex.Replace(sw.ToString(), @"(<a[^>]*>)|(</a>)", " ", RegexOptions.IgnoreCase));
        //Tried: Response.Write(sw.ToString());
        Response.End();
    }

public override void VerifyRenderingInServerForm(Control control)
    {
        //this override allows export to excel from within an update panel
    }

<asp:GridView ID="gvCompleteReport" runat="server" DataSourceID="odsGetCompleteReport"      AutoGenerateColumns="false"
    CssClass="gridview" DataKeyNames="organization, service">
    <Columns>
        <asp:BoundField HeaderText="Organization" DataField="organization" SortExpression="organization" />
        <asp:BoundField HeaderText="Service" DataField="service" SortExpression="service" />
        <asp:BoundField HeaderText="Category" DataField="Material Category" />
        <asp:BoundField HeaderText="Material" DataField="Material Accepted" />
        <asp:BoundField HeaderText="Acceptance CD" DataField="acceptance_ds" />
        <asp:BoundField HeaderText="County" DataField="County" />
        <asp:CheckBoxField HeaderText="Residential" DataField="residential_fl" />
        <asp:CheckBoxField HeaderText="Commercial" DataField="commercial_fl" />
        <asp:BoundField HeaderText="Svc Type" DataField="service_type_ds" />
    </Columns>
</asp:GridView>

0 个答案:

没有答案