Winforms DataTable转换为Excel

在asp.net中,将数据表转换为excel文件非常容易。 如何在winform中为数据表做同样的事情?

例如:在我的asp.net代码中,这里是我的函数将数据表转换为excel:

Public Shared Sub DataTableToExcel(ByVal dt As DataTable, ByVal FileName As String HttpContext.Current.Response.Clear() HttpContext.Current.Response.Write(Environment.NewLine) For Each row As DataRow In dt.Rows For i As Integer = 0 To dt.Columns.Count - 1 HttpContext.Current.Response.Write(row(i).ToString().Replace(";", String.Empty) + ";") Next HttpContext.Current.Response.Write(Environment.NewLine) Next HttpContext.Current.Response.ContentType = "application/ms-excel" HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName + ".xls") HttpContext.Current.Response.[End]() End Sub 

但是在winforms中,你不能像现在这样使用它。 您需要读出数据表并创build/打开Excel工作簿。

我希望有一种方法可以直接将winforms中使用的数据表转换为excel。

谢谢。