如何在导出的Excel中显示列标题

时间:2013-08-09 13:42:06

标签: wpf export-to-excel

我正在按照教程“将数据从sql server数据库导出到wpf中的excel”。现在我可以成功实现这个功能。但是在导出的Excel文件中,没有列名(数据库列标题,如CustomerId,CustomerName,city,postcode,telephoneNo ......)
Exported Excel

如何获得此功能?另外,我如何打开SaveAs对话框?谢谢。以下是我的代码:

     private void button1_Click(object sender, RoutedEventArgs e)
    {
    string sql = null;
    string data = null;

    int i = 0;
    int j = 0;

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

    xlApp = new Microsoft.Office.Interop.Excel.Application();
    xlWorkBook = xlApp.Workbooks.Add(misValue);
    xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

    SqlConnection cnn = new SqlConnection();
    cnn.ConnectionString = @"Data Source=.\sqlexpress;Initial Catalog=Client;Integrated Security=SSPI;";
    cnn.Open();
    sql = "select * from Customers";
    SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn);
    DataSet ds = new DataSet();
    dscmd.Fill(ds);

    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;
        }
    }


    xlWorkBook.Close(true, misValue, misValue);
    xlApp.Quit();

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

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();
    }
}

1 个答案:

答案 0 :(得分:0)

我不是这方面的专家,但我相信您可以在Range对象中使用下划线字符(_)来选择或编辑列标题:

xlWorkSheet.Range["A1", _].Value2 = "Heading for first column";