Winforms数据表转换为Excel

e3bfsja2  于 2023-01-14  发布在  其他
关注(0)|答案(1)|浏览(185)

在www.example.com中,将数据表转换为excel文件是非常容易的。我如何在winforms中对数据表做同样的事情呢?asp.net, it is quite easy to convert a datatable to an excel file. How do I do the same for datatables in winforms?
例如:在我的www.example.com代码中,下面是我将datatable转换为excel的函数:asp.net code, here is my function to convert the datatable to 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中,你不能像它一样使用,你需要读出datatable并创建/打开excel工作簿。
我希望有一种方法可以直接将winforms中使用的datatable快速转换为excel。
谢谢。

btqmn9zl

btqmn9zl1#

这段代码实际上是在创建一个CSV文件(使用分号而不是逗号),并通知Excel打开它。您可以使用以下代码在C#中执行类似的操作。请注意,“FileName”必须包含与Excel关联的扩展名。

Public Shared Sub DataTableToExcel(ByVal dt As DataTable, ByVal FileName As String)
     
    StreamWriter writer = new StreamWriter(FileName)
    
    For Each row As DataRow In dt.Rows
        For i As Integer = 0 To dt.Columns.Count - 1
          writer.Write(row(i).ToString().Replace(";", String.Empty) + ";")
        Next
    
        writer.WriteLine()
    Next
    
    writer.Close()
    
    System.Diagnostics.Process.Start(FileName)

End Sub

相关问题