调用两个Gridview并将其导出到两个单独的工作表中

时间:2015-10-13 02:00:53

标签: c# asp.net excel gridview

我想将gridview1gridview2导出到两个单独的工作表中,这些工作表可以在我的代码中以grid view 1grid view 2的形式在一个Excel文件中命名。我无法导出到Excel,并且不确定如何在按钮中调用导出并传递参数以导出两个Gridview:

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].Text.ToString();
                }
            }


            // save the application
            workbook.SaveAs(@"C:\Users\testacc\Desktop\Test\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();
        }

我在哪里放置代码?

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

1 个答案:

答案 0 :(得分:0)

您必须在

中创建这些对象

public void callingfunction(){

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



ExportToExcel(app, workbook, gv1, 'sheet1', 1)

ExportToExcel(app, workbook, gv2, 'sheet2', 2)   
}