Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,903 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Hello all ,
i have this below code to export my datagrid view o a CSV format , which i can open in excel later , but the datagrid headers are not getting exported , kindly help me how to include headers of my data grid view while exporting:
private void btnexcelexport_Click(object sender, EventArgs e)
{
int cols;
//open file
StreamWriter wr = new StreamWriter(@"C:\Users\ramadasr\Documents\Export.csv", false, Encoding.UTF8);
//determine the number of columns and write columns to file
cols = iP_SpoolsDataGridView.Columns.Count;
for (int i = 0; i < cols; i++)
{
wr.Write(iP_SpoolsDataGridView.Columns[i].Name.ToString().ToUpper() + ",");
}
wr.WriteLine();
//write rows to excel file
for (int i = 0; i < (iP_SpoolsDataGridView.Rows.Count); i++)
{
for (int j = 0; j < cols; j++)
{
if (iP_SpoolsDataGridView.Rows[i].Cells[j].Value != null)
{
wr.Write(iP_SpoolsDataGridView.Rows[i].Cells[j].Value + ",");
}
else
{
wr.Write(",");
}
}
wr.WriteLine();
}
//close file
wr.Close();
}
here is the image of my exported view:
Maybe try replacing
wr.Write(iP_SpoolsDataGridView.Columns[i].Name.ToString().ToUpper() + ",");
with
wr.Write(iP_SpoolsDataGridView.Columns[i].HeaderText.ToUpper() + ",");