0

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

我怎样才能得到这个功能?另外,如何打开另存为对话框?谢谢。以下是我的代码:

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

1 回答 1

0

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

xlWorkSheet.Range["A1", _].Value2 = "Heading for first column";
于 2013-08-09T13:56:07.393 回答