简体   繁体   English

如何在一个MS Excel文件中将2个gridviews导出到2个单独的工作表中?

[英]How do I export 2 gridviews into 2 separate sheets in one MS Excel file?

How do I export 2 gridviews (GridView1 & GridView2) into 2 separate sheets in one MS Excel file with the click of 1 button? 如何通过单击1按钮将2个gridviews(GridView1和GridView2)导出到一个MS Excel文件中的2个单独的工作表中? Currently, I'm able to export only 1 gridview to an Excel sheet which the filename is the same as the sheet name. 目前,我只能将1个gridview导出到Excel工作表,该工作表的文件名与工作表名称相同。 But I would like to 2 gridviews into 2 separate sheets which I would like sheet name to be define/set by myself. 但是我想将gridviews分为2个单独的工作表,我希望工作表名称由我自己定义/设置。 Thanks 谢谢

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

//Edit my answer since there is only 1 export button: Take a look at this question : //编辑我的答案,因为只有一个导出按钮:看一下这个问题

firstly add these namespace: 首先添加以下名称空间:

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

So basically you should have (or go ahead and make them) 2 DataTable (to bind to 2 gridviews): dt1 and dt2 因此,基本上,您应该拥有(或继续制作)2个DataTable(以绑定到2个gridviews):dt1和dt2

Make a dataset and add 2 datatables to it 制作数据集并向其中添加2个数据表

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

then 然后

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

to change worksheet name, I believe you can do: 更改工作表名称,我相信您可以这样做:

currentSheet.Name = "your sheet name"

you need to modifiy your code so that you will create a worksheet in the excel file and manually copy the data from grid to excel file and create this code as a function that takes grid,sheetname and sheetid like 1 ,2 and so on as arguments and then within button click event call it twice once for grid1 and once for grid2 with different sheetnames and sheet ids 1 and 2 respectively. 您需要修改代码,以便在excel文件中创建工作表,然后将数据从网格手动复制到excel文件,并将此代码创建为以Grid,Sheetname和Sheetid之类的参数(如1,2等)作为参数的函数然后在按钮单击事件中,分别对grid1调用两次,对grid2调用一次,分别使用不同的工作表名称和工作表ID 1和2对其进行调用。 the code for the function is as follows. 该函数的代码如下。

Write these two line of code in button click event and after that call the function twice once for each grid by passing excel app and workbook also as arguments. 在按钮单击事件中编写这两行代码,然后通过将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();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM