I am trying to export content of a SQL Server database table to an Excel document. The problem I have is that the table column names are not showing up as column headers in Excel.
public partial class Reports : System.Web.UI.Page
{
protected void reportbtn_Click(object sender, EventArgs e)
{
SqlConnection cnn;
string connectionString = null;
string sql = null;
string data = null;
int i = 0;
int j = 0;
//Creates the Excel Workbook
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application();
ExcelApp.ScreenUpdating = true;
ExcelApp.Visible = true;
ExcelApp.Interactive = true;
ExcelApp.IgnoreRemoteRequests = false;
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
//Connects to Database
connectionString = "data source=LocalHost;initial catalog=KPMG;Integrated Security=True";
cnn = new SqlConnection(connectionString);
cnn.Open()
//Sql Command Statement
sql = "Select FirstName, LastName From EmployeeData Where EmployeeID = 1"; //sql string needs to be adjusted to pull all necessary information
SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn);
DataSet ds = new DataSet();
dscmd.Fill(ds);
// This for loop populates the excel document, but can't figure out how to
// include the table names as headers for the columns
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
for (j = 0; j <= ds.Tables[0].Columns.Count - 1; j++)
{
data = ds.Tables[0].Rows[i].ItemArray[j].ToString();
xlWorkSheet.Cells[i + 1, j + 1] = data;
}
}
//saves excel workbook to C:
xlWorkBook.SaveAs("TravelReport.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:/Users/LabPatron/Documents/TravelReport.xls");
}
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();
}
}
}