i am trying to export the elements in gridview to excel spreadsheet. that grid hides several columns depending on the condition, here is some of the code
in the def of the button, this is the part where i have prob with exporting
worksheet = workbook.Worksheets["Sheet1"];
//string wname = tab.Text.Replace(" ", "_");
//worksheet.Name = wname;
range = worksheet.Cells["A1"];
for (int i = 0; i < fr_chart_grid.Columns.Count; i++)//count = 7
{
if (fr_chart_grid.Columns[i].Visible == true)
dtData.Columns.Add(fr_chart_grid.HeaderRow.Cells[i].Text);
}
// add each of the data rows to the table
foreach (GridViewRow row in fr_chart_grid.Rows)
{
DataRow drData;
drData = dtData.NewRow();
for (int i = 0; i < row.Cells.Count; i++)
{
if (fr_chart_grid.Columns[i].Visible == true)
drData[i] = row.Cells[i].Text;
}
dtData.Rows.Add(drData);
}
range.CopyFromDataTable(dtData, SpreadsheetGear.Data.SetDataFlags.None);
and here is how my grid is defined
<asp:GridView ID="fr_chart_grid" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Dateval" HeaderText="Date" DataFormatString="{0:d}" HtmlEncode="false" />
<asp:BoundField DataField="Col1" HeaderText="Data" DataFormatString="{0:f3}" />
<asp:BoundField DataField="Col2" HeaderText="" DataFormatString="{0:f3}"/>
<asp:BoundField DataField="Col3" HeaderText="" DataFormatString="{0:f3}"/>
<asp:BoundField DataField="Col4" HeaderText="" DataFormatString="{0:f3}"/>
<asp:BoundField DataField="Col5" HeaderText="" DataFormatString="{0:f3}"/>
<asp:BoundField DataField="Col6" HeaderText="" DataFormatString="{0:f3}"/>
</Columns>
</asp:GridView>
my problem is that i have blank columns when i export the datafield, and sometimes wuts suppose to be in col 3 goes into col 4, with col 3 being blank. othertimes i have 5 rows and it tells me it cannot find the 5th row…it is frustrating….is there a way i could get rid of the blank columns? it’s random and it doesn’t show when i run the website, but it causes prob when i export to excel
It looks like you have at least one issue… where you set the data for a cell in your new row, you are indexing i in both row.Cells and drData — They are out of sync when some columns are not visible.
This line is trouble:
drData may have fewer items than i due to non-visible columns. You’ll be overwritting data that is intended for other columns, or getting exceptions. You need to make sure you index drData with the index of the visible columns.
Something like this should work: