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

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.

Related

Read the count of filters in ms project and populate in Excel

I want to create a table in excel which show the count of rows when a filter is applied in ms project. The table should have the filter names as column headers and count of the rows filtered in each column under the header like this
filter 1 filter 2 filter 3
0 10 3
I can write basic macros in excel and ms project.
I use the below to count rows.
applyfilter = fitler1
select all
countFitleredRows = ActiveSelection.Tasks.Count
But how do I read the countFitleredRows for mulitple fitlers and create a table in excel.
If some one has a working macro that would be great.
otherwise I want to know the logic of writing the values in the form of a table in excel.
regards,
Waqas.
Waqas Mahmood,
Although I don't have a macro that does exactly what you want, the following macro will provide a basic structure for creating what you want.
John
Sub BaseCalendarExceptions()
'This macro exports the exceptions for all base calendars in a given Project file
'(modified version of the CalendarExceptions macro published previously in this forum)
' Written by John - Project 2/8/16
Dim MyXL As Object
Set MyXL = CreateObject("Excel.Application")
Dim i As Integer, j As Integer
Dim BC As Calendar
Dim E As Exception
Dim xlRng As Range
'open Excel, define workbook, and set column headers
MyXL.Workbooks.Add
MyXL.Visible = True
MyXL.ActiveWorkbook.Worksheets.Add.Name = "BaseCal Exc Report"
MyXL.ActiveWorkbook.Worksheets("BaseCal Exc Report").Activate
Set xlRng = MyXL.ActiveSheet.Range("A1")
xlRng.Range("A1") = "Proj Cal Holidays"
xlRng.Range("B1") = "Base Calendar"
xlRng.Range("C1") = "Start Date"
xlRng.Range("D1") = "Finish Date"
'Gather and export Project calendar exceptions
j = 0
For Each BC In ActiveProject.BaseCalendars
i = 2 + j
If BC.Exceptions.Count > 0 Then
For Each E In BC.Exceptions
xlRng.Range("A" & i) = E.Name
xlRng.Range("B" & i) = BC.Name
xlRng.Range("C" & i) = E.Start
xlRng.Range("D" & i) = E.Finish
i = i + 1
Next E
End If
j = i
Next BC
MyXL.ActiveWorkbook.Worksheets("BaseCal Exc Report").Columns("A:D").AutoFit
End Sub
The routine creates an Excel file and loops through all the task filters, creating a column for each filter with the name (row 1) and # tasks (row 2).
Sub FilteredTaskCountReport()
Dim appXl As Object
Set appXl = CreateObject("Excel.Application")
appXl.Visible = True
Dim wbk As Object
Set wbk = appXl.Workbooks.Add
Dim wst As Object
Set wst = wbk.Worksheets(1)
Dim CurrentTaskUID As Long
CurrentTaskUID = ActiveCell.Task.UniqueID
OutlineShowAllTasks
Dim f As Variant
Dim c As Integer
c = 0
For Each f In ActiveProject.TaskFilterList
FilterApply f
SelectAll
c = c + 1
wst.Cells(1, c) = f
On Error Resume Next
wst.Cells(2, c) = ActiveSelection.Tasks.Count
If Err.Number <> 0 Then
wst.Cells(2, c) = 0
End If
On Error GoTo 0
Next f
FilterApply "&All Tasks"
Find "Unique ID", "equals", CurrentTaskUID
Set appXl = Nothing
End Sub

Export data from listview to excel vb.net

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!

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

Exporting multiple datagridviews to different tabs of excelsheet

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

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