System.Argument Exception Error in vb.net, My Code is below - vb.net

here is my code
For Each Cel As DataGridViewCell In GridRow.Cells
If Cel.Value IsNot Nothing Then
e.Graphics.DrawString(Cel.Value.ToString(),
Cel.InheritedStyle.Font,
New SolidBrush(Cel.InheritedStyle.ForeColor),
New RectangleF(CInt(arrColumnLefts(iCount)),
CSng(iTopMargin),
CInt(arrColumnWidths(iCount)),
CSng(iCellHeight)),
strFormat)
End If
e.Graphics.DrawRectangle(Pens.Black,
New Rectangle(CInt(arrColumnLefts(iCount)),
iTopMargin,
CInt(arrColumnWidths(iCount)),
iCellHeight))
iCount += 1
Next

Related

OpenXML generate Report from Excel Model

I need your help to understand how to populate a new excel by copying it from a template using Openxml.
I would like to keep the formatting of the columns deriving from the template;
Public Sub ExportDTfromModel(ByVal pathmodel As String, ByVal pathdestination As String, ByVal dt As System.Data.DataTable)
u.SegnalaSoloLog("Inizio Metodo: " & MethodBase.GetCurrentMethod().Name.ToString())
Try
If System.IO.File.Exists(pathmodel) Then
System.IO.File.Copy(pathmodel, pathdestination)
Using spreadSheet As SpreadsheetDocument = SpreadsheetDocument.Open(pathdestination, True)
Dim WorksheetPart As WorksheetPart = GetWorksheetPartByName(spreadSheet, dt.TableName)
If (Not WorksheetPart Is Nothing) Then
Dim worksheet As Worksheet = New Worksheet()
WorksheetPart.Worksheet = worksheet
Dim sheetData As SheetData = New SheetData()
Dim headerRow As DocumentFormat.OpenXml.Spreadsheet.Row = New DocumentFormat.OpenXml.Spreadsheet.Row()
Dim columns As List(Of String) = New List(Of String)()
For Each column As DataColumn In dt.Columns
columns.Add(column.ColumnName)
Dim cell As DocumentFormat.OpenXml.Spreadsheet.Cell = New DocumentFormat.OpenXml.Spreadsheet.Cell()
cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String
cell.CellValue = New DocumentFormat.OpenXml.Spreadsheet.CellValue(column.ColumnName)
' Dim headerCell As Cell = createTextCell(
'ds.Columns.IndexOf(column) + 1,
'1,
'column.ColumnName)
headerRow.AppendChild(cell)
Next
sheetData.AppendChild(headerRow)
'For i As Integer = 0 To ds.Rows.Count - 1
' Dim contentRow As DataRow
' contentRow = ds.Rows(i)
' sheetData.AppendChild(createContentRow(contentRow, i + 2))
'Next
For Each dsrow As DataRow In dt.Rows
Dim newRow As DocumentFormat.OpenXml.Spreadsheet.Row = New DocumentFormat.OpenXml.Spreadsheet.Row()
For Each col As String In columns
Dim cell As DocumentFormat.OpenXml.Spreadsheet.Cell = New DocumentFormat.OpenXml.Spreadsheet.Cell()
' cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String
Select Case dsrow(col).GetType().ToString
Case "System.DateTime"
cell.CellValue = New DocumentFormat.OpenXml.Spreadsheet.CellValue(Convert.ToDateTime(dsrow(col)))
cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.Date
Case "System.Decimal"
cell.CellValue = New DocumentFormat.OpenXml.Spreadsheet.CellValue(Convert.ToDecimal(dsrow(col)))
cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.Number
Case "System.String"
cell.CellValue = New DocumentFormat.OpenXml.Spreadsheet.CellValue(dsrow(col).ToString)
cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String
End Select
newRow.AppendChild(cell)
Next
sheetData.AppendChild(newRow)
Next
End If
spreadSheet.WorkbookPart.Workbook.Save()
GC.Collect()
u.SegnalaSoloLog("File Excel Generato in : " & pathdestination)
End Using
Else
u.SegnalaSoloLog("Errore Modello non trovato, impossibile esportare il file")
End If
Catch ex As Exception
u.SegnalaSoloLog("Errore in Export from model: " & ex.Message)
End Try
End Sub

