将GridView导出到多个Excel工作表

时间:2011-10-03 08:43:22

标签: asp.net excel gridview

我的Web应用程序中有两个Gridview。我需要点击(ExcelExpot)按钮,然后在Excel中导出相应的Sheet1和Sheet2。

  protected void ExportToExcel()
    {

        this.GridView1.EditIndex = -1;
        Response.Clear();
        Response.Buffer = true;
        string connectionString = (string)ConfigurationSettings.AppSettings["ConnectionString"];
        SqlConnection sqlconnection = new SqlConnection(connectionString);
        String sqlSelect = "select * from login";
        sqlconnection.Open();
        SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(sqlSelect, connectionString);
        //DataTable dt1
        DataTable dt1 =new DataTable();
        mySqlDataAdapter.Fill(dt1);

        //LinQ Query for dt2
        var query = (from c in dt.AsEnumerable()
        select new {id= c.Field<string>("id"),name=c.Field<string>("name"),city=c.Field<string>("city")}) ;
        DataTable dt2 = new DataTable();
        d2=query.CopyToDatatable();

        DataSet ds=new DataSet();
        ds.Tabls.Add(dt1);
        ds.Tabls.Add(dt2);
        Excel.Application excelHandle1 = PrepareForExport(ds);
        excelHandle1.Visible = true;

    } 
  // code for PrepareForExport(ds);
         PrepareForExport(ds)
             {

                two tables in two worksheets of Excel...

              }

4 个答案:

答案 0 :(得分:6)

使用EPPlus执行此操作是件小事。不需要Interop程序集,字面上有两行代码可以完成所有的魔术:

ws.Cells["A1"].LoadFromDataTable(dt1, true);
ws2.Cells["A1"].LoadFromDataTable(dt2, true);

完整代码:

protected void ExportExcel_Click(object sender, EventArgs e)
{

     //LinQ Query for dt2
    var query = (from c in dt.AsEnumerable()
    select new {id= c.Field<string>("id"),name=c.Field<string>("name"),city=c.Field<string>("city")}) ;
    DataTable dt2 = new DataTable();
    dt2=query.CopyToDatatable();

    //DataTable dt1
    DataTable dt1 =new DataTable();
    mySqlDataAdapter.Fill(dt1);

    using (ExcelPackage pck = new ExcelPackage())
    {
        ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Page 1");
        ExcelWorksheet ws2 = pck.Workbook.Worksheets.Add("Page 2");

        ws.Cells["A1"].LoadFromDataTable(dt1, true);
        ws2.Cells["A1"].LoadFromDataTable(dt2, true);

        //Write it back to the client
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.AddHeader("content-disposition", "attachment;  filename=ExcelDemo.xlsx");
        Response.BinaryWrite(pck.GetAsByteArray());
        Response.Flush();
        Response.End();
    }
}

请注意,我复制并粘贴了您的代码以收集数据。我希望这些行能够产生一个DataTable。

答案 1 :(得分:4)

我同意@Andrew Burgess并已将其代码实施到我的一个项目中。只是为了记录,代码中的一些小错误会导致一些COM异常。更正后的代码如下(问题是Excel编号表,行,列从1到n不是从零开始)。

using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.IO;

        //Print using Ofice InterOp
        Excel.Application excel = new Excel.Application();

        var workbook = (Excel._Workbook)(excel.Workbooks.Add(Missing.Value));

        for (var i = 0; i < dataset.Tables.Count; i++)
        {

                if (workbook.Sheets.Count <= i)
                {
                    workbook.Sheets.Add(Type.Missing, Type.Missing, Type.Missing,
                                        Type.Missing);
                }

                //NOTE: Excel numbering goes from 1 to n
                var currentSheet = (Excel._Worksheet)workbook.Sheets[i + 1]; 

                for (var y = 0; y < dataset.Tables[i].Rows.Count; y++)
                {
                    for (var x = 0; x < dataset.Tables[i].Rows[y].ItemArray.Count(); x++)
                    {
                        currentSheet.Cells[y+1, x+1] = dataset.Tables[i].Rows[y].ItemArray[x];
                    }
                }
        }

        string outfile = @"C:\APP_OUTPUT\EXCEL_TEST.xlsx";

        workbook.SaveAs( outfile, Type.Missing, Type.Missing, Type.Missing,
                        Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange,
                        Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                        Type.Missing);

        workbook.Close();
        excel.Quit();

答案 2 :(得分:2)

您需要创建工作簿,根据需要添加更多工作表(默认为三个),然后填写单元格。

文件顶部:

using Excel=Microsoft.Office.Interop.Excel;

然后是生成Excel文件的主要代码

Excel.Application excel = new Application();

var workbook = (Excel._Workbook) (excel.Workbooks.Add(Missing.Value));

for (var i = 0; i < dataset.Tables.Count; i++)
{
    if (workbook.Sheets.Count <= i)
    {
        workbook.Sheets.Add(Type.Missing, Type.Missing, Type.Missing, 
                            Type.Missing);
    }

    var currentSheet = (Excel._Worksheet)workbook.Sheets[i];
    for (var y = 0; y < dataset.Tables[i].Rows.Count; y++)
    {
        for (var x = 0; x < dataset.Tables[i].Rows[y].ItemArray.Count(); x++)
        {
            currentSheet.Cells[y, x] = dataset.Tables[i].Rows[y].ItemArray[x];
        }
    }
}

workbook.SaveAs("C:\\Temp\\book.xlsx", Type.Missing, Type.Missing, Type.Missing,
                Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, 
                Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
                Type.Missing);

workbook.Close();
excel.Quit();

Response.WriteFile(C:\\Temp\\book.xlsx");

不确切知道这是否有效,但它应该让你朝着正确的方向发展

(另外:Type.MissingMissing.Value来自名称空间System.Reflection,仅限FYI)

答案 3 :(得分:2)

您可以使用ADO.NET,而不是使用某些第三方库或Excel自动化(添加额外开销)。

http://support.microsoft.com/kb/316934#10

您只需使用您习惯使用的OleDbCommand对象的T-SQL。

CREATE TABLE Sheet1 (id INT, name char(255))
CREATE TABLE Sheet2 (id INT, name char(255))
// for inserts use a parameterized command with ?'s
INSERT INTO Sheet1 (id, name) VALUES(?, ?)
INSERT INTO Sheet1 (id, name) VALUES(?, ?)

您使用Path.GetTempFileName创建临时excel文件并输出,之后您可以删除临时文件。