
Originally Posted by
JohnH
How are you exporting to Excel?
JohnH, I am using the Excel.Application class and a reference to MS Excel Object 14.0 Library
Namespace import
Imports Excel = Microsoft.Office.Interop.Excel
Imports Word = Microsoft.Office.Interop.Word
heres some code
Code:
Dim oXL As Excel.Application
Dim oWB As Excel.Workbook
Dim oSheet As Excel.Worksheet
Dim oRange As Excel.Range
oXL = New Excel.Application
'oXL.Visible = True '
oXL.DisplayAlerts = False
oWB = oXL.Workbooks.Add
oSheet = DirectCast(oWB.ActiveSheet, Excel.Worksheet)
oSheet.Name = "vInventory"
Dim dt As New DataTable
dt = (DirectCast(DataGridView1.DataSource, DataTable))
Dim rowCount As Integer = 1
For Each dr As DataRow In dt.Rows
rowCount += 1
For i As Integer = 1 To dt.Columns.Count
If rowCount = 2 Then
oSheet.Cells(1, i) = dt.Columns(i - 1).ColumnName
End If
oSheet.Cells(rowCount, i) = dr.Item(i - 1).ToString
Next
Next
Dim cellRange As Excel.Range
cellRange = oSheet.Range(oSheet.Cells(2, 1), oSheet.Cells(rowCount,1)) 'first column cells
cellRange.NumberFormat = "MM/DD/YYYY" 'formatted as 'Short date', but in excel it reads 'Custom'
cellRange = oSheet.Range(oSheet.Cells(2, 1), oSheet.Cells(rowCount,1)) 'second column cells
cellRange.NumberFormat = "$#,##.00" 'formatted as 'Currency', but in excel it reads 'Custom',
oRange = oSheet.Range(oSheet.Cells(1, 1), oSheet.Cells(rowCount, dt.Columns.Count))
oRange.EntireColumn.AutoFit()
Dim saveFileDialog1 As New SaveFileDialog
saveFileDialog1.Filter = "Excel Workbook|*.xlsx"
saveFileDialog1.Title = "Export to Excel"
saveFileDialog1.FileName = fileSavePath("xlsx")
saveFileDialog1.ShowDialog()
If saveFileDialog1.FileName <> "" Then
oWB.SaveAs(saveFileDialog1.FileName)
oWB.Close() '
oWB = Nothing
oXL.Quit() '
GC.WaitForPendingFinalizers()
GC.Collect()
end if The formatting works, but in excel it should read 'Short Date' or 'Currency' and not Custom
Maybe I should use a different numberformat property value?
Bookmarks