Export DataGridView to Excel using VB 2013

Im fairly new to VB 2013. Any advice and help is greatly appreciated.
I have a datagridview that I want to export to Excel. I have the code working that does the export, but it doesnt show the header names. I need to edit the code to bring the header names over as well.
Additionally, I want to drop the first column from the export.
Example of my gridview code:
Private Sub Button2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button2.Click
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Integer
Dim j As Integer
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("Sheet1")
'Export Header Names Start
Dim columnsCount As Integer = DataGridView1.Columns.Count
For Each column In DataGridView1.Columns
xlWorkSheet.Cells(1, column.Index + 1).Value = column.name
Next
' 'Export Header Name End
For i = 0 To DataGridView1.RowCount - 2
For j = 0 To DataGridView1.ColumnCount - 1
xlWorkSheet.Cells(i + 1, j + 1) = _
DataGridView1(j, i).Value.ToString()
Next
Next
If System.IO.File.Exists("C:\test\export.xlsx") Then
System.IO.File.Delete("C:\test\export.xlsx")
End If
xlWorkSheet.SaveAs("C:\test\export.xlsx")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
MsgBox("You can find the file here C:\test")
End Sub
DataGridview Output:
For many years i,m using this function.
Public Sub grid_ToExcel_Export(ByVal FileName As String, ByVal Data_GridView As DataGridView)
Dim sb As New System.Text.StringBuilder
Try
Dim intColumn, intColumnValue As Integer
Dim row As DataGridViewRow
For intColumn = 0 To Data_GridView.Columns.Count - 1
sb.Append(Data_GridView.Columns(intColumn).HeaderText)
If intColumnValue <> Data_GridView.Columns.Count - 1 Then
sb.Append(vbTab)
End If
Next
sb.Append(vbCrLf)
For Each row In Data_GridView.Rows
For intColumnValue = 0 To Data_GridView.Columns.Count - 1
sb.Append(StrConv(IIf(IsDBNull(row.Cells(intColumnValue).Value), "", row.Cells(intColumnValue).Value), VbStrConv.None))
If intColumnValue <> Data_GridView.Columns.Count - 1 Then
sb.Append(vbTab)
End If
Next
sb.Append(vbCrLf)
Next
SaveExcel(FileName, sb)
Catch ex As Exception
Throw
Finally
Data_GridView = Nothing
sb = Nothing
End Try
End Sub
Private Sub SaveExcel(ByVal fpath As String, ByVal sb As System.Text.StringBuilder)
Dim fsFile As New FileStream(fpath, FileMode.Create, FileAccess.Write)
Dim strWriter As New StreamWriter(fsFile, System.Text.Encoding.Unicode)
Try
With strWriter
.BaseStream.Seek(0, SeekOrigin.End)
.WriteLine(sb)
.Close()
End With
Catch e As Exception
msg(e.ToString)
Finally
sb = Nothing
strWriter = Nothing
fsFile = Nothing
End Try
End Sub

Uploading file to datagridview

