Export the information in the DataGridView to Excel is "Room charge system" one of the functions, here is mainly vs office interaction, methods have n many (from here can see this function is difficult to go to), now introduce me to use a bar, You first need to add and reference the namespace.
1. Add: Right-click on the project name of the form that is the U-layer of the project name--add--reference--The following image appears, search for Excel, in the results of the matching version of the Microsoft.Interop.Excel
2. Reference namespaces: Imports Microsoft.Office.Interop
Thanks to the ability to export excel several times, it is packaged separately into a function exporttoexcel and placed in a module.
Public Function exportToExcel (ByVal DTG as DataGridView) as the Boolean ' DataGridView ' does not have information, quit the procedure If DTG. Rows.Count = 0 Then MsgBox ("No information to export!") ") Return False Exit Function End If ' defines an Excel program, workbook, worksheet Dim xlapp as New exce L.application () Dim xlbook As Excel.Workbook = XlApp.Workbooks.Add () Dim xlsheet As Excel.Worksheet = Xlbook . Worksheets (1) ' Define Excel table row and column index Dim rowIndex As Integer = 1 Dim colindex As Integer = 0 ' Add to Excel Add a table header for col as Integer = 0 to DTG. Columns.count-1 Colindex = colindex + 1 xlsheet.cells (1, colindex) = DTG. Columns (COL). HeaderText Next ' adds information from DataGridView to excel in for row as Integer = 0 to DTG. RowCount-1 RowIndex = rowIndex + 1 colindex = 0 for col as Integer = 0 to DTG. Columns.count-1 Colindex = colindex + 1 xlsheet.cells (rowIndex, colindex) = dTG (col, Row). Value.tostring () Next Next xlapp.visible = True ' Show Excel table Return True End Function
Form Call Code
Private Sub Btnexcel_click (sender as Object, e as EventArgs) Handles Btnexcel.click call globaldata.exporttoexcel ( Dtgchargecash) End Sub
The above is the code of the U-layer, and the B, D two is similar to other forms. Here's what you need to suggest.
DTG (Col,row) row by column, row from 0 initially, the header is not counted in the number of rows.
Excel (Row,col) First after the column, the rows from 1 start, the header is recorded in the number of rows.
DataGridView Export Excel