Reputation: 430
This is a snippet of my code.
XLWorkbook wb = new XLWorkbook();
GridView[] gvExcel = new GridView[] { gv01PL, gv01PD, gv01T1, gv023P, gv023L, gv02SU };
string[] name = new string[] { "01-PL", "01-PD", "01-T1", "02-3P", "02-3L", "02-SU" };
for (int i = 0; i < gvExcel.Length; i++)//each gridview
{
if (gvExcel[i].Visible)
{
gvExcel[i].AllowPaging = false;
DataTable dt = new DataTable(name[i].ToString());
for (int z = 0; z < gvExcel[i].Columns.Count; z++)
{
dt.Columns.Add(gvExcel[i].Columns[z].HeaderText);
}
foreach (GridViewRow row in gvExcel[i].Rows)
{
dt.Rows.Add();
for (int c = 0; c < row.Cells.Count; c++)
{
dt.Rows[dt.Rows.Count - 1][c] = row.Cells[c].Text;
}
}
wb.Worksheets.Add(dt);
gvExcel[i].AllowPaging = true;
}
}
I am having trouble with this line:
dt.Rows[dt.Rows.Count - 1][c] = row.Cells[c].Text;
It is giving the error of "Cannot find column 0". I know I am missing something simple here. Any help would be greatly appreciated.
Upvotes: 1
Views: 1126
Reputation: 1694
You can be getting this error because the DataTable
doesn't have any columns.
Make sure that this gvExcel[i].Columns.Count
isn't 0 here:
for (int z = 0; z < gvExcel[i].Columns.Count; z++) { dt.Columns.Add(gvExcel[i].Columns[z].HeaderText); }
Upvotes: 2
Reputation: 167
Clone your row instead...
var desRow = dt.NewRow();
var sourceRow = dt.Rows[dt.Rows.Count - 1];
desRow.ItemArray = sourceRow.ItemArray.Clone() as object[];
dt.Rows.Add(desRow);
Upvotes: 0