Hello from Germany,
with following code I export a datatable to Excel.
This works excellent! But there is a problem:
Column M (Datatype String in VS2005) now contains data in example like '7001400'. The original content was '07001400'.
I understand why: because Excel doesn't format the column to 'Text'.
How do I format the column so that my original data table-data is exported correctly?
Before writing data into excel or afterwards?
Thank You for Your help
Marlon
with following code I export a datatable to Excel.
VB.NET:
Private Sub TEST_XLS(ByVal ds As DataSet)
Dim dt As DataTable
'To manipulate an Excel workbook, the code needs to instantiate an Excel Application object,
'and then use the object model to add a new workbook, change the name (to Northwind Customers in this example), and do other UI chores.
'Create an instance of Excel 2003, add a workbook,
'and let the user know what's happening
Dim xl As New Microsoft.Office.Interop.Excel.Application
xl.Workbooks.Add()
xl.ActiveSheet.Name = "KPI-Report"
xl.Visible = True
xl.Range("A1").Value = "Loading the DataSet...."
'Once Excel is loaded and running, the code needs a reference to the table in the DataSet ds.
'Then it loops through the Columns collection of that DataTable object and places the field names
'in the first row of the worksheet. This example uses a Customers table and a Customers column heading.
Try
xl.ScreenUpdating = False
'Start with the Customers table
dt = ds.Tables("VWDWD_EXP_KPI")
'Add the column headings for the Customers
Dim dc As DataColumn
Dim iCols As Int32 = 0
For Each dc In dt.Columns
xl.Range("A1").Offset(0, iCols).Value = dc.ColumnName
iCols += 1
Next
'All that's left is to loop through the rows in the table and use the ItemArray property of the DataRow
'object to write the contents of each data row to a row of the worksheet. This is about as close as Excel
'comes to supporting a DataSet object directly.
'Add the data
Dim iRows As Int32
For iRows = 0 To dt.Rows.Count - 1
xl.Range("A2").Offset(iRows).Resize(1, iCols).Value = dt.Rows(iRows).ItemArray()
Next
Catch ex As Exception
'The remaining code in the procedure updates the UI and applies built-in formatting to the worksheet.
Finally
xl.ScreenUpdating = True
End Try
'Make the sheet pretty
With xl.ActiveSheet.Range("A1")
.AutoFilter()
.AutoFormat(Microsoft.Office.Interop.Excel.XlRangeAutoFormat.xlRangeAutoFormatSimple)
End With
xl = Nothing
End Sub
This works excellent! But there is a problem:
Column M (Datatype String in VS2005) now contains data in example like '7001400'. The original content was '07001400'.
I understand why: because Excel doesn't format the column to 'Text'.
How do I format the column so that my original data table-data is exported correctly?
Before writing data into excel or afterwards?
Thank You for Your help
Marlon