Quantcast
Channel: Visual Studio and Visual Web Developer Express
Viewing all articles
Browse latest Browse all 3509

Error recevied upon exporting of 2 gridviews into excel.

$
0
0

I have this export function that allows me to export 2 gridviews into 2 separated worksheets, however upon clicking the export button the excel file is created.

But my problems are: 1. I am unable to create the worksheet for Gridview2 and populate the data. Only managed to create worksheet and populate data  for Gridview1
The error I received is at

worksheet.Cells[1, i] = gridview.Columns[i - 1].HeaderText; Exception is when populating the first colummn upon taking in sheetid =2

My guess is that because the 2nd worksheet is not created that's why. Please advice

protected void EXPORT_BUTTON_Click(object sender, EventArgs e)
{
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);
String DT1 = "Data table 1";
String DT2 = "Data table 2";
ExportToExcel(app, workbook, Gridview1, DT1, 1);
ExportToExcel(app, workbook, Gridview2, DT2, 2);   
}
public void ExportToExcel(Microsoft.Office.Interop.Excel._Application app, Microsoft.Office.Interop.Excel._Workbook workbook, GridView gridview, string SheetName, int sheetid)
{

 
    // 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
    Excel.Worksheet worksheet = (Excel.Worksheet))workbook.Worksheets["Sheet" + sheetid];
    worksheet = workbook.ActiveSheet;
worksheet = (Excel.Worksheet)workbook,Worksheets.Add(); // 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(); } }


Viewing all articles
Browse latest Browse all 3509

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>