Im using vb.net in creating excel file but it gives me an error that it cant open file because the file format or file extension file is not valid.
Dim excelLocation As String = txtLocate.Text + txtFilename.Text.Trim + ".xlsx"
Dim source1 As New BindingSource
Dim APP As New Excel.Application
Dim worksheet As Excel.Worksheet
Dim workbook As Excel.Workbook
If System.IO.File.Exists(excelLocation) = False Then
System.IO.File.Create(excelLocation).Dispose()
End If
workbook = APP.Workbooks.Open(excelLocation)
worksheet = workbook.Worksheets("sheet1")
Dim columnsCount As Integer = dgvList.Columns.Count
For Each column In dgvList.Columns
worksheet.Cells(1, column.Index + 1).Value = column.Name
Next
For i As Integer = 0 To dgvList.Rows.Count - 1
Dim columnIndex As Integer = 0
Do Until columnIndex = columnsCount
worksheet.Cells(i + 2, columnIndex + 1).Value = dgvList.Item(columnIndex, i).Value.ToString
columnIndex += 1
Loop
Next
workbook.SaveAs()
workbook.Close()
MsgBox("Save!")
Related
Sources:
Private Sub toEditDataOnReportCell(ByVal passedData As String)
Dim monthlyReportFilePath As String = "./Report/Example.xlsx"
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
'Start a new workbook in Excel
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Open(monthlyReportFilePath)
'Set which worksheet tobe modified
oSheet = oBook.Worksheets(1)
'This will find the lastRow in the sheet
'Dim lastRow As Integer = 7
Dim ETLastRow As Integer = oSheet.usedrange.rows.count
'This is next emptyRow in the sheet
Dim ETemptyRow As Integer = ETLastRow + 1
'edit last empty row val on column 8
Dim columnToMod As Integer = 8
oSheet.Cells(ETemptyRow, columnToMod).value = passedData
ETLastRow = oSheet.usedrange.rows.count
ETemptyRow = ETLastRow + 1
'This will not prompt the user to overwrite the excel sheet
oExcel.DisplayAlerts = False
oBook.Save()
oBook.Close()
oExcel.Quit()
TextBox12.AppendText("Sucess!!!" + vbCrLf + vbCrLf)
End Sub
Giving wrong last row, if in excel doc already have a table with formula in it.
Output Preview:
Targeting In Cell Range (H8:H38)
[1]: https://i.stack.imgur.com/D4RT5.png
But Output In Cell Range (H40:H)
[2]: https://i.stack.imgur.com/0wufs.png
Hehehe, i found the solutions,
Thanks to #StoriKnow & his answer there:
Here is my latest sources:
Private Sub toEditDataOnReportCell(ByVal passedData As String)
Dim monthlyReportFilePath As String = "./Report/Example.xlsx"
Dim oExcel As New Object
Dim oBook As New Object
Dim oSheet As New Object
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Open(monthlyReportFilePath)
oSheet = oBook.Worksheets(1)
Try
Dim sourceCol As Integer, rowCount As Integer, currentRow As Integer
Dim currentRowValue As String
sourceCol = 8 'column H has a value of 8
rowCount = oSheet.Cells(oSheet.Rows.Count, sourceCol).End(Excel.XlDirection.xlUp).Row
'for every row, find the first blank cell and select it
For currentRow = 8 To rowCount
currentRowValue = oSheet.Cells(currentRow, sourceCol).Value
If (currentRowValue Is Nothing) Or (currentRowValue = "") Then
'oSheet.Cells(currentRow, sourceCol).Select
Dim preview As String = currentRow
TextBox12.AppendText(preview + " ")
oSheet.Cells(currentRow, sourceCol).Select
oSheet.Cells(currentRow, sourceCol).value = passedData
Exit Try
End If
Next
Finally
''' DO NOTHING
End Try
''This will not prompt the user to overwrite the excel sheet
oExcel.DisplayAlerts = False
oBook.Save()
oBook.Close()
oExcel.Quit()
end Sub
Output that achived:
I have this code for Exporting from listview to Excel but it is too slow when saving it is there a way to make it much more faster ?
Dim objExcel As New Excel.Application
Dim bkWorkBook As Workbook
Dim shWorkSheet As Worksheet
Dim i As Integer
Dim j As Integer
objExcel = New Excel.Application
objExcel.DisplayAlerts = False
bkWorkBook = objExcel.Workbooks.Add
shWorkSheet = CType(bkWorkBook.ActiveSheet, Worksheet)
shWorkSheet.Name = "ExportedFromListView"
For i = 0 To Me.lvLogs.Columns.Count - 1
shWorkSheet.Cells(1, i + 1) = Me.lvLogs.Columns(i).Text
Next
For i = 0 To Me.lvLogs.Items.Count - 1
For j = 0 To Me.lvLogs.Items(i).SubItems.Count - 1
shWorkSheet.Cells(i + 2, j + 1) = Me.lvLogs.Items(i).SubItems(j).Text
Next
Next
bkWorkBook.SaveAs("D:\SGTSI\Excel Attendance\biodata1.xlsx")
bkWorkBook.SaveAs("D:\SGTSI\Attendance\SPA-" & DateTime.Now.ToString("y"-attendance.xlsx")
bkWorkBook.Close()
I want to export my datagridview rows to a existing excel template with headers that will start from cell A10:AA10.
This is the template:
I've tried this
Public Sub exportToexcel()
Dim default_location As String = "D:\Book1.xlsx"
Dim dset As New DataSet
dset.Tables.Add()
For i As Integer = 0 To dgvReports.ColumnCount - 1
dset.Tables(0).Columns.Add(dgvReports.Columns(i).HeaderText)
Next
add rows to the table
Dim dr1 As DataRow
For i As Integer = 0 To dgvReports.RowCount - 1
dr1 = dset.Tables(0).NewRow
For j As Integer = 0 To dgvReports.Columns.Count - 1
dr1(j) = dgvReports.Rows(i).Cells(j).Value
Next
dset.Tables(0).Rows.Add(dr1)
Next
Dim excel As Microsoft.Office.Interop.Excel.Application
excel = New Microsoft.Office.Interop.Excel.Application
Dim wBook As Microsoft.Office.Interop.Excel.Workbook
Dim wSheet As Microsoft.Office.Interop.Excel.Worksheet
excel.Visible = True
excel.UserControl = True
wBook = excel.Workbooks.Add(System.Reflection.Missing.Value)
wSheet = wBook.Sheets("Sheet1")
excel.Range("A50:I50").EntireColumn.AutoFit()
With wBook
.Sheets("Sheet1").Select()
.Sheets(1).Name = "Sheet1"
End With
Dim dt As System.Data.DataTable = dset.Tables(0)
' wSheet.Cells(1).value = strFileName
For Each col As DataGridViewColumn In dgvReports.Columns
wSheet.Cells(1, col.Index + 1) = col.HeaderText.ToString
Next
For i = 0 To dgvReports.RowCount - 1
For j = 0 To dgvReports.ColumnCount - 1
wSheet.Columns.NumberFormat = "#"
wSheet.Cells(i + 2, j + 1).value = dgvReports.Rows(i).Cells(j).Value.ToString
Next j
Next i
wSheet.Columns.AutoFit()
Dim blnFileOpen As Boolean = False
Try
Dim fileTemp As System.IO.FileStream = System.IO.File.OpenWrite(default_location)
fileTemp.Close()
Catch ex As Exception
blnFileOpen = False
End Try
If System.IO.File.Exists(default_location) Then
System.IO.File.Delete(default_location)
End If
wBook.SaveAs(default_location)
excel.Workbooks.Open(default_location)
excel.Visible = True
End Sub
This only creates a new excel file. I just need to feel a existing excel file.
Replace this line:
wBook = excel.Workbooks.Add(System.Reflection.Missing.Value)
that code will add a new Workbook to your newly created Excel.
This will open the file assigned to the default_location variable:
wBook = excel.Workbooks.Open(default_location)
I have this code to export the data in listview to excel sheet, but this code export data without the header of list view.
How can I edit this code to show the header of the listview?
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
SaveFileDialog1.Title = "Save Excel File"
SaveFileDialog1.Filter = "Excel files (*.xls)|*.xls|Excel Files (*.xlsx)|*.xslx"
SaveFileDialog1.ShowDialog()
'exit if no file selected
If SaveFileDialog1.FileName = "" Then
Exit Sub
End If
'create objects to interface to Excel
Dim xls As New Excel.Application
Dim book As Excel.Workbook
Dim sheet As Excel.Worksheet
'create a workbook and get reference to first worksheet
xls.Workbooks.Add()
book = xls.ActiveWorkbook
sheet = book.ActiveSheet
'step through rows and columns and copy data to worksheet
Dim row As Integer = 1
Dim col As Integer = 1
For Each item As ListViewItem In ListView1.Items
For i As Integer = 0 To item.SubItems.Count - 1
sheet.Cells(row, col) = item.SubItems(i).Text
col = col + 1
Next
row += 1
col = 1
Next
'save the workbook and clean up
book.SaveAs(SaveFileDialog1.FileName)
xls.Workbooks.Close()
xls.Quit()
releaseObject(sheet)
releaseObject(book)
releaseObject(xls)
End Sub
Private Sub releaseObject(ByVal obj As Object)
'Release an automation object
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
You can get each column text by using this code:
Dim columns As New List(Of String)
Dim columncount As Integer = ListView1.Columns.Count - 1
For i As Integer = 0 To columncount
columns.Add(ListView1.Columns(i).Text)
Next
For Each columnname In columns
MessageBox.Show(columnname)
Next
Before you enter the loop to export your data you need to iterate the ColumnHeaderCollection in the ListView
For i = 0 To ListView1.Columns.Count - 1
sheet.Cells(1, i + 1) = ListView1.Items(i).Name
Next
SaveFileDialog1.Title = "Save Excel File"
SaveFileDialog1.Filter = "Excel Files (*.xlsx)|*.xlsx"
SaveFileDialog1.ShowDialog()
'exit if no file selected
If SaveFileDialog1.FileName = "" Then
Exit Sub
End If
'create objects to interface to Excel
Dim xls As New Excel.Application
Dim book As Excel.Workbook
Dim sheet As Excel.Worksheet
'create a workbook and get reference to first worksheet
xls.Workbooks.Add()
book = xls.ActiveWorkbook
sheet = book.ActiveSheet
'step through rows and columns and copy data to worksheet
Dim row As Integer = 2
Dim col As Integer = 1
'////////////////////////////////////////////////////////////////////////
Dim rowhead As Integer = 1
Dim colhead As Integer = 1
Dim columns As New List(Of String)
Dim columncount As Integer = LvCOCONFIRMATION.Columns.Count - 1
For i As Integer = 0 To columncount
sheet.Cells(rowhead, colhead) = LvCOCONFIRMATION.Columns(i).Text
colhead = colhead + 1
Next
'////////////////////////////////////////////////////////////////////////
For Each item As ListViewItem In LvCOCONFIRMATION.Items
For i As Integer = 0 To item.SubItems.Count - 1
sheet.Cells(row, col) = item.SubItems(i).Text
col = col + 1
Next
row += 1
col = 1
Next
'save the workbook and clean up
book.SaveAs(SaveFileDialog1.FileName)
xls.Workbooks.Close()
xls.Quit()
releaseObject(sheet)
releaseObject(book)
releaseObject(xls)
I'm Using following code to export my listview to Excelsheet but the problem is i have multiple listviews which i have to export in different sheets in same excel file . . . . .
Dim flnameSaveAs As String = System.IO.Path.GetFileName(Main.spath1)
'Save Files name
Dim extension As String
extension = Path.GetExtension(Main.spath1)
Dim file As String = System.IO.Path.GetFileName(Main.spath1)
Dim FinenameA As String = System.IO.Path.GetDirectoryName(Main.spath1)
Dim savnames As String
savnames = file.Substring(0, Len(file) - Len(extension))
Dim ExportSheet As String
ExportSheet = deskPath + "\Cel_ID_TimeLine.txt"
Dim lvi As ListViewItem
Dim sb As New System.Text.StringBuilder
Dim sbhd As New System.Text.StringBuilder
Dim columns As Integer = lvCidTimeLine.Columns.Count
For ixhd As Integer = 0 To lvCidTimeLine.Columns.Count - 1
sbhd.Append(lvCidTimeLine.Columns(ixhd).Text)
sbhd.Append(vbTab)
Next
sb.Append(vbCrLf)
For Each lvi In lvCidTimeLine.Items
For ix As Integer = 0 To lvi.SubItems.Count - 1
sb.Append(lvi.SubItems(ix).Text)
If ix < lvi.SubItems.Count - 1 Then
sb.Append(vbTab)
Else
sb.Append(vbCrLf)
End If
Next
Next
Dim sw As New StreamWriter(ExportSheet)
sw.Write(sbhd.ToString)
sw.Write(sb.ToString)
sw.Close()
Dim oExcel As Excel.Application
' Create the spreadsheet
oExcel = CreateObject("Excel.Application")
oExcel.Workbooks.OpenText(ExportSheet, , , , -4142, , True)
oExcel.Cells.EntireColumn.AutoFit()
oExcel.ActiveWorkbook.SaveAs(savpath + "\" + savnames + ".xls", -4143)
oExcel.Quit()
oExcel = Nothing
So do you have any idea how to add another sheet and export another listview to it ??
Try This Code Instead
Try
Dim objExcel As New Excel.Application
Dim bkWorkBook As Excel.Workbook
Dim shWorkSheet As Excel.Worksheet
Dim shWorkSheet1 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 lv1.Columns.Count - 1
shWorkSheet.Cells(1, i + 1) = lv1.Columns(i).Text
Next
For i = 0 To lv1.Items.Count - 1
For j = 0 To lv1.Items(i).SubItems.Count - 1
shWorkSheet.Cells(i + 2, j + 1) = lv1.Items(i).SubItems(j).Text
Next
Next
shWorkSheet1 = bkWorkBook.Worksheets.Add(, shWorkSheet, , )
For i = 0 To lv2.Columns.Count - 1
shWorkSheet1.Cells(1, i + 1) = lv2.Columns(i).Text
Next
For i = 0 To lv2.Items.Count - 1
For j = 0 To lv2.Items(i).SubItems.Count - 1
shWorkSheet1.Cells(i + 2, j + 1) = lv2.Items(i).SubItems(j).Text
Next
Next
objExcel.Visible = False
objExcel.Application.DisplayAlerts = False
objExcel.ActiveWorkbook.SaveAs(savpath + "\" + savnames + "_1" + ".xls", -4143)
objExcel.Quit()
objExcel = Nothing
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Dim proc As System.Diagnostics.Process
For Each proc In System.Diagnostics.Process.GetProcessesByName("EXCEL")
proc.Kill()
Next
You need to ADD to the sheets collection. Interop Excel Sheets