Help me convert list view entries to excel then pdf. Or simply help me convert listview entries to PDF. l am using visual basic 2012. This is the code that l have:
Private Sub ToolStripButton2_Click(sender As Object, e As EventArgs) Handles ToolStripButton2.Click
'Export the listview to an Excel spreadsheet
SaveFileDialog1.Title = "Save Excel File"
SaveFileDialog1.Filter = "Excel files (*.xls)|*.xls|Excel Files (*.pdf)|*.pdf"
SaveFileDialog1.Filter = "PDF files (*.pdf)|*.pdf"
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 CustomerView.Items
' lblID.Text = SalesView.SelectedItems(0).Text
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
Related
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.
My program has output data to the Listview control. Now I would like to export the data to a text file/excel and then load it back to the listview control when I need to. I know how to do both these tasks using the listbox control but listview is new to me. I've been researching and playing around with code for hours but I keep getting one error or the other. Kindly find the latest version of my code to export data below. Also, if you could provide code to import, that would be super.
'Export the listview to an Excel spreadsheet
Dim SaveFileDialog1 As New SaveFileDialog
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
Dim placeholder As String
'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 lstViewUsers.Items
For i As Integer = 0 To item.SubItems.Count - 1
placeholder = sheet.Cells(row, col) = item.SubItems(i).Text
col = col + 1
Next
row += 1
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
I'm a newbie to visual studio.
I want to export different datagridviews from multiple forms to an excel workbook as different sheets on the same workbook based on whether it is checked in checkedlist box.
Basically I am doing a daily checklist for our school on location basis where the user can export checklist floor wise on the corresponding form of each floor, but also can export a multiple sheet workbook containing diff floors as per its checked in checklistbox, any help please? I am stuck at checkedlistbox. currently i am doing as below: but gives me an exception at the second sheet.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
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
Me.Cursor = Cursors.WaitCursor
Dim sheetnumber As Integer = 1
If CheckedListBox1.GetItemChecked(0) = True Then
worksheet = workbook.Sheets(sheetnumber)
sheetnumber = sheetnumber + 1
worksheet.Name = "Anim_Check List_"
Dim cellRowIndex As Integer = 1
Dim cellColumnIndex As Integer = 1
For i As Integer = 0 To Form7.DataGridView1.Rows.Count - 1
For j As Integer = 0 To Form7.DataGridView1.Columns.Count - 1
If cellRowIndex = 1 Then
worksheet.Cells(cellRowIndex, cellColumnIndex) = Form7.DataGridView1.Columns(j).HeaderText
Else
worksheet.Cells(cellRowIndex, cellColumnIndex) = Form7.DataGridView1.Rows(i).Cells(j).Value.ToString()
End If
cellColumnIndex += 1
Next
cellColumnIndex = 1
cellRowIndex += 1
Next
End If
If CheckedListBox1.GetItemChecked(1) = True Then
workbook.Worksheets.Add(sheetnumber)
excel.Worksheets(sheetnumber).activate
sheetnumber = sheetnumber + 1
worksheet.Name = "Edits 1-5_"
Dim cellRowIndex As Integer = 1
Dim cellColumnIndex As Integer = 1
For i As Integer = 0 To Form8.DataGridView1.Rows.Count - 1
For j As Integer = 0 To Form8.DataGridView1.Columns.Count - 1
If cellRowIndex = 1 Then
worksheet.Cells(cellRowIndex, cellColumnIndex) = Form8.DataGridView1.Columns(j).HeaderText
Else
worksheet.Cells(cellRowIndex, cellColumnIndex) = Form8.DataGridView1.Rows(i).Cells(j).Value.ToString()
End If
cellColumnIndex += 1
Next
cellColumnIndex = 1
cellRowIndex += 1
Next
End If
Dim saveDialog As New SaveFileDialog()
saveDialog.FileName = workbook.Name
saveDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*"
saveDialog.FilterIndex = 1
If saveDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
workbook.SaveAs(saveDialog.FileName)
MessageBox.Show("Export Successful")
End If
End Sub
It is very difficult to understand what you are trying to do. From what I can decipher, there appears to be three (3) different WindowsForms open. The main active form has a Button and a CheckedListBox. The two other forms (Form7, Form8) each have a DataGridView with some data.
I assume that the CheckListBox allows the user to select which form to use when exporting to Excel. Example, if the user checks the first option, then clicks the button, then the DataGridView on Form7 will be exported to the Excel workbook. If the second option is checked then Form8’s DataGridView will be exported to the same workbook.
I hope I have this correct. To help, I would recommend you break the problem down into smaller pieces. Example, looking at the code in both “if” statements that check for a checked state in the checked list box… it is clear they are doing the same thing. The only difference is the DataGridView and the name of the worksheet.
It looks like a method, that took a workbook to add the sheet to, a DataGridView to export and finally a string for the worksheet name… might come in handy.
Private Sub AddGridToWorkbook(workbook As Workbook, dgv As DataGridView, sheetName As String)
This method would add a new worksheet to the given workbook using the given sheetName as the name for the new worksheet. Lastly the method would loop through the given DataGridView and export the values to the new worksheet.
The current posted code is trying to print the header row inside the loop through the grids rows. This will miss the first row of data. The header row for the new excel worksheet needs to be exported separately and outside the loop through the grids rows.
Lastly, I am curious what Form7 and Form8 are… If these are WindowsForm “Classes”… then the statement:…
worksheet.Cells(cellRowIndex, cellColumnIndex) = Form7.DataGridView1.Rows(i).Cells(j).Value.ToString()
This will not work as you expect… Form7 is a “Class” and you are using it like an instantiated object.
In my example below, I have two WindowsForms “Classes” called “Form7” and “Form8”. When the main form loads, I instantiate and show these two forms. Example: create the global variable forms.
Dim form7 As Form7 = New Form7()
Dim form8 As Form8 = New Form8()
Then show the forms on load.
form7.Show()
form8.Show()
Now the previous line of code will work using the instantiated “Form7” object named form7.
worksheet.Cells(cellRowIndex, cellColumnIndex) = form7.DataGridView1.Rows(i).Cells(j).Value.ToString()
Revised code to export the grids
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
excel.Visible = True
Dim workbook = excel.Workbooks.Add()
If CheckedListBox1.GetItemChecked(0) = True Then
AddGridToWorkbook(workbook, form7.DataGridView1, "Anim_Check List_")
End If
If CheckedListBox1.GetItemChecked(1) = True Then
AddGridToWorkbook(workbook, form8.DataGridView1, "Edits 1-5_")
End If
Dim saveDialog As New SaveFileDialog()
saveDialog.FileName = workbook.Name
saveDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*"
saveDialog.FilterIndex = 1
If saveDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
workbook.SaveAs(saveDialog.FileName)
MessageBox.Show("Export Successful")
End If
End Sub
Private Sub AddGridToWorkbook(workbook As Workbook, dgv As DataGridView, sheetName As String)
Try
Dim worksheet As Worksheet = workbook.Worksheets.Add()
worksheet.Name = sheetName
AddHeaderRow(worksheet, dgv)
For row As Integer = 0 To dgv.Rows.Count - 1
For col As Integer = 0 To dgv.Columns.Count - 1
If dgv.Rows(row).Cells(col).Value IsNot Nothing Then
worksheet.Cells(row + 2, col + 1) = dgv.Rows(row).Cells(col).Value.ToString()
End If
Next
Next
Catch ex As Exception
MessageBox.Show("Ex: " + ex.Message)
End Try
End Sub
Private Sub AddHeaderRow(worksheet As Worksheet, dgv As DataGridView)
For col As Integer = 0 To dgv.Columns.Count - 1
worksheet.Cells(1, col + 1) = dgv.Columns(col).HeaderText
Next
End Sub
Hope this helps
I'm in the middle of writing a script that populates an excel spreadsheet with data from an MS Project file. I would like the script to recognize the title name of the MS Project columns as I have a number of custom columns with different names (custom number fields are populated with different names)
The code below was my attempt, but i'm getting an error when it comes to writing the value of the task column title to the sheet, am I doing something wrong here?
Sub PopulateSheet()
Dim Proj As MSProject.Application
Dim NewProj As MSProject.Project
Dim t As MSProject.Task
Dim xl as workbook
Dim s as worksheet
Dim Newsheet as worksheet
Set Xl = ThisWorkbook
BookNam = Xl.Name
Set Newsheet = Xl.Worksheets.Add
'Code to find and open project files
Set Proj = New MSProject.Application
MsgBox ("Please Select MS Project File for Quality Checking")
'Select Project File
FileOpenType = Application.GetOpenFilename( _
FileFilter:="MS Project Files (*.mpp), *.mpp", _
Title:="Select MS Project file", _
MultiSelect:=False)
'Detect if File is selected, if not then stop code
If FileOpenType = False Then
MsgBox ("You Havent Selected a File")
Exit Sub
End If
'Write the FileOpenType variant to two separate strings
NewProjFilePath = Left$(FileOpenType, InStrRev(FileOpenType, "\"))
NewProjFileName = Mid$(FileOpenType, InStrRev(FileOpenType, "\") + 1)
Newsheet.Name = NewProjFileName
Set s = Newsheet
'Populate spreadsheet header row with column titles from MS Project
s.Range("A1").Value = t.Number1 ***<-- Error '91' - Object variable or With block variable not set***
End Sub
Here is generic code that loops through the fields in the active task table and prints out the field headings as displayed in the table.
Sub GetTaskTableHeaders()
Dim t As Table
Set t = ActiveProject.TaskTables(ActiveProject.CurrentTable)
Dim f As TableField
For Each f In t.TableFields
If f.Field > 0 Then
Dim header As String
Dim custom As String
custom = Application.CustomFieldGetName(f.Field)
If Len(f.Title) > 0 Then
header = f.Title
ElseIf Len(custom) > 0 Then
header = custom
Else
header = Application.FieldConstantToFieldName(f.Field)
End If
Debug.Print "Field " & f.Index, header
End If
Next f
End Sub
Note that fields can be customized at the project level to be given a different title, or they can be customized at the table level. This code looks for both customizations and if neither is found, the field name is used.
Try the code below, explanation inside the code's comments:
Option Explicit
Sub PopulateSheet()
Dim Proj As MSProject.Application
Dim NewProj As MSProject.Project
Dim PjTableField As MSProject.TableField ' New Object
Dim PjTaskTable As MSProject.Table ' New Object
Dim t As MSProject.task
Dim xl As Workbook
Dim s As Worksheet
Dim Newsheet As Worksheet
Dim BookName As String
Dim FileOpenType
Dim NewProjFilePath As String, NewProjFileName As String
Set xl = ThisWorkbook
BookName = xl.Name
Set Newsheet = xl.Worksheets.Add
'Code to find and open project files
Set Proj = New MSProject.Application
MsgBox ("Please Select MS Project File for Quality Checking")
'Select Project File
FileOpenType = Application.GetOpenFilename( _
FileFilter:="MS Project Files (*.mpp), *.mpp", _
Title:="Select MS Project file", _
MultiSelect:=False)
'Detect if File is selected, if not then stop code
If FileOpenType = False Then
MsgBox ("You Havent Selected a File")
Exit Sub
End If
'Write the FileOpenType variant to two separate strings
NewProjFilePath = Left$(FileOpenType, InStrRev(FileOpenType, "\"))
NewProjFileName = Mid$(FileOpenType, InStrRev(FileOpenType, "\") + 1)
Newsheet.Name = NewProjFileName
Set s = Newsheet
' Open MS-Project File
Proj.FileOpen NewProjFilePath & NewProjFileName
Set NewProj = Proj.ActiveProject
' ===== New code Section =====
' set the Table object
Set PjTaskTable = NewProj.TaskTables(NewProj.CurrentTable)
' loop through all tablefields in table
For Each PjTableField In PjTaskTable.TableFields
If PjTableField.Field = pjTaskNumber1 Then ' check if currect field numeric value equals the numeric value of "Number1"
'Populate spreadsheet header row with column titles from MS Project
s.Range("A1").Value = PjTableField.Title ' populate "A1" with the field's title and
End If
Next PjTableField
End Sub