I am familiar with the basic preparation of the Excel export function. Let me give a brief introduction.
First: Add reference
Second, import the namespace
Again: it is the basic code. Here we take the data center charging system's export of recharge information as an example. Since detailed comments are made in the Code, the detailed introduction will not be repeated.
Private sub btnexport_click (sender as system. object, e as system. eventargs) handles btnexport. click 'create Excel dim xlapp, xlbook, xlsheet as object xlapp = Createobject ("Excel. application ") xlbook = xlapp. workbooks. add xlsheet = xlbook. worksheets (1) dim row as datarow defines row as the dim Col as datacolumn of the able as the dim rowindex column of Col, colindex as integer 'Open the page xlsheet = xlapp on sheet1. worksheets ("sheet1") 'assigned Initial Value rowindex = 2' row (original value 1) colindex = 0' column 'write field name for each Col in DT. columns colindex = colindex + 1 xlapp. cells (2, colindex) = Col. the original value of columnname is 1, and next writes specific content to the table for each row in DT. rows rowindex = rowindex + 1 colindex = 0 for each Col in DT. columns colindex = colindex + 1 xlapp. cells (rowindex, colindex) = row (Col. columnname) Next next 'displays the Excel application xlapp. visible = true end sub
Finally, according to your own needs, the content exported to excel is more refined. You can add headers.
* Excel header * xlsheet. cells (1, 3 ). value = "Student recharge record" 'header content, in the first row, the third column xlsheet. range ("A1", "g1 "). font. bold = true 'font bold xlsheet. range ("A1", "g1 "). font. colorindex = 32' font color blue xlsheet. range ("A1", "g1 "). font. size = 25 'size 25 xlsheet. range ("A1", "g1 "). merge () 'merge cell '***** Excel table content ******* xlsheet. range ("A2", "G2 "). font. bold = true 'font bold xlsheet. range ("A2", "G2 "). font. size = 14' font size xlsheet. range ("A1", "g1 "). horizontalalignment = 3' specifies the cell, horizontally centered (redundant) xlsheet. cells. horizontalalignment = 3' all cells, horizontally centered xlsheet. pagesetup. centerhorizontally = true 'sets the horizontal center of the page xlsheet. range ("A2", "G2 "). columnwidth = 20' set the width of the specified column (unit: number of characters)
This is final: