when export datagridview to excel data exported without Header text of column

Posted by Ahmedsa under C# on 1/29/2018 | Points: 10 | Views : 943 | Status : [Member] | Replies : 2
Problem

Export datagridview to excel data exported without Header text of column .

Detais

when export datagridview to excel it export success but all data exported without header

so How to solve this problem .

private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
private void button1_Click(object sender, EventArgs e)
{

Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;

xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
int i = 0;
int j = 0;
for ( i = 1; i < ScfGrid.Columns.Count + 1; i++)
{
if (ScfGrid.Columns[i - 1].Visible)
{
xlWorkSheet.Cells[1, i] = ScfGrid.Columns[i - 1].HeaderText;
}
}
for (i = 0; i <= ScfGrid.RowCount - 1; i++)
{
for (j = 0; j <= ScfGrid.ColumnCount - 1; j++)
{
DataGridViewCell cell = ScfGrid[j, i];
xlWorkSheet.Cells[i + 1, j + 1] = cell.Value;
}
}

xlWorkBook.SaveAs("D:\\ahmed.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();

releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);

MessageBox.Show("Excel file created , you can find the file c:\\csharp.net-informations.xls");


}




Responses

Posted by: Prabahkar on: 1/30/2018 [Member] Starter | Points: 25

Up
0
Down
Hi, i suggest that you use Spire.XLS to export data from datatable to Excel, it offers a method InsertDataTable(DataTable dataTable, bool columnHeaders, int firstRow, int firstColumn) to include column hearders when writing datatable to Excel, by setting the columnHeaders parameter as true.

https://www.e-iceblue.com/Introduce/excel-for-net-introduce.html


Ahmedsa, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Mattbrown on: 2/10/2018 [Member] Starter | Points: 25

Up
0
Down
Alpha writing services provide you the best in class, plagiarism free and value for money blog at your convenient time from expert Writers.

https://www.tech-help-support.com/apple-support/iphone-support/

Ahmedsa, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response