I am using the following code to export a datatable into a Excel spreadsheet.
I am having issues trying to set the AutoFilter on for the top row.
With the code as it stands does turn on the Autofilter , however it gives an error "Unable to Set the Autofilter property of the range class."
Any ideas?
I am having issues trying to set the AutoFilter on for the top row.
With the code as it stands does turn on the Autofilter , however it gives an error "Unable to Set the Autofilter property of the range class."
Any ideas?
VB.NET:
Public Shared Sub PopulateSheet(ByVal dt As DataTable, ByVal File As String) Dim oXL As Excel.Application = CType(CreateObject("Excel.Application"), Excel.Application)
Dim oWB As Excel.Workbook
Dim oSheet As Excel.Worksheet
Dim oRng As Excel.Range
oXL.Visible = True
oWB = oXL.Workbooks.Add
oSheet = CType(oWB.ActiveSheet, Excel.Worksheet)
Dim dc As DataColumn
Dim dr As DataRow
Dim colIndex As Integer = 0
Dim rowIndex As Integer = 0
For Each dc In dt.Columns
colIndex = colIndex + 1
oXL.Cells(1, colIndex) = dc.ColumnName
oXL.Cells(1, colIndex).Style = "Accent1"
Next
For Each dr In dt.Rows
rowIndex = rowIndex + 1
colIndex = 0
For Each dc In dt.Columns
colIndex = colIndex + 1
oXL.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)
Next
Next
oSheet.Cells.Select()
oSheet.Columns.AutoFit()
oSheet.Rows.AutoFit()
oXL.Cells(1, colIndex).AutoFilter = True
oXL.Visible = True
oXL.UserControl = True
oWB.SaveAs(File)
oRng = Nothing
'Close All Objects of Excel
NAR(oSheet)
oWB.Close(False)
NAR(oWB)
oXL.Workbooks.Close()
NAR(oXL.Workbooks)
'quit and dispose app
oXL.Quit()
NAR(oXL)
'VERY IMPORTANT
GC.Collect()
End Sub