For some reason when I am writing my datatable to excel I am getting the below error message. It appears that the error is happening within my second for loop.
Exception from HRESULT: 0x800A03EC
Public Shared Sub ExportExcel(ByVal dt As DataTable)
Try
Dim strFile As String = MYFilelocation
Dim excel As New Microsoft.Office.Interop.Excel.ApplicationClass
Dim wBook As Microsoft.Office.Interop.Excel.Workbook
Dim wSheet As Microsoft.Office.Interop.Excel.Worksheet
wBook = excel.Workbooks.Add()
wSheet = wBook.ActiveSheet()
Dim dc As System.Data.DataColumn
Dim dr As System.Data.DataRow
Dim colIndex As Integer = 0
Dim rowIndex As Integer = 0
For Each dc In dt.Columns
colIndex = colIndex + 1
excel.Cells(1, colIndex) = dc.ColumnName
Next
For Each dr In dt.Rows
rowIndex = rowIndex + 1
colIndex = 0
For Each dc In dt.Columns
colIndex = colIndex + 1
excel.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)
Next
Next
wSheet.Columns.AutoFit()
wBook.SaveAs(strFile)
wBook.Close()
Catch ex As Exception
MessageBox.Show("there was an issue Exporting to Excel" & ex.ToString)
End Try
End Sub
Try this:
Dim workbook = New ExcelFile
Dim worksheet = workbook.Worksheets.Add("DataTable to Sheet")
Dim dataTable = New DataTable
dataTable.Columns.Add("ID", Type.GetType("System.Int32"))
dataTable.Columns.Add("FirstName", Type.GetType("System.String"))
dataTable.Columns.Add("LastName", Type.GetType("System.String"))
dataTable.Rows.Add(New Object() {100, "John", "Doe"})
dataTable.Rows.Add(New Object() {101, "Fred", "Nurk"})
dataTable.Rows.Add(New Object() {103, "Hans", "Meier"})
dataTable.Rows.Add(New Object() {104, "Ivan", "Horvat"})
dataTable.Rows.Add(New Object() {105, "Jean", "Dupont"})
dataTable.Rows.Add(New Object() {106, "Mario", "Rossi"})
worksheet.Cells(0, 0).Value = "DataTable insert example:"
' Insert DataTable to an Excel worksheet.
worksheet.InsertDataTable(dataTable,
New InsertDataTableOptions() With
{
.ColumnHeaders = True,
.StartRow = 2
})
workbook.Save("DataTable to Sheet.xlsx")
I have tried many methods to create multiple Excel files required for my project. But all are slow down the process. Ultimately, I found that this is the fastest method to create Excel files.
Imports:
Imports DocumentFormat.OpenXml.Packaging
Add references to project
WindowsBase
DocumentFormat.OpenXml
Install-Package DocumentFormat.OpenXml
Full Code:
Private Sub ExportDataSet(ByVal DataTable_In As DataTable, ByVal Destination As String, Optional ds As DataSet = Nothing)
Dim FileName As String = "ExcelFileName" & ".xlsx"
Using workbook = SpreadsheetDocument.Create(Destination & "\" & FileName, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook)
Dim workbookPart = workbook.AddWorkbookPart()
workbook.WorkbookPart.Workbook = New DocumentFormat.OpenXml.Spreadsheet.Workbook()
workbook.WorkbookPart.Workbook.Sheets = New DocumentFormat.OpenXml.Spreadsheet.Sheets()
If Not DataTable_In Is Nothing Then
Dim sheetPart = workbook.WorkbookPart.AddNewPart(Of WorksheetPart)()
Dim sheetData = New DocumentFormat.OpenXml.Spreadsheet.SheetData()
sheetPart.Worksheet = New DocumentFormat.OpenXml.Spreadsheet.Worksheet(sheetData)
Dim sheets As DocumentFormat.OpenXml.Spreadsheet.Sheets = workbook.WorkbookPart.Workbook.GetFirstChild(Of DocumentFormat.OpenXml.Spreadsheet.Sheets)()
Dim relationshipId As String = workbook.WorkbookPart.GetIdOfPart(sheetPart)
Dim sheetId As UInteger = 1
If sheets.Elements(Of DocumentFormat.OpenXml.Spreadsheet.Sheet)().Count() > 0 Then
sheetId = sheets.Elements(Of DocumentFormat.OpenXml.Spreadsheet.Sheet)().[Select](Function(s) s.SheetId.Value).Max() + 1
End If
Dim sheet As DocumentFormat.OpenXml.Spreadsheet.Sheet = New DocumentFormat.OpenXml.Spreadsheet.Sheet() With {
.Id = relationshipId,
.SheetId = sheetId,
.Name = DataTable_In.TableName
}
sheets.Append(sheet)
Dim headerRow As DocumentFormat.OpenXml.Spreadsheet.Row = New DocumentFormat.OpenXml.Spreadsheet.Row()
Dim columns As List(Of String) = New List(Of String)()
For Each column As System.Data.DataColumn In DataTable_In.Columns
columns.Add(column.ColumnName)
Dim cell As DocumentFormat.OpenXml.Spreadsheet.Cell = New DocumentFormat.OpenXml.Spreadsheet.Cell()
cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String
cell.CellValue = New DocumentFormat.OpenXml.Spreadsheet.CellValue(column.ColumnName)
headerRow.AppendChild(cell)
Next
sheetData.AppendChild(headerRow)
For Each dsrow As System.Data.DataRow In DataTable_In.Rows
Dim newRow As DocumentFormat.OpenXml.Spreadsheet.Row = New DocumentFormat.OpenXml.Spreadsheet.Row()
For Each col As String In columns
Dim cell As DocumentFormat.OpenXml.Spreadsheet.Cell = New DocumentFormat.OpenXml.Spreadsheet.Cell()
cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String
cell.CellValue = New DocumentFormat.OpenXml.Spreadsheet.CellValue(dsrow(col).ToString())
newRow.AppendChild(cell)
Next
sheetData.AppendChild(newRow)
Next
Else
For Each table As System.Data.DataTable In ds.Tables
Dim sheetPart = workbook.WorkbookPart.AddNewPart(Of WorksheetPart)()
Dim sheetData = New DocumentFormat.OpenXml.Spreadsheet.SheetData()
sheetPart.Worksheet = New DocumentFormat.OpenXml.Spreadsheet.Worksheet(sheetData)
Dim sheets As DocumentFormat.OpenXml.Spreadsheet.Sheets = workbook.WorkbookPart.Workbook.GetFirstChild(Of DocumentFormat.OpenXml.Spreadsheet.Sheets)()
Dim relationshipId As String = workbook.WorkbookPart.GetIdOfPart(sheetPart)
Dim sheetId As UInteger = 1
If sheets.Elements(Of DocumentFormat.OpenXml.Spreadsheet.Sheet)().Count() > 0 Then
sheetId = sheets.Elements(Of DocumentFormat.OpenXml.Spreadsheet.Sheet)().[Select](Function(s) s.SheetId.Value).Max() + 1
End If
Dim sheet As DocumentFormat.OpenXml.Spreadsheet.Sheet = New DocumentFormat.OpenXml.Spreadsheet.Sheet() With {
.Id = relationshipId,
.SheetId = sheetId,
.Name = table.TableName
}
sheets.Append(sheet)
Dim headerRow As DocumentFormat.OpenXml.Spreadsheet.Row = New DocumentFormat.OpenXml.Spreadsheet.Row()
Dim columns As List(Of String) = New List(Of String)()
For Each column As System.Data.DataColumn In table.Columns
columns.Add(column.ColumnName)
Dim cell As DocumentFormat.OpenXml.Spreadsheet.Cell = New DocumentFormat.OpenXml.Spreadsheet.Cell()
cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String
cell.CellValue = New DocumentFormat.OpenXml.Spreadsheet.CellValue(column.ColumnName)
headerRow.AppendChild(cell)
Next
sheetData.AppendChild(headerRow)
For Each dsrow As System.Data.DataRow In table.Rows
Dim newRow As DocumentFormat.OpenXml.Spreadsheet.Row = New DocumentFormat.OpenXml.Spreadsheet.Row()
For Each col As String In columns
Dim cell As DocumentFormat.OpenXml.Spreadsheet.Cell = New DocumentFormat.OpenXml.Spreadsheet.Cell()
cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String
cell.CellValue = New DocumentFormat.OpenXml.Spreadsheet.CellValue(dsrow(col).ToString())
newRow.AppendChild(cell)
Next
sheetData.AppendChild(newRow)
Next
Next
End If
End Using
End Sub
Related
How to modify my query so that the headers can also be pulled?
Sub AccessToExcel()
ControlFile = ActiveWorkbook.Name
Dim myrange As Range
Set myrange = ActiveWorkbook.Sheets("Control").Range("C9")
Dim i As Integer
i = 1
Do While Len(myrange.Offset(i, 0)) > 0
Dim terr_filter As String
terr_filter = myrange.Offset(i, 1).Value
Dim terr_name As String
terr_name = myrange.Offset(i, 0).Value
Dim file_path As String
file_path = myrange.Offset(i, 3).Value
Dim file_name As String
file_name = myrange.Offset(i, 2).Value
Dim j As Long, sPath_Access_DB As String
Dim oDAO As DAO.DBEngine, oDB As DAO.Database, oRS As DAO.Recordset
Dim strPath As String
sPath_Access_DB = Range("rng_Ctrl_Path").Value
'Exporting Component Summary to Access
If sPath_Access_DB = "" Then Exit Sub
Set oDAO = New DAO.DBEngine
Set oDB = oDAO.OpenDatabase(sPath_Access_DB, dbOpenDynaset)
Set oRS = oDB.OpenRecordset(terr_name)
Sheets.Add After:=ActiveSheet
Range("B2").CopyFromRecordset oRS
ActiveSheet.Name = terr_filter
oDB.Close
i = i + 1
Loop
End Sub
You need to loop and extract them yourself:
For j = 1 to oRS.Fields.Count
Cells(1, j + 1).Value = oRS.Fields(j - 1).Name
Next
I’m using VB.net on Microsoft visual studio 2017, to create a little App and I’m having a problem with the code that I’m using to export my Datagridview to excel. It exports everything but the last row of my data. Any idea how I can fix this?
Imports Excel = Microsoft.Office.Interop.Excel
Imports Microsoft.Office
Imports Microsoft.Office.Interop
Imports System.IO
Private Sub ExportToExcel()
' Creating a Excel object.
Dim excel As Microsoft.Office.Interop.Excel._Application = New Microsoft.Office.Interop.Excel.Application()
Dim workbook As Microsoft.Office.Interop.Excel._Workbook = excel.Workbooks.Add(Type.Missing)
Dim worksheet As Microsoft.Office.Interop.Excel._Worksheet = Nothing
Try
worksheet = workbook.ActiveSheet
worksheet.Name = "ExportedFromDatGrid"
Dim cellRowIndex As Integer = 1
Dim cellColumnIndex As Integer = 1
'Write headers
For j As Integer = 0 To DataGridView_Kontakte.Columns.Count - 2
worksheet.Cells(cellRowIndex, cellColumnIndex) = DataGridView_Kontakte.Columns(j).HeaderText
cellColumnIndex += 1
Next
cellColumnIndex = 1
cellRowIndex += 1
'Loop through each row and read value from each column.
For i As Integer = 0 To DataGridView_Kontakte.Rows.Count - 2
For j As Integer = 0 To DataGridView_Kontakte.Columns.Count - 1
' Excel index starts from 1,1. As first Row would have the Column headers, adding a condition check.
worksheet.Cells(cellRowIndex, cellColumnIndex) = DataGridView_Kontakte.Rows(i).Cells(j).Value.ToString()
cellColumnIndex += 1
Next
cellColumnIndex = 1
cellRowIndex += 1
Next
'Getting the location and file name of the excel to save from user.
Dim saveDialog As New SaveFileDialog()
saveDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*"
saveDialog.FilterIndex = 2
If saveDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
workbook.SaveAs(saveDialog.FileName)
MessageBox.Show("Export Successful")
End If
Catch ex As System.Exception
MessageBox.Show(ex.Message)
Finally
excel.Quit()
workbook = Nothing
excel = Nothing
End Try
End Sub
You can try my function to export in EXCEL
Sub ExportExcel(ByVal obj As Object)
Dim rowsTotal, colsTotal As Short
Dim I, j, iC As Short
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor
Dim xlApp As New Excel.Application
Try
Dim excelBook As Excel.Workbook = xlApp.Workbooks.Add
Dim excelWorksheet As Excel.Worksheet = CType(excelBook.Worksheets(1), Excel.Worksheet)
xlApp.Visible = True
rowsTotal = obj.RowCount
colsTotal = obj.Columns.Count - 1
With excelWorksheet
.Cells.Select()
.Cells.Delete()
For iC = 0 To colsTotal
.Cells(1, iC + 1).Value = obj.Columns(iC).HeaderText
Next
For I = 0 To rowsTotal - 1
For j = 0 To colsTotal
.Cells(I + 2, j + 1).value = obj.Rows(I).Cells(j).Value
Next j
Next I
.Rows("1:1").Font.FontStyle = "Bold"
.Rows("1:1").Font.Size = 12
.Cells.Columns.AutoFit()
.Cells.Select()
.Cells.EntireColumn.AutoFit()
.Cells(1, 1).Select()
End With
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
'RELEASE ALLOACTED RESOURCES
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default
xlApp = Nothing
End Try
End Sub
From Datgridview to Excel? It should be done like this.
Imports System.Data
Imports System.Data.SqlClient
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim cnn As SqlConnection
Dim connectionString As String
Dim sql As String
connectionString = "data source=servername;" & _
"initial catalog=databasename;user id=username;password=password;"
cnn = New SqlConnection(connectionString)
cnn.Open()
sql = "SELECT * FROM Product"
Dim dscmd As New SqlDataAdapter(sql, cnn)
Dim ds As New DataSet
dscmd.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
cnn.Close()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button2.Click
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Integer
Dim j As Integer
xlApp = New Excel.ApplicationClass
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
For i = 0 To DataGridView1.RowCount - 2
For j = 0 To DataGridView1.ColumnCount - 1
xlWorkSheet.Cells(i + 1, j + 1) = _
DataGridView1(j, i).Value.ToString()
Next
Next
xlWorkSheet.SaveAs("C:\vbexcel.xlsx")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
MsgBox("You can find the file C:\vbexcel.xlsx")
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
End Class
Please see the link below for all relevant information, and several relater links as well.
http://vb.net-informations.com/excel-2007/vb.net_export_from_datagridview_to_excel.htm
i want to do a "Save as" in my program in visual Studio but i have a problem...
This is the code where export datagridview to excel :
If ((DataGridView1.Columns.Count = 0) Or (DataGridView1.Rows.Count = 0)) Then
Exit Sub
End If
Dim dset As New DataSet
dset.Tables.Add()
For i As Integer = 0 To DataGridView1.ColumnCount - 1
dset.Tables(0).Columns.Add(DataGridView1.Columns(i).HeaderText)
Next
Dim dr1 As DataRow
For i As Integer = 0 To DataGridView1.RowCount - 1
dr1 = dset.Tables(0).NewRow
For j As Integer = 0 To DataGridView1.Columns.Count - 1
dr1(j) = DataGridView1.Rows(i).Cells(j).Value
Next
dset.Tables(0).Rows.Add(dr1)
Next
Dim excel As New Microsoft.Office.Interop.Excel.Application
Dim wBook As Microsoft.Office.Interop.Excel.Workbook
Dim wSheet As Microsoft.Office.Interop.Excel.Worksheet
wBook = excel.Workbooks.Add()
wSheet = wBook.ActiveSheet()
Dim dt As System.Data.DataTable = dset.Tables(0)
Dim dc As System.Data.DataColumn
Dim dr As System.Data.DataRow
Dim colIndex As Integer = 0
Dim rowIndex As Integer = 0
For Each dc In dt.Columns
colIndex = colIndex + 1
excel.Cells(1, colIndex) = dc.ColumnName
Next
For Each dr In dt.Rows
rowIndex = rowIndex + 1
colIndex = 0
For Each dc In dt.Columns
colIndex = colIndex + 1
excel.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)
Next
Next
wSheet.Columns.AutoFit()
Dim strFileName As String = "D:\testehorario.xlsx"
Dim blnFileOpen As Boolean = False
Try
Dim fileTemp As System.IO.FileStream = System.IO.File.OpenWrite(strFileName)
fileTemp.Close()
Catch ex As Exception
blnFileOpen = False
End Try
If System.IO.File.Exists(strFileName) Then
System.IO.File.Delete(strFileName)
End If
wBook.SaveAs(strFileName)
excel.Workbooks.Open(strFileName)
excel.Visible = True
and this is the code that does the "Save as":
Dim sfd As New SaveFileDialog() ' this creates an instance of the SaveFileDialog called "sfd"
sfd.Filter = "txt files (*.xlsx)|*.xlsx|All files (*.*)|*.*"
sfd.FilterIndex = 1
sfd.RestoreDirectory = True
If sfd.ShowDialog() = DialogResult.OK Then
Dim FileName As String = sfd.FileName ' retrieve the full path to the file selected by the user
Dim sw As New System.IO.StreamWriter(FileName, False) ' create a StreamWriter with the FileName selected by the User
sw.WriteLine(TextBox1.Text) ' Write the contents of TextBox to the file
sw.Close() ' close the file
End If
How can I export a datagridview to excel and make a Save As ? I have already tried using the "Save as" code in the top code but it gives error...
I'm not able to find examples on how to export multiple data sets/tables to a single Excel worksheet utilizing the EPPlus library. When I run the codes, it returns one set that happens to be the last set. What am I doing wrong with the following codes? Thanks!
Dim dSets as DataSets
Dim dGrid as DataGrid
Dim dTable as DataTable
Dim sheet as String
sheet = "DumpSets"
Dim attachment as String
attachment = "attachment; filename=" + sheet + ".xlsx"
Dim xlPack as ExcelPackage = New ExcelPackage()
Dim ws as ExcelWorksheet = xlPack.Workbook.Worksheets.Add(sheet)
Response.Clear()
Response.AddHeader("content-disposition", attachment)
Response.Charset = ""
For each dTable in dSets.Tables
dGrid = New DataGrid
Me.EnableViewState = False
dGrid.DataSource = dTable
ws.Cells(1, 1).LoadFromDataTable(dGrid.DataSource, True)
dGrid.DataBind()
Next
Response.BinaryWrite(xlPack.GetAsByteArray())
Response.End()
As #Blackwood already mentioned, you always add the data in the same place.
So it should be something like this:
Dim cnt As Integer = 1
For each dTable in dSets.Tables
dGrid = New DataGrid
Me.EnableViewState = False
dGrid.DataSource = dTable
ws.Cells(1, cnt).LoadFromDataTable(dGrid.DataSource, True)
dGrid.DataBind()
cnt = (cnt + 1)
Next
You could also add every dataset to it's own sheet.
Dim cnt As Integer = 1
For Each dt As DataTable In dSets.Tables
Dim ws As ExcelWorksheet = xlPack.Workbook.Worksheets.Add(("Sheet " + cnt))
ws.Cells(1, 1).LoadFromDataTable(dGrid.DataSource, True)
cnt = (cnt + 1)
Next
Excel gives me an error: excel cannot open the file .xlsx because the file format or file extension is not valid.
Here is my code:
Response.AppendHeader("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
Response.AppendHeader("Content-disposition", "attachment; filename=Excel.xlsx")
Response.ContentEncoding = Encoding.Unicode
Response.BinaryWrite(Encoding.Unicode.GetPreamble)
Response.Write(x.ToString)
Response.End()
I believe it should be like this.
Private Sub DatatableToExcel(ByVal dtTemp As DataTable)
Dim _excel As New Microsoft.Office.Interop.Excel.Application
Dim wBook As Microsoft.Office.Interop.Excel.Workbook
Dim wSheet As Microsoft.Office.Interop.Excel.Worksheet
wBook = _excel.Workbooks.Add()
wSheet = wBook.ActiveSheet()
Dim dt As System.Data.DataTable = dtTemp
Dim dc As System.Data.DataColumn
Dim dr As System.Data.DataRow
Dim colIndex As Integer = 0
Dim rowIndex As Integer = 0
For Each dc In dt.Columns
colIndex = colIndex + 1
_excel.Cells(1, colIndex) = dc.ColumnName
Next
For Each dr In dt.Rows
rowIndex = rowIndex + 1
colIndex = 0
For Each dc In dt.Columns
colIndex = colIndex + 1
_excel.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)
Next
Next
wSheet.Columns.AutoFit()
Dim strFileName As String = "C:\datatable.xlsx"
If System.IO.File.Exists(strFileName) Then
System.IO.File.Delete(strFileName)
End If
wBook.SaveAs(strFileName)
wBook.Close()
_excel.Quit()
End Sub
http://www.authorcode.com/export-datatable-to-excel-in-vb-net/