如何在一个MS Excel文件中将2个网格视图导出为2个单独的工作表?

时间:2015-09-27 12:46:35

标签: c# asp.net excel gridview

如何通过单击1按钮将2个网格视图(GridView1和GridView2)导出到一个MS Excel文件中的2个单独的工作表中?目前,我只能将1个gridview导出到Excel工作表,其中文件名与工作表名称相同。但我想将2个网格视图分成两个单独的工作表,我希望自己定义/设置工作表名称。感谢

public void ExportGridToExcel()
{
      Response.Clear();
      Response.Buffer = true;
      Response.ClearContent();
      Response.ClearHeaders();
      Response.Charset = "";

      string FileName ="Export"+DateTime.Now+".xls";

      StringWriter strwritter = new StringWriter();
      HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);

      Response.Cache.SetCacheability(HttpCacheability.NoCache);
      Response.ContentType = "application/vnd.ms-excel";
      Response.AddHeader("Content-Disposition","attachment;filename=" + FileName);

      GridView1.GridLines = GridLines.Both;
      GridView1.HeaderStyle.Font.Bold = true;
      GridView1.RenderControl(htmltextwrtter);

      Response.Write(strwritter.ToString());
      Response.End();
}

2 个答案:

答案 0 :(得分:0)

//编辑我的答案,因为只有一个导出按钮: 看看this question

首先添加这些命名空间:

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

所以基本上你应该(或继续制作它们)2 DataTable(绑定到2个网格视图):dt1和dt2

制作数据集并向其添加2个数据表

DataSet dataset = new DataSet();
        dataset.Tables.Add(dt1);
        dataset.Tables.Add(dt2);

然后

//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();

更改工作表名称,我相信你可以这样做:

currentSheet.Name = "your sheet name"

答案 1 :(得分:0)

您需要修改代码,以便在excel文件中创建工作表并手动将数据从网格复制到excel文件,并将此代码创建为一个函数,它将grid,sheetname和sheetid视为1,2等等在作为参数然后在按钮单击事件中,为grid1调用一次,为grid2调用一次,分别使用不同的sheetnames和sheet id 1和2。该功能的代码如下。

在按钮点击事件中写下这两行代码,然后通过将excel应用程序和工作簿也作为参数传递,为每个网格调用两次函数。

     // creating Excel Application
     Microsoft.Office.Interop.Excel._Application app  = new Microsoft.Office.Interop.Excel.Application();

    // creating new WorkBook within Excel application
    Microsoft.Office.Interop.Excel._Workbook workbook =  app.Workbooks.Add(Type.Missing);

 public void ExportToExcel(Microsoft.Office.Interop.Excel._Application app, Microsoft.Office.Interop.Excel._Workbook workbook,GridView gridview,string SheetName,int sheetid)
 {  


        // creating new Excelsheet in workbook
         Microsoft.Office.Interop.Excel._Worksheet worksheet = null;                   

       // see the excel sheet behind the program
        app.Visible = true;

       // get the reference of first sheet. By default its name is Sheet1.
       // store its reference to worksheet
        worksheet = workbook.Sheets["Sheet"+ sheetid];
        worksheet = workbook.ActiveSheet;

        // changing the name of active sheet
        worksheet.Name = sheetname; 

        // storing header part in Excel
        for(int i=1;i<gridview.Columns.Count+1;i++)
        {
              worksheet.Cells[1, i] = gridview.Columns[i-1].HeaderText;
        }



        // storing Each row and column value to excel sheet
        for (int i=0; i < gridview.Rows.Count-1 ; i++)
        {
            for(int j=0;j<gridview.Columns.Count;j++)
            {
                worksheet.Cells[i + 2, j + 1] = gridview.Rows[i].Cells[j].Value.ToString();
            }
        }


        // save the application
        workbook.SaveAs("c:\\output.xls",Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive , Type.Missing, Type.Missing, Type.Missing, Type.Missing);

        // Exit from the application
      app.Quit();
    }