如何在不同工作表上的同一个excel文件中导出两个gridviews?

时间:2012-12-11 20:06:16

标签: c# .net excel gridview

我目前在我的页面上有两个网格视图。我能够将一个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;
    }
}

1 个答案:

答案 0 :(得分: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.CellsSpreadsheetGear,{{3} }和LibXL等。

Flexcel