OpenXML generate Report from Excel Model - vb.net

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

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.

An unhandled exception of type 'System.Data.Odbc.OdbcException' occurred in System.Data.dll

I Create Project VB.NET Export data to Excels. But error An unhandled exception of type 'System.Data.Odbc.OdbcException' occurred in System.Data.dll
I Connect Database Postgresql Use PostgreSQL ODBC Driver (psqlODBC).
MainForm.vb
Imports System.IO
Imports System.Data
Imports System.Data.Odbc
Public Class MainForm
Private Function getDemoDataSet() As DataSet
Dim MyCon As New Odbc.OdbcConnection
MyCon.ConnectionString = "Driver={PostgreSQL UNICODE};database=tscon;server=192.168.3.60;port=5432;uid=postgres;sslmode=disable;readonly=0;protocol=7.4;User ID=postgres;password=1234;"
Dim da As Odbc.OdbcDataAdapter
Dim dt As New DataTable()
Dim str2 As String
MyCon.Open()
str2 = "select * from entity_tbl"
Dim ds As New DataSet
da = New Odbc.OdbcDataAdapter(str2, MyCon)
da.Fill(ds)
ds.Tables(0).TableName = "Customer0"
MyCon.Close()
Return ds
End Function
Private Sub startDemoButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles startDemoButton.Click
' Prepare the output filenames
Dim timeMark As String = DateTime.Now.ToString("yyyyMMdd HHmmss")
''Dim cellByCellFilePath As String = "C:\ExcelExportCellByCell_" + timeMark + ".xls"
Dim fastExportFilePath As String = "D:\" + timeMark + ".xls"
Me.demoResultListBox.Items.Clear()
' Object to mark the times for each process
Dim stopwatch As New Stopwatch()
Me.UseWaitCursor = True
Try
' Get the demo DataSet
stopwatch.Start()
Dim demoDataSet As DataSet = Me.getDemoDataSet()
stopwatch.Stop()
Me.demoResultListBox.Items.Add("* Generate DEMO DataSet: " + stopwatch.Elapsed.ToString())
stopwatch.Reset()
' '' Use the "Copy-cell-by-cell" method
''stopwatch.Start()
''ExportingCellByCellMethod.ExportToExcel(demoDataSet, cellByCellFilePath)
''stopwatch.Stop()
''Me.demoResultListBox.Items.Add("* COPY CELL-BY-CELL method: " + stopwatch.Elapsed.ToString())
''stopwatch.Reset()
' Use the "fast export" method
stopwatch.Start()
FastExportingMethod.ExportToExcel(demoDataSet, fastExportFilePath)
stopwatch.Stop()
Me.demoResultListBox.Items.Add("* FAST EXPORT method: " + stopwatch.Elapsed.ToString())
stopwatch.Reset()
Finally
Me.UseWaitCursor = False
End Try
End Sub
End Class
Module FastExportingMethod.vb
Imports Microsoft.Office.Interop.Excel
Imports Microsoft.Office.Interop
Module FastExportingMethod
Public Sub ExportToExcel(ByVal dataSet As DataSet, ByVal outputPath As String)
' Create the Excel Application object
'Dim excelApp As New ApplicationClass()
Dim excelApp As New Excel.Application()
' Create a new Excel Workbook
Dim excelWorkbook As Workbook = excelApp.Workbooks.Add(Type.Missing)
Dim sheetIndex As Integer = 0
Dim col, row As Integer
Dim excelSheet As Worksheet
' Copy each DataTable as a new Sheet
For Each dt As System.Data.DataTable In dataSet.Tables
sheetIndex += 1
' Copy the DataTable to an object array
Dim rawData(dt.Rows.Count, dt.Columns.Count - 1) As Object
' Copy the column names to the first row of the object array
For col = 0 To dt.Columns.Count - 1
rawData(0, col) = dt.Columns(col).ColumnName
Next
' Copy the values to the object array
For col = 0 To dt.Columns.Count - 1
For row = 0 To dt.Rows.Count - 1
rawData(row + 1, col) = dt.Rows(row).ItemArray(col)
Next
Next
' Calculate the final column letter
Dim finalColLetter As String = String.Empty
Dim colCharset As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Dim colCharsetLen As Integer = colCharset.Length
If dt.Columns.Count > colCharsetLen Then
finalColLetter = colCharset.Substring( _
(dt.Columns.Count - 1) \ colCharsetLen - 1, 1)
End If
finalColLetter += colCharset.Substring( _
(dt.Columns.Count - 1) Mod colCharsetLen, 1)
' Create a new Sheet
excelSheet = CType( _
excelWorkbook.Sheets.Add(excelWorkbook.Sheets(sheetIndex), _
Type.Missing, 1, XlSheetType.xlWorksheet), Worksheet)
excelSheet.Name = dt.TableName
' Fast data export to Excel
Dim excelRange As String = String.Format("A1:{0}{1}", finalColLetter, dt.Rows.Count + 1)
excelSheet.Range(excelRange, Type.Missing).Value2 = rawData
' Mark the first row as BOLD
CType(excelSheet.Rows(1, Type.Missing), Range).Font.Bold = True
excelSheet = Nothing
Next
' Save and Close the Workbook
excelWorkbook.SaveAs(outputPath, XlFileFormat.xlWorkbookNormal, Type.Missing, _
Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlExclusive, _
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing)
excelWorkbook.Close(True, Type.Missing, Type.Missing)
excelWorkbook = Nothing
' Release the Application object
excelApp.Quit()
excelApp = Nothing
' Collect the unreferenced objects
GC.Collect()
GC.WaitForPendingFinalizers()
End Sub
End Module

