Range selection in excel sheet using vb.net - vb.net

This is my code:
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "Excel files (*.xls)|*.xls"
saveFileDialog1.Title = "Save File"
saveFileDialog1.RestoreDirectory = True
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
Try
Dim ExcelApp As New Microsoft.Office.Interop.Excel.Application()
ExcelApp.Application.Workbooks.Add(Type.Missing)
ExcelApp.Cells.HorizontalAlignment = XlHAlign.xlHAlignLeft
' Change properties of the Workbook
ExcelApp.Columns.ColumnWidth = 15
' Storing header part in Excel
For i As Integer = 1 To DataGridView1.Columns.Count
ExcelApp.Cells(1, i) = DataGridView1.Columns(i - 1).HeaderText
Next
' Storing Each row and column value to excel sheet
For i As Integer = 0 To DataGridView1.Rows.Count - 2
For j As Integer = 0 To DataGridView1.Columns.Count - 1
ExcelApp.Cells(i + 2, j + 1) = DataGridView1.Rows(i).Cells(j).Value.ToString()
Next
Next
Dim Destinationpath As String = saveFileDialog1.FileName
ExcelApp.ActiveWorkbook.SaveAs(Destinationpath)
ExcelApp.ActiveWorkbook.Saved = True
ExcelApp.Quit()
MsgBox("Record exported successfully", MsgBoxStyle.Information)
Catch
MsgBox("It is being used by another process.Please close it and retry.", MsgBoxStyle.Critical)
End Try
Else
End If
Now how do I select the range using the above code which is populated in an excel sheet.

Found the answer:
Dim lastrow As Range = ExcelApp.Rows.End(XlDirection.xlDown)
Dim findme As Range = ExcelApp.Range("A1:E" & lastrow.Row)
MsgBox("A1:E" & lastrow.Row)

Related

vb.net Export Datagridview to excel template

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)

Save generated excel file with dialog

I'm generating an xls file from a datatable on a button click. Right now the path to save the file is hardcoded in the function to generate the file:
Function CreateExcelFile(xlFile As String) As Boolean
Try
Dim xlRow As Integer = 2
Dim xlApp As New Microsoft.Office.Interop.Excel.Application
Dim xlWB = xlApp.Workbooks.Add
Dim xlWS = xlApp.Worksheets.Add
Dim intStr As Integer = 0
Dim NewFile As String = ""
Dim strCaption As String = "PSLF Driver Files Records"
xlFile = Replace(xlFile, "Return Files", "Reports")
xlFile = Replace(xlFile, "txt", "xlsx")
xlFile = Replace(xlFile, "_", " ")
intStr = InStr(xlFile, "Reports")
xlApp.IgnoreRemoteRequests = True
xlWS = xlWB.Worksheets(xlApp.ActiveSheet.Name)
xlApp.DisplayAlerts = False
xlApp.Sheets.Add()
Dim xlTopRow As Integer = 2 'First Row to enter data
xlApp.Sheets.Add()
xlApp.Sheets(1).Name = strCaption
xlApp.Sheets(1).Select()
'Store datatable in 2-dimensional array
Dim arrExcel(frm_Records.BindingSource1.DataSource.Rows.Count, frm_Records.BindingSource1.DataSource.Columns.Count - 1) As String
'Write header row to array
arrExcel(0, 0) = "SSN"
arrExcel(0, 1) = "CREATE_DATE"
arrExcel(0, 2) = "SERVICER_CODE"
arrExcel(0, 3) = "STATUS"
arrExcel(0, 4) = "DRIVER_FILE_OUT"
arrExcel(0, 5) = "LAST_UPDATE_USER"
arrExcel(0, 6) = "LAST_UPDATE_DATE"
arrExcel(0, 7) = "CREATE_USER"
'Copy rows from datatable to array
xlRow = 1
For Each dr As DataRow In frm_Records.BindingSource1.DataSource.Rows
arrExcel(xlRow, 0) = dr("SSN")
arrExcel(xlRow, 1) = dr("CREATE_DATE")
arrExcel(xlRow, 2) = dr("SERVICER_CODE")
arrExcel(xlRow, 3) = dr("STATUS")
If IsDBNull(dr("DRIVER_FILE_OUT")) Then
arrExcel(xlRow, 4) = ""
Else
arrExcel(xlRow, 4) = dr("DRIVER_FILE_OUT")
End If
arrExcel(xlRow, 5) = dr("LAST_UPDATE_USER")
arrExcel(xlRow, 6) = dr("LAST_UPDATE_DATE")
arrExcel(xlRow, 7) = dr("CREATE_USER")
xlRow += 1
Next
'Set up range
Dim c1 As Microsoft.Office.Interop.Excel.Range = xlApp.Range("A1") 'Top left of data
Dim c2 As Microsoft.Office.Interop.Excel.Range = xlApp.Range("T" & frm_Records.BindingSource1.DataSource.Rows.Count - 1 + xlTopRow) 'Bottom right of data
Dim xlRange As Microsoft.Office.Interop.Excel.Range = xlApp.Range(c1, c2)
xlRange.Value = arrExcel 'Write array to range in Excel
xlWB.ActiveSheet.Range("A:T").Columns.Autofit()
xlWB.ActiveSheet.Range("A1:T1").Interior.Color = RGB(255, 255, 153)
xlWB.ActiveSheet.Range("A1:T1").Font.Bold = True
With xlApp.ActiveWindow
.SplitColumn = 0
.SplitRow = 1
End With
xlApp.ActiveWindow.FreezePanes = True
Dim strSheet As String
For Each Sht In xlWB.Worksheets
If Sht.name Like "*Sheet*" Then
strSheet = Sht.name
xlApp.Sheets(strSheet).delete()
End If
Next
xlApp.IgnoreRemoteRequests = False
xlWB.SaveAs(xlFile)
xlWB.Close()
Dim xlHWND As Integer = xlApp.Hwnd
'this will have the process ID after call to GetWindowThreadProcessId
Dim ProcIdXL As Integer = 0
'get the process ID
GetWindowThreadProcessId(xlHWND, ProcIdXL)
'get the process
Dim xproc As Process = Process.GetProcessById(ProcIdXL)
xlApp.Quit()
'Release
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp)
'set to nothing
xlApp = Nothing
'kill it with glee
If Not xproc.HasExited Then
xproc.Kill()
End If
Catch ex As Exception
WP.WAPC_RUNSCRIPT_ERROR_FILE(WP.argScriptName, "Error Writing to Excel Report: " & ex.Message)
Return False
End Try
Return True
End Function
<DllImport("user32.dll", SetLastError:=True)> _
Private Function GetWindowThreadProcessId(ByVal hwnd As IntPtr, _
ByRef lpdwProcessId As Integer) As Integer
End Function
#End Region
What I want to do is upon completion of the creation of the Excel file, I want to give the user the option of where to save the newly created file. I'm new at
Winforms and am not sure how to do this.
What is the best way to enable the user to choose where to saved the file?
Update:
Working code after #Claudius' answer.
Private Sub btnRecExport_Click(sender As Object, e As EventArgs) Handles
btnRecExport.Click
Dim file As String = "I:\PSLFRecords.xlsx"
CreateExcelFile(file)
Dim sfdRecords As New SaveFileDialog()
sfdRecords.Filter = "Excel File|*.xls"
sfdRecords.Title = "Save PSLF Driver Records"
sfdRecords.ShowDialog()
If sfdRecords.FileName <> "" Then
xlWB.SaveAs(sfdRecords.FileName)
fs.Close()
End If
End Sub
From MSDN edited to your needs:
Private Sub Button2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button2.Click
' Displays a SaveFileDialog so the user can save the Image
' assigned to Button2.
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "Excel File|*.xls
saveFileDialog1.Title = "Save an Excel File"
saveFileDialog1.ShowDialog()
' If the file name is not an empty string open it for saving.
If saveFileDialog1.FileName <> "" Then
xlWB.SaveAs(saveFileDialog1.FileName)
fs.Close()
End If
End Sub
All you'd actually need is just a new instance of the FolderBrowserDialog Class, that will return to you the path the user selected. All the information you need is already present in the documentation.

Delete Blank Rows after exporting from Datagridview to excel

Good day Guys. This Code enables me to export datagridview to excel excluding invisible rows using button.
The problems is. this code leaves a blank rows in my excel everytime datagridview.row is invisible.
Can someone help me how to delete a blank row using excel-vba macro? after the "NEXT I" line?
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim xlapp As Microsoft.Office.Interop.Excel.Application
Dim misvalue As Object = System.Reflection.Missing.Value
Dim rowsTotal, colsTotal As Short
Dim I, J As Short
xlapp = New Microsoft.Office.Interop.Excel.Application
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor
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()
Dim curCol As Short = 0
For iC = 0 To colsTotal
If DataGridView1.Columns(iC).Visible Then
.Cells(1, curCol + 1).Value = DataGridView1.Columns(iC).HeaderText
curCol += 1
End If
Next
For I = 0 To rowsTotal
curCol = 0
For J = 0 To colsTotal
DataGridView1.Rows(I).Visible = True
.Cells(I + 2, curCol + 1).value = DataGridView1.Rows(I).Cells(J).Value
curCol += 1
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()
excelWorksheet.SaveAs("E:\vbexcel.xlsx")
xlapp.Quit()
xlapp.Quit()
releaseObject(xlapp)
releaseObject(excelBook)
releaseObject(excelWorksheet)
End With
MsgBox("You can find the file E:\vbexcel.xlsx")
Dim res As MsgBoxResult
res = MsgBox("Process completed, Would you like to open the file?", MsgBoxStyle.YesNo)
If (res = MsgBoxResult.Yes) Then
Process.Start("E:\vbexcel.xlsx")
End If
End Sub
You are using same variables to get next cell of DataGridView and Excel Sheet, that is why it is inserting blank rows for invisible rows/columns
' variables to access grid cell
Dim gvRow as Integer = 0, gvCol as Integer = 0
' variables to access excel cell
Dim exRow as Integer = 0, exCol as Integer = 0
For gvRow = 0 To DataGridView1.RowCount - 1
exCol = 0
If DataGridView1.Rows(gvRow).Visible Then
For gvCol = 0 To DataGridView1.Columns.Count - 1
If DataGridView1.Columns(gvCol).Visible Then
.Cells(exRow, exCol).value = DataGridView1.Rows(gvRow).Cells(gvCol).Value
exCol += 1
End If
Next gvCol
exRow += 1
End If
Next gvRow

export datagridview header column to excel vb 2012

i'm using visual studio 2012 and microsoft SQL server 2012 to export datagridview to excel using this coding:
Public Class Export
Private Sub Export_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DataGridView1.AllowUserToAddRows = False
ClassKoneksi.namadatabase = "KPIRWAN"
Dim dssiswa As New DataSet
Dim sql As String
sql = "select*from Siswa order by NIS ASC"
dssiswa = ClassSiswa.displayData(ClassSiswa.opencon, sql, "DataSiswa")
DataGridView1.DataSource = dssiswa
DataGridView1.DataMember = "DataSiswa"
DataGridView1.ReadOnly = True
ClassSiswa.closecon()
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
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ExportExcel()
End Sub
Private Sub ExportExcel()
Dim xlApp As Microsoft.Office.Interop.Excel.Application
Dim xlBook As Microsoft.Office.Interop.Excel.Workbook
Dim xlSheet As Microsoft.Office.Interop.Excel.Worksheet
Dim oValue As Object = System.Reflection.Missing.Value
Dim sPath As String = String.Empty
Dim dlgSave As New SaveFileDialog
dlgSave.DefaultExt = "xls"
dlgSave.Filter = "Microsoft Excel|*.xls"
dlgSave.InitialDirectory = Application.StartupPath
If dlgSave.ShowDialog = Windows.Forms.DialogResult.OK Then
Try
xlApp = New Microsoft.Office.Interop.Excel.Application
xlBook = xlApp.Workbooks.Add(oValue)
xlSheet = xlBook.Worksheets("sheet1")
Dim xlRow As Long = 2
Dim xlCol As Short = 1
For k As Integer = 0 To DataGridView1.ColumnCount - 1
xlSheet.Cells(1, xlCol) = DataGridView1(k, 0).Value
xlCol += 1
Next
For k As Integer = 0 To DataGridView1.ColumnCount - 1
xlSheet.Cells(2, xlCol) = DataGridView1(k, 0).Value
xlCol += 1
Next
For i As Integer = 0 To DataGridView1.RowCount - 1
xlCol = 1
For k As Integer = 0 To DataGridView1.ColumnCount - 1
xlSheet.Cells(xlRow, xlCol) = DataGridView1(k, i).Value
xlCol += 1
Next
xlRow += 1
Next
xlSheet.Columns.AutoFit()
Dim sFileName As String = Replace(dlgSave.FileName, ".xlsx", "xlx")
xlSheet.SaveAs(sFileName)
xlBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlBook)
releaseObject(xlSheet)
MsgBox("Data successfully exported.", MsgBoxStyle.Information, "PRMS/SOB Date Tagging")
Catch
MsgBox(ErrorToString)
Finally
End Try
End If
End Sub
End Class
it work perfectly fine except when i exported the datagridview to excel the column header text in the datagridview is not exported to excel sheet only the gridview.
how do i make the coding to get the column header text to excel sheet?
I think you'll have to get the HeaderText from each column like this:
xlSheet.Cells(x,y).Value = DataGridView1.Columns(k).HeaderText
You would put this in your "k" loop. And then write it wherever you want in the file. x and y have to be the location where you write the header (maybe determined by k)
EDIT: writing the headers in first row of excel
For k As Integer = 0 To DataGridView1.ColumnCount - 1
xlSheet.Cells(1,k+1).Value = DataGridView1.Columns(k).HeaderText
Next

export the listview items to excel sheet with listview header

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)