I have this program where I am trying to upload an excel file and will be shown in my datagridview but i having this error
Additional information: Could not find installable ISAM.
Im new to VB please help me
Here is my code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Con As System.Data.OleDb.OleDbConnection
Dim ds As System.Data.DataSet
Dim cmd As System.Data.OleDb.OleDbDataAdapter
Con = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source='c:\manpower.xlsx';Extended Properties=cc;")
cmd = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet2$]", Con)
ds = New System.Data.DataSet
cmd.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
Con.Close()
End Sub
Why are you using OLEDB connection in the first place? Why not sqlConnection?
If you can, use something like this:
Private Sub LoadFormData()
Dim cmdText as String
Dim ds as DataSet
cmdText = "SELECT ID, FName, SName, Title FROM PeopleTable;"
ds = GetQueryResults(cmdText)
Me.DataGridView1.DataSource = ds.Tables(0)
End Sub
Private Function GetQueryResults(cmdText As String)
Dim oConn As New SqlConnection
oConn.ConnectionString = "........." ' your connection string
Dim cmd As New SqlCommand(cmdText, oConn)
Dim ds As New DataSet()
Dim da As New SqlDataAdapter(cmd)
Try
oConn.Open()
da.Fill(ds)
oConn.Close()
Catch ex As Exception ' handle error any way you like
Dim errform As New SysErrScreen
errform.ErrText.Text = ex.Message & vbCrLf & vbCrLf & cmdText
errform.ShowDialog()
oConn.Close()
End Try
Return ds
End Function
You can easily import an Excel file into DataGridView, and export from DataGridView to Excel.
Imports Excel = Microsoft.Office.Interop.Excel
Imports System.Data.OleDb
'~~> Define your Excel Objects
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim xlApp As New Excel.Application
'Dim xlWorkBook As Excel.Workbook
'Dim xlWorkSheet As Excel.Worksheet
Dim strConn As String
Dim da As OleDbDataAdapter
Dim ds As New DataSet
Dim dao_dbE As dao.DBEngine
Dim dao_DB As DAO.Database
Dim strFirstSheetName As String
dao_dbE = New dao.DBEngine
dao_DB = dao_dbE.OpenDatabase("C:\your_path_here\Book1.xls", False, True, "Excel 8.0;")
strFirstSheetName = dao_DB.TableDefs(0).Name
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\your_path_here\Book1.xls;Extended Properties=""Excel 8.0;"""
da = New OleDbDataAdapter("SELECT * FROM [" & _
strFirstSheetName & "]", strConn)
da.TableMappings.Add("Table", "Excel")
da.Fill(ds)
DataGridView1.DataSource = ds.Tables(0).DefaultView
da.Dispose()
dao_DB.Close()
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
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
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 - 1
For j = 0 To colsTotal - 1
.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("Export Excel Error " & ex.Message)
Finally
'RELEASE ALLOACTED RESOURCES
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default
xlApp = Nothing
End Try
End Sub
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Integer
Dim j As Integer
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
For Each col As DataGridViewColumn In Me.DataGridView1.Columns
xlWorkSheet.Cells(1, col.Index + 1) = col.HeaderText.ToString
Next
Try
For CurrentRowIndex = 0 To DataGridView1.RowCount - 1 'current row index
'For j = 0 To Me.DataGridView1.ColumnCount
For CurrentColumnIndex = 0 To DataGridView1.ColumnCount - 1 'current column index within row index
xlWorkSheet.Cells(2, CurrentColumnIndex + 1) = DataGridView1.Columns(CurrentColumnIndex).HeaderText 'display header
xlWorkSheet.Cells(CurrentRowIndex + 3, CurrentColumnIndex + 1) = DataGridView1(CurrentColumnIndex, CurrentRowIndex).Value.ToString()
Next
'xlWorkSheet.Cells(2, CurrentColumnIndex + 1) = DataGridView1.Columns(CurrentColumnIndex).HeaderText 'display header
'xlWorkSheet.Cells(i + 2, j + 1) = Me.DataGridView1(j, i).Value.ToString()
'xlWorkSheet.Cells(2, CurrentColumnIndex + 1) = DataGridView1.Columns(CurrentColumnIndex).HeaderText 'display header
'Next
Next
Catch ex As Exception
MsgBox("Unable to extract data" & ex.Message, MsgBoxStyle.Critical)
Exit Sub
End Try
xlWorkBook.Activate()
'//get path
Me.FolderBrowserDialog1.ShowDialog()
Dim path As String = Me.FolderBrowserDialog1.SelectedPath
xlWorkBook.SaveAs(path & "\Excel_With_Headers.xls")
'xlWorkSheet.SaveAs("burn permit export.xls")
xlWorkBook.Close()
xlApp.Quit()
'releaseObject(xlApp)
'releaseObject(xlWorkBook)
'releaseObject(xlWorkSheet)
MsgBox("You can find your report at " & path & "\burn permit export.xls")
End Sub
Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Integer
Dim j As Integer
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
Try
For CurrentRowIndex = 0 To DataGridView1.RowCount - 1 'current row index
'xlWorkSheet.Cells(1, 1) = "With Headers"
For CurrentColumnIndex = 0 To DataGridView1.ColumnCount - 1 'current column index within row index
xlWorkSheet.Cells(2, CurrentColumnIndex + 1) = DataGridView1.Columns(CurrentColumnIndex).HeaderText 'display header
xlWorkSheet.Cells(CurrentRowIndex + 3, CurrentColumnIndex + 1) = DataGridView1(CurrentColumnIndex, CurrentRowIndex).Value.ToString()
Next
Next
Catch ex As Exception
MsgBox("Unable to extract data" & ex.Message, MsgBoxStyle.Critical)
Exit Sub
End Try
End Sub
End Class

export to excel vb.net office 2010

I have a vb.net project, want to export to excel (2010) in English from axmshflexgrid. But I have always an exception
Ancien format ou bibliothèque de type non valide
and an empty excel file with this code.
Private Sub cmd_export_excel_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmd_export_excel.Click
On Error GoTo ErrorHandler
Dim iRow As Short
Dim iCol As Short
Dim objExcl As Microsoft.Office.Interop.Excel.Application
Dim objWk As Microsoft.Office.Interop.Excel.Workbook
Dim objSht As Microsoft.Office.Interop.Excel.Worksheet
Dim iHead As Short
Dim vHead As Object
objExcl = New Microsoft.Office.Interop.Excel.Application
objExcl.Visible = True
objExcl.UserControl = True
Dim oldCI As System.Globalization.CultureInfo = _
System.Threading.Thread.CurrentThread.CurrentCulture
System.Threading.Thread.CurrentThread.CurrentCulture = _
New System.Globalization.CultureInfo("en-US")
objWk = objExcl.Workbooks.Add
System.Threading.Thread.CurrentThread.CurrentCulture = oldCI
objSht = objWk.Sheets(1)
vHead = Split(g.FormatString, "|")
For iHead = 1 To UBound(vHead)
If Len(Trim(vHead(iHead))) > 0 Then objSht.Cells._Default(1, iHead) = vHead(iHead)
Next
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor
For iRow = 0 To g.Rows - 1
For iCol = 0 To g.get_Cols() - 1
g.Row = iRow
g.Col = iCol
If g.Text <> "" Then
objSht.Range(NumCol2Lattre(iCol + 1) & "" & iRow + 2 & ":" & NumCol2Lattre(iCol + 1) & "" & iRow + 2 & "").Select()
objExcl.ActiveCell.Value = CStr(g.Text)
End If
Next iCol
Next iRow
objExcl.Application.Visible = True
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default
objSht = Nothing
objWk = Nothing
objExcl = Nothing
Exit Sub
ErrorHandler:
objSht = Nothing
objWk = Nothing
objExcl = Nothing
MsgBox("Error In expotation task & " & Err.Description, MsgBoxStyle.Information)
Err.Clear()
End Sub
Do you have multiple versions installed?
Whats the version of you interop assemblies?
Compare the version with the created excel instance (objExcl.Version).
It looks like you have a version conflict.
You may have to re-install office2010 in this case(helps most of the time).

Export to excel vb.net

I have a problem when I export a flexgrid to excel from vb.net vs2008 to office 2010 english version an excel file is opened but it is empty. However, when I use office french version it is opened [correctly]
My code is:
On Error GoTo ErrorHandler
Dim iRow As Short
Dim iCol As Short
Dim objExcl As Excel.Application
Dim objWk As Excel.Workbook
Dim objSht As Excel.Worksheet
Dim iHead As Short
Dim vHead As Object
objExcl = New Excel.Application
objExcl.Visible = True
objExcl.UserControl = True
Dim oldCI As System.Globalization.CultureInfo = _
System.Threading.Thread.CurrentThread.CurrentCulture
System.Threading.Thread.CurrentThread.CurrentCulture = _
New System.Globalization.CultureInfo("en-US")
objWk = objExcl.Workbooks.Add
System.Threading.Thread.CurrentThread.CurrentCulture = oldCI
objSht = objWk.Sheets(1)
vHead = Split(g.FormatString, "|")
'populate heading in the sheet
'take the column heading from flex grid and put it in the sheet
For iHead = 1 To UBound(vHead)
If Len(Trim(vHead(iHead))) > 0 Then objSht.Cells._Default(1, iHead) = vHead(iHead)
Next
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor
For iRow = 0 To g.Rows - 1
For iCol = 0 To g.get_Cols() - 1
g.Row = iRow
g.Col = iCol
'
'If g.Text <> "" Then objSht.Cells._Default(iRow + 2, iCol + 1) = g.Text
If g.Text <> "" Then
objSht.Range(NumCol2Lattre(iCol + 1) & "" & iRow + 2 & ":" & NumCol2Lattre(iCol + 1) & "" & iRow + 2 & "").Select()
objExcl.ActiveCell.Value = g.Text
End If
Next iCol
Next iRow
objExcl.Application.Visible = True
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default
objSht = Nothing
objWk = Nothingl may not be destroyed until it is garbage collected. Click
objExcl = Nothing
Exit Sub
ErrorHandler:
objSht = Nothing
objWk = Nothing
objExcl = Nothing
MsgBox("Error In expotation task & " & Err.Description, MsgBoxStyle.Information)
Err.Clear()
Check out this website Exporting MSFlexGrid to Excel
I suspect your problem is with vHead = Split(g.FormatString, "|") Use the debugger to find out what is the value of g.FormatString. Is it causing an error? Step through the code one line at a time and see what happens.
On Error GoTo ErrorHandler
Imports System.Data
Imports System.IO
Imports System.Web.UI
Partial Class ExportGridviewDatainVB
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindGridview()
End If
End Sub
Protected Sub BindGridview()
Dim dt As New DataTable()
dt.Columns.Add("UserId", GetType(Int32))
dt.Columns.Add("UserName", GetType(String))
dt.Columns.Add("Education", GetType(String))
dt.Columns.Add("Location", GetType(String))
dt.Rows.Add(1, "SureshDasari", "B.Tech", "Chennai")
dt.Rows.Add(2, "MadhavSai", "MBA", "Nagpur")
dt.Rows.Add(3, "MaheshDasari", "B.Tech", "Nuzividu")
dt.Rows.Add(4, "Rohini", "MSC", "Chennai")
dt.Rows.Add(5, "Mahendra", "CA", "Guntur")
dt.Rows.Add(6, "Honey", "B.Tech", "Nagpur")
gvDetails.DataSource = dt
gvDetails.DataBind()
End Sub
Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
' Verifies that the control is rendered
End Sub
Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As EventArgs)
Response.ClearContent()
Response.Buffer = True
Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", "Customers.xls"))
Response.ContentType = "application/ms-excel"
Dim sw As New StringWriter()
Dim htw As New HtmlTextWriter(sw)
gvDetails.AllowPaging = False
BindGridview()
'Change the Header Row back to white color
gvDetails.HeaderRow.Style.Add("background-color", "#FFFFFF")
'Applying stlye to gridview header cells
For i As Integer = 0 To gvDetails.HeaderRow.Cells.Count - 1
gvDetails.HeaderRow.Cells(i).Style.Add("background-color", "#df5015")
Next
gvDetails.RenderControl(htw)
Response.Write(sw.ToString())
Response.[End]()
End Sub
End Class