1

目前我的页面上有两个网格视图。我能够将一个gridview 导出到excel 文件。但是对于第二个 gridview,我希望它在同一个文件的另一个工作表中打开。任何人都可以帮助我开始并告诉我如何去做吗?

这是我的代码的样子:

protected void btnExport_Click(object sender, EventArgs e)
{
    GridView gridView = null;
    System.IO.StringWriter stringWrite = null;
    System.Web.UI.HtmlTextWriter htmlWrite = null;
    try
    {
        gridView = new GridView();
        List<string> columns = new List<string>();
        columns.Add("CREATE_AR_YN");
        columns.Add("GL_DEBIT_ACCT");
        columns.Add("ALLOC_METHOD");
        columns.Add("CUST_NAME");
        columns.Add("DEFAULT_PYMT_TERMS");
        columns.Add("AR_BILL_GROUP");

        BoundField bf = null;
        for (int i = 0; i < columns.Count; i++)
        {
            bf = new BoundField();
            bf.DataField = columns[i];
            bf.HeaderText = columns[i];
            bf.HeaderStyle.BackColor = System.Drawing.Color.FromName("#81DAF5");
            gridView.Columns.Add(bf);
            gridView.AutoGenerateColumns = false;
        }

        List<FMAProfile> custList = GetSelectedCustomerProfile();
        gridView.DataSource = custList;
        gridView.DataBind();
        Response.Clear();
        Response.ClearHeaders();
        Response.Cache.SetCacheability(HttpCacheability.Private);
        Response.AddHeader("content-disposition", "attachment;filename=" + "CustomerProfile" + ".xls");
        Response.Charset = "";
        //Response.ContentType = "application/vnd.xls";
        Response.ContentType = "application/vnd.ms-excel";
        //Response.Buffer = false;
        stringWrite = new System.IO.StringWriter();
        htmlWrite = new HtmlTextWriter(stringWrite);
        gridView.RenderControl(htmlWrite);
        Response.Write(stringWrite.ToString());
        Response.End();
    }
    catch (Exception ex)
    {
        if (ex.Message.Trim().IndexOf("Thread was being aborted") == -1)
        {
            Log(ex.ToString());
        }
    }
    finally
    {
        if (gridView != null)
        {
           gridView.Dispose();
           gridView = null;
        }
        if (stringWrite != null)
        {
            stringWrite.Dispose();
        }
        stringWrite = null;
        if (htmlWrite != null)
        {
            htmlWrite.Dispose();
        }
        htmlWrite = null;
    }
}
4

1 回答 1

1

您不是在导出真正的 XLS,而是基本上是 Excel 可以导入的 HTML……

有关使用示例代码创建 Excel 文件的 HTML 方法的一些深入信息,请参阅http://www.c-sharpcorner.com/UploadFile/kaushikborah28/79Nick08302007171404PM/79Nick.aspx

还可以在http://msdn.microsoft.com/en-us/library/Aa155477%28office.10%29.aspx查看官方文档

我不确定您是否可以在 HTML 中创建多个工作表...

创建真实 Excel 文件的选项:

MS 提供 OpenXML SDK V 2.0(免费) - 请参阅http://msdn.microsoft.com/en-us/library/bb448854%28office.14%29.aspx

这可以读写 MS Office 文件(包括 Excel)。

另一种选择见http://www.codeproject.com/KB/office/OpenXML.aspx

如果您需要更多类似渲染、公式等,那么有不同的免费和商业库,如ClosedXMLEPPlusAspose.CellsSpreadsheetGearLibXLFlexcel等。

注意: ASP.NET 不支持 Office 互操作(这似乎是您的项目内置的内容)。

于 2012-12-11T20:32:54.740 回答