Why does calculated row in dataGridView not get saved when exporting as an Excel file?

The code I am working on loads an XML file into a dataTable and displays it in a dataGridView. I then average each column in the dataGridView and display them as a new row in the dataGridView. I then export the dataGridView as an Excel file, however it is does not include the added average row. Any input that is manually entered into the dataGridView does get saved in the export? I understand that with SQL databases, you must call an update on the dataGridView source. I am not quite sure what to do in this case. Any ideas on how I can get the changes to be saved?
Opens a XML file and loads it into dataGridView
Private Sub ExOpen_Click(sender As Object, e As EventArgs) Handles ExOpen.Click
' Uses a openFileDialog to find the file path for the file the user wishes to
' use. It then displays the path in a textBox. Load a DataTable with the
' information found in the XML file and then set it as the dataSource for the
' DataGridView()
OpenFileDialog1.FileName = Nothing
OpenFileDialog1.Filter = "XML|*.xml"
If OpenFileDialog1.ShowDialog = System.Windows.Forms.DialogResult.OK Then
lblExFile.Text = OpenFileDialog1.FileName
End If
Dim dtDataTbl As New System.Data.DataTable
Dim dsDataSet As New DataSet
For Each dtDataTbl In dsDataSet.Tables
dtDataTbl.BeginLoadData()
Next
Try
dsDataSet.ReadXml(lblExFile.Text)
For Each dtDataTbl In dsDataSet.Tables
dtDataTbl.EndLoadData()
Next
DataGridView1.DataSource = dtDataTbl
Catch
Finally
dsDataSet = Nothing
dtDataTbl = Nothing
End Try
End Sub
Performs average of columns and adds it as a new row in dataGridView
Private Sub ExAvg_Click(sender As Object, e As EventArgs) Handles ExAvg.Click
' Goes through each column and finds the average. The averages are printed out
' into the DataGridView.
Dim decAvg As Decimal = 0
Dim sValue As String = Nothing
Dim sAppend As String = Nothing
Dim iCount As Integer = 0
For iColumn As Integer = 1 To DataGridView1.Columns.Count - 1
iCount = 0
For iRow As Integer = 0 To DataGridView1.Rows.Count - 1
sAppend = Nothing
If Not DataGridView1.Rows(iRow).Cells(iColumn).Value Is Nothing Then
sValue = CStr(DataGridView1.Rows(iRow).Cells(iColumn).Value)
Dim cChars() As Char = sValue.ToCharArray()
' Each character is only taken if a digit or "."
For Each cCharacter In cChars
If Char.IsDigit(cCharacter) OrElse cCharacter = "." Then
sAppend &= cCharacter
End If
Next
iCount += 1
decAvg += CDec(sAppend)
End If
Next
decAvg = Math.Round(decAvg / iCount, 2)
' Print the average row in the DataGridView.
Try
If iColumn = 1 Then
DataGridView1.Rows(iCount).Cells(iColumn).Value = "$" & CStr(decAvg)
Else
DataGridView1.Rows(iCount).Cells(iColumn).Value = CStr(decAvg)
End If
DataGridView1.Rows(iCount).Cells(0).Value = "Average"
Catch
End Try
Next
DataGridView1.v()
End Sub
Exports the dataGridView as an Excel file(missing added average row)
Private Sub ExSave_Click(sender As Object, e As EventArgs) Handles ExSave.Click
' Information from the DataGridView is transferred into an excel object
' row by row and column by column. The file name is picked by the user
' using a saveFileDialog.
SaveFileDialog1.FileName = Nothing
SaveFileDialog1.Filter = "Excel File|*.xls"
If SaveFileDialog1.ShowDialog = System.Windows.Forms.DialogResult.OK Then
lblExFile.Text = SaveFileDialog1.FileName
End If
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.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = CType(xlWorkBook.Worksheets(1), Excel.Worksheet)
Dim dc As DataColumn
Dim dr As DataRow
Dim dt As System.Data.DataTable
dt = CType(DataGridView1.DataSource, System.Data.DataTable)
Dim colIndex As Integer = 0
Dim rowIndex As Integer = 0
Try
'Export the Columns to excel file
For Each dc In dt.Columns
colIndex = colIndex + 1
xlWorkSheet.Cells(1, colIndex) = dc.ColumnName
Next
'Export the rows to excel file
For Each dr In dt.Rows
rowIndex = rowIndex + 1
colIndex = 0
For Each dc In dt.Columns
colIndex = colIndex + 1
xlWorkSheet.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)
Next
Next
xlWorkSheet.Columns.AutoFit()
xlWorkBook.SaveAs(lblExFile.Text, XlFileFormat.xlWorkbookNormal, Type.Missing, _
Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlExclusive, _
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing)
xlWorkBook.Close()
You are adding the average to the GridView but write the datatable to Excel.

DataGrid export to excel

I have a DataGrid control that fills with a data set.
I don't show all fields of data set in DataGrid control.
I want to create an excel file from my DataGrid.
How to get solution?
(windows form , vb net 1.1)
Try this
Link
OR
Try This
Imports Excel = Microsoft.Office.Interop.Excel
Dim excel As New Microsoft.Office.Interop.Excel.ApplicationClass
Dim wBook As Microsoft.Office.Interop.Excel.Workbook
Dim wSheet As Microsoft.Office.Interop.Excel.Worksheet
wBook = excel.Workbooks.Add(System.Reflection.Missing.Value)
wSheet = wBook.Sheets("sheet1")
With wBook
.Sheets("Sheet1").Select()
.Sheets(1).Name = "NameYourSheet"
End With
For i = 0 To DataGrid1.RowCount - 1
For j = 0 To DataGrid1.ColumnCount - 1
wSheet.Cells(i + 1, j + 1).value = DataGrid1.Rows(i).Cells(j).Value.tosring
Next j
Next i
wSheet.Columns.AutoFit()
Private Sub btnExportToExcel_Click(sender As Object, e As EventArgs) Handles btnExportToExcel.Click
Dim xlApp As Excel.Application = New Excel.Application
xlApp.SheetsInNewWorkbook = 1
Dim xlWorkBook As Excel.Workbook = xlApp.Workbooks.Add
Dim xlWorkSheet As Excel.Worksheet = xlWorkBook.Worksheets.Item(1)
xlWorkSheet.Name = "Example_Export"
For nRow = 0 To dgvDataToExport.Rows.Count - 1
For nCol = 0 To dgvDataToExport.Columns.Count - 1
xlWorkSheet.Cells(nRow + 1, nCol + 1) = dgvDataToExport.Rows(nRow).Cells(nCol).Value
Next nCol
Next nRow
xlApp.DisplayAlerts = False
xlWorkBook.SaveAs("C:\Example.xlsx", Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, Type.Missing, Type.Missing, _
Excel.XlSaveAsAccessMode.xlNoChange, Excel.XlSaveConflictResolution.xlLocalSessionChanges)
xlWorkBook.Close()
xlApp.Quit()
End Sub
Try with this one:
Sub create_excel(sender As Object, e As EventArgs)
Dim strFileName As string
Dim tw As New StringWriter()
Dim hw As New HtmlTextWriter(tw)
strFileName = "some_excel_from_datagrid.xls"
Response.ContentType = "application/vnd.msexcel"
Response.AddHeader("Content-Disposition", "attachment; filename=" & strFileName)
Response.Charset = "UTF-8"
Response.ContentEncoding = Encoding.Default
DataGridID.RenderControl(hw)
Response.Write(tw.ToString())
Response.End()
End Sub
Maybe in this princip work.
String path = #"D:\users\....";
//your path
String connStr = "Provider=//your provider;Data Source=" + path + ";Extended Properties=Excel 12.0;";
//The connection to that file
OleDbConnection conn = new OleDbConnection(connStr);
//The query
string strSQL = "SELECT * FROM [?]";
//The command
OleDbCommand cmd = new OleDbCommand(/*The query*/strSQL, /*The connection*/conn);
DataTable dT = new DataTable();
conn.Open();
try
{
OleDbDataReader dR = cmd.ExecuteReader();
dT.Load(dR);
bS.DataSource = dT;
dGV.DataSource = bS;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
Try
If Not dgv.RowCount = 0 Then
Dim folderBrowser As New FolderBrowserDialog
folderBrowser.Description = "Select location to save the report"
Dim filepath1 As String = ""
If (folderBrowser.ShowDialog() = DialogResult.OK) Then
filepath1 = folderBrowser.SelectedPath
Else
Exit Sub
End If
Dim xlApp As Microsoft.Office.Interop.Excel.Application
Dim xlWorkBook As Microsoft.Office.Interop.Excel.Workbook
Dim xlWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
Try
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Integer
Dim j As Integer
xlApp = New Microsoft.Office.Interop.Excel.ApplicationClass
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim titleStyle As Excel.Style = xlWorkSheet.Application.ActiveWorkbook.Styles.Add("NewStyle1")
titleStyle.Font.Bold = True
titleStyle.Font.Size = "18"
titleStyle.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red)
xlWorkSheet.Cells(2, 2) = "Employee Payment Report"
xlWorkSheet.Cells(2, 4) = DateAndTime.Now.ToString("dd/MM/yyyy")
xlWorkSheet.Cells(2, 2).Style = "NewStyle1"
xlWorkSheet.Cells(2, 4).Style = "NewStyle1"
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'======================================================================================================
Dim headerStyle As Excel.Style = xlWorkSheet.Application.ActiveWorkbook.Styles.Add("NewStyle")
headerStyle.Font.Bold = True
headerStyle.Font.Size = "12"
headerStyle.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Brown)
For k = 1 To dgv.Columns.Count
xlWorkSheet.Cells(4, k) = dgv.Columns(k - 1).HeaderText
xlWorkSheet.Cells(4, k).Style = "NewStyle"
Next
'=======================================================================================================
Dim str As String = ""
Dim l As Integer = 1
j = 6
Dim amt As Double = 0.0
For i = 0 To dgv.RowCount - 1
amt = amt + dgv.Rows(i).Cells(4).Value
For m = 0 To dgv.ColumnCount - 1
xlWorkSheet.Cells(j, l) = dgv(m, i).Value.ToString()
str = dgv(m, i).Value.ToString()
l = l + 1
Next
j = j + 1
l = 1
Next
'======================================================================================================
Dim lastStyle As Excel.Style = xlWorkSheet.Application.ActiveWorkbook.Styles.Add("NewStyle2")
lastStyle.Font.Bold = True
lastStyle.Font.Size = "12"
lastStyle.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Blue)
Dim c As Integer = dgv.ColumnCount
xlWorkSheet.Cells(j + 2, c - 1) = "Total Amount"
xlWorkSheet.Cells(j + 2, c) = amt.ToString
xlWorkSheet.Cells(j + 2, c - 1).Style = "NewStyle2"
xlWorkSheet.Cells(j + 2, c).Style = "NewStyle2"
'=======================================================================================================
xlWorkSheet.SaveAs(filepath1 + "\EmployeePaymentReport.xlsx")
xlWorkBook.Close()
xlApp.Quit()
cls.releaseObject(xlApp)
cls.releaseObject(xlWorkBook)
cls.releaseObject(xlWorkSheet)
MsgBox("You can find the file at " + filepath1 + "\EmployeePaymentReport.xlsx")
Catch ex As Exception
MsgBox(ex.Message)
For Each Process In System.Diagnostics.Process.GetProcessesByName("EXCEL")
If Process.MainModule.ModuleName.ToUpper().Equals("EXCEL.EXE") Then
Process.Kill()
End If
Next
End Try
Else
Exit Sub
End If
Catch ex As Exception
End Try
End Sub