Export data from listview to excel vb.net - excel

I export data from listview to excel. With this code below, it exports all the data I want to export. The problem shows when I export to excel next time. Exported data is added to previously created excel.
The code I have used is below:
Private Sub btnExcel_Click(sender As Object, e As EventArgs) Handles btnExcel.Click
Dim objExcel As New Excel.Application
Dim bkWorkBook As Excel.Workbook
Dim shWorkSheet As Excel.Worksheet
Dim i As Integer
Dim j As Integer
objExcel = New Excel.Application
bkWorkBook = objExcel.Workbooks.Add
shWorkSheet = CType(bkWorkBook.ActiveSheet, Excel.Worksheet)
For i = 0 To Me.ListView3.Columns.Count - 1
shWorkSheet.Cells(1, i + 1) = Me.ListView3.Columns(i).Text
Next
For i = 0 To Me.ListView3.Items.Count - 1
For j = 0 To Me.ListView3.Items(i).SubItems.Count - 1
shWorkSheet.Cells(i + 2, j + 1) = Me.ListView3.Items(i).SubItems(j).Text
Next
objExcel.Cells.Select()
objExcel.Cells.EntireColumn.AutoFit()
objExcel.Cells.EntireRow.AutoFit()
objExcel.Cells.Range("A1").Select()
Next
bkWorkBook.SaveAs("C:\PDF\Naročilo " + TxtPodjetje.Text + " " + DT_DatumNaročila.Text + ".xlsx")
bkWorkBook.Close()
objExcel.Quit()
If I close created vb.net app after the first export and restart it works properly and I get data as I want.
Any help would be really appreciated!

Related

Add an Excel Form Control to a file in vb.net

I've got an application written that does a pretty standard dump of a datagridview into an Excel file. The application loops through 12 items and creates a separate sheet in the workbook, then filling in the table using the datagridview.
The export is all good, but what I want to do now is add to every every sheet an additional column that contains a check box on every row in that sheet. It seems the better way to do that is add the form control before the Excel file is saved in the code, but I can't work out if that is possible - Adding a checkbox column to the datagridview doesn't seem to be a viable option.
Code - the dtResults is a datatable filled by a Microsoft SQL query.
Private Sub btnProcess_Click(sender As Object, e As EventArgs) Handles btnProcess.Click
Dim TestsDT As New DataTable
TestsDT.Columns.Add("SvcAbbrev")
TestsDT.Rows.Add("PH.")
TestsDT.Rows.Add("LCFA")
TestsDT.Rows.Add("FAECALP")
TestsDT.Rows.Add("PE-1")
TestsDT.Rows.Add("BGLUC")
TestsDT.Rows.Add("SIGAF")
TestsDT.Rows.Add("CALP")
TestsDT.Rows.Add("HELPFAE")
TestsDT.Rows.Add("M2-PK")
TestsDT.Rows.Add("FAEZONULIN")
TestsDT.Rows.Add("FAEFAESIGA")
Dim xlApp As Microsoft.Office.Interop.Excel.Application
Dim xlWorkBook As Microsoft.Office.Interop.Excel.Workbook
Dim xlWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim z As Integer
Dim x As Integer
xlApp = New Microsoft.Office.Interop.Excel.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
For l = 0 To TestsDT.Rows.Count - 1
txtTest.Text = TestsDT.Rows(l).Item("SvcAbbrev")
dgResults.DataSource = GetResults()
Dim Count As Integer = 0
Count = dgResults.Rows.Count - 1
If Count < 1 Then
Else
Dim ChkBox As New DataGridViewCheckBoxColumn()
ChkBox.HeaderText = "Checkbox"
ChkBox.Name = "Check"
dgResults.Columns.Insert(4, ChkBox)
xlWorkSheet = xlWorkBook.Sheets.Add()
xlWorkSheet.Name = txtTest.Text
xlWorkSheet.Columns.AutoFit()
For z = 0 To dgResults.RowCount - 2
For x = 0 To dgResults.ColumnCount - 1
For y As Integer = 1 To dgResults.Columns.Count
xlWorkSheet.Cells(1, y) = dgResults.Columns(y - 1).HeaderText
xlWorkSheet.Cells(z + 2, x + 1) = dgResults(x, z).Value.ToString()
Next
Next
Next
End If
Next
xlWorkBook.Sheets("Sheet1").Delete
xlWorkSheet.SaveAs("C:\Users\brettf\desktop\test-output.xlsx")
xlWorkBook.Close()
xlApp.Quit()
MessageBox.Show("Processing complete. Excel file should open automatically.", "Processing Complete", MessageBoxButtons.OK, MessageBoxIcon.Information)
Process.Start("C:\Users\brettf\desktop\test-output.xlsx")
Current Output:
Desired Output:
The checkbox has no bearing to anything in the datagridview and will be used once the document is printed by another group of staff within the business.

Export more than 2000 row of data from a data gridview to excel file in vb.net

I did succeed to export data from a DataGridView to excel file by using a loop and writing cell by cell, but the problem is i have more than 2000 rows so the exporting process takes a lot of time.
My question is : Is there anything to change so i can minimize the exportation time ?
Thanks
'exporter
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
xlApp = New Excel.Application
xlBook = xlApp.Workbooks.Open(Filename:=Path.Combine(Application.StartupPath, "EMP_.xlsx"), IgnoreReadOnlyRecommended:=True, ReadOnly:=False, Editable:=True)
xlSheet = xlBook.Worksheets(1)
If DataGridView1.DataSource IsNot Nothing Then
Dim i, j As Integer
For i = 1 To DataGridView1.RowCount - 1
For j = 1 To DataGridView1.ColumnCount
xlSheet.Cells(i + 1, j) = DataGridView1.Rows(i - 1).Cells(j - 1).Value
Next
Next
xlApp.Visible = True
xlApp.UserControl = True
xlApp.Quit()
xlApp = Nothing
Else
MsgBox("Le tableau est vide")
End If
End Sub
Not sure if this is something might be open too. By chance if you could load your DataGridView via setting the DataSource of the DataGridView to a DataTable then the following would be an option.
Using SpreadSheetLight (installed via NuGet) you can use a function like the sample below. Pass in the following, full path and file name, sheet name, the DataTable from the DataGridView e.g. Dim dt As DataTable = CType(DataGridView1.DataSource,DataTable) and the last argument if True included column headers (DataColumn names) or False exclude column names.
SpreadSheetLight home page.
Public Sub SimpleExportRaw(
pFileName As String,
pSheetName As String,
pDataTable As DataTable,
pColumnHeaders As Boolean)
Using doc As New SLDocument()
doc.SelectWorksheet(pSheetName)
doc.ImportDataTable(1, SLConvert.ToColumnIndex("A"), pDataTable, pColumnHeaders)
doc.SaveAs(pFileName)
End Using
End Sub

Visual Basic - Saving textbox to Excel file

I would like to setup a webpage that users can paste work orders into a textbox, click submit, and it writes it to .xlsx on a server.
I've gotten StreamWriter to save it to a .txt, but doesn't work/isn't compatible with .xlsx.
Could someone point me in the right direction? I'm not looking for someone to do it for me, but I am new to coding, so I've got tons of stupid questions.
If you had the users input the work orders into a datagrid instead of a textbox, your export to excel would be easier and look better.
Function EXPTOEXLS()
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 'need to add reference to "Microsoft Excel xx object library" then add | IMPORTS microsoft.office.interop (add to top)
Try
Dim excelBook As Excel.Workbook = xlApp.Workbooks.Add
Dim excelWorksheet As Excel.Worksheet = CType(excelBook.Worksheets(1), Excel.Worksheet)
xlApp.Visible = True
rowsTotal = DataGridView1.RowCount - 1
colsTotal = DataGridView1.Columns.Count - 1
With excelWorksheet
.Cells.Select()
.Cells.Delete()
For iC = 0 To colsTotal
.Cells(1, iC + 1).Value = DataGridView1.Columns(iC).HeaderText
Next
For I = 0 To rowsTotal
For j = 0 To colsTotal
.Cells(I + 2, j + 1).value = DataGridView1.Rows(I).Cells(j).Value
Next j
Next I
.Rows("1:1").Font.FontStyle = "Bold"
.Rows("1:1").Font.Size = 10
.Cells.Columns.AutoFit()
.Cells.Select()
.Cells.EntireColumn.AutoFit()
.Cells(1, 1).Select()
End With
Catch ex As Exception
MsgBox(ex.Message)
Finally
'RELEASE ALLOACTED RESOURCES
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default
xlApp = Nothing
End Try
End Function

Exporting to Excel - Make DateTime columns into Date

I've got an Export to Excel function in my application.
There are no problems with the program itself, but when exporting data, it shows DateTime values as dd/MM/yyyy 00:00:00, which, when displaying them on a DataGridView before importing, shows empty cells in some places.
I need to adapt my export code to remove the time portion of the data, and just display the date. When I highlight the cell in Excel, I am formatting it to be 'Date' of format dd/MM/yyyy.
How can I do this programatically?
my code
Dim xlapp As Excel.Application
Dim xlWorkbook As Excel.Workbook
Dim xlWorksheet As Excel.Worksheet
Dim misvalue As Object = Reflection.Missing.Value
xlapp = New Excel.Application
xlWorkbook = xlapp.Workbooks.Add(misvalue)
xlWorksheet = xlWorkbook.Sheets.Add
xlWorksheet.Name = "SupplierInformation"
xlWorksheet.Cells.NumberFormat = "#"
For k As Integer = 1 To dgvExport.Columns.Count
xlWorksheet.Cells(1, k) = dgvExport.Columns(k - 1).HeaderText
Next
For i = 0 To dgvExport.RowCount - 1
For j = 0 To dgvExport.ColumnCount - 1
xlWorksheet.Cells(i + 2, j + 1) = dgvExport(j, i).Value.ToString
Next
Next
xlWorksheet.Columns.AutoFit()
Declare a variable that will be used for referring to a range, eg;
Dim eRange as Excel.Range
Then, set the range in your Worksheet
eRange = xlWorksheet.Range("A1", B5")
Then set the format, using .NumberFormat
eRange.NumberFormat = "dd/MM/yyyy"
FYI: This link contains pretty much all of the information you could ever need on how to format Excel data and cells using VB

export mysql table data with column header using vb.net

i want to export mysql table data with column heading to excel sheet. am using vb.net. but am not able to get table column heading in excel sheet. am getting only mysql table data.
my code
-------
Dim i, j As Integer
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
xlApp = New Excel.ApplicationClass
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
For i = 0 To ds.Tables(0).Rows.Count - 1
For j = 0 To ds.Tables(0).Columns.Count - 1
xlWorkSheet.Cells(i + 1, j + 1) = _
ds.Tables(0).Rows(i).Item(j)
Next
Next
xlWorkSheet.SaveAs("D:\vbexcel.xlsx")
xlWorkBook.Close()
xlApp.Quit()
I don't know Vb.net, but I had a similar issue and had to use the syntax:
IGNORE 1 LINES in the statement.
http://dev.mysql.com/doc/refman/5.1/en/load-data.html (this is for importing, but the IGNORE 1 LINES syntax is described here...)

Resources