views:

487

answers:

2

In asp.net, it is quite easy to convert a datatable to an excel file. How do I do the same for datatables in winforms?

For Example: in my 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

But in winforms, you cannot use the same as it is. You need to read out the datatable and create/open the excel workbook.

I wish there is a way to directly convert datatable used in winforms to excel fast.

Thanks.

A: 

Check the following link:

c# (WinForms-App) export DataSet to Excel

Wael Dalloul
In the link you provided, there is a code snippet: if (openAfter) OpenFile(fileName);There is no declaration for the said function. Could you help me out on this? Thanks.
Batuta
I was able to work around on the function I mentioned on my last comment. Now when I run the application, I am getting the error: xml type 'list of xdt:untypedAtomic' does not support a conversion from Clr type 'DBNull' to Clr type 'String'i am ensuring that the data in my datatable either contains a string value or simply an empty string "". No DBNulls.
Batuta