Create an Excel file in the program 1 using Excel = Microsoft. Office. InterOP. Excel;
2 using system;
3 using system. runtime;
4 using system. reflection;
5 // Add a com reference for Excel
6 Public void createexcelfile (string filepath)
7 {
8if (! File. exists (filepath ))
9 {
10excel. applicationclass excelapp = new Microsoft. Office. InterOP. Excel. applicationclass ();
11excel. Workbook excelbook = excelapp. workbooks. Add (missing. value );
12excelapp. displayalerts = false;
13
14excel. worksheet excelsheet =
(Excel. worksheet) excelbook. worksheets. Add (missing. Value, missing. value );
15excelsheet. Name = "div_link ";
16
17excelbook. saveas (filepath, Excel. xlfileformat. xlworkbooknormal,
Missing. Value, missing. Value, false, false, Excel. xlsaveasaccessmode. xlshared,
Missing. Value, missing. Value, missing. value );
18excelbook. Close (Excel. xlsaveaction. xldonotsavechanges, missing. Value, missing. value );
19
20excelapp. Quit ();
21
22system. runtime. interopservices. Marshal. releasecomobject (excelapp );
23gc. Collect ();
24}
25 // here you can directly add the code for operating the Excel file
26}
Supplement: the code added in the preceding comment for using jet to access EXCEL to insert data: 1 string connstr =
2 "provider = Microsoft. Jet. oledb.4.0; Data Source =" + filepath + "; extended properties = Excel 8.0 ;";
3 oledbconnection oleconn = new oledbconnection (connstr );
4 oledbcommand olecmd = new oledbcommand ();
5olecmd. Connection = oleconn;
6oleconn. open ();
7 // dt_1 is a data table of mine.
8for (INT I = 0; I <dt_1.rows.count; I ++)
9 {
10/** // * Note that when Excel is used as a Jet Database
11 * the worksheet in Excel is the corresponding data table,
12 * Add a $ suffix to the worksheet name. In common SQL statements, use [] to pack the table,
13 * In DTS statements, you do not need to use [] to wrap the worksheet name, but you still need a $ suffix.
14 * For example:
15 * select F1, F2 from OpenRowSet ('Microsoft. Jet. oledb.4.0 ', 'excel 8.0; HDR = no; database = C:/a.xls', sheet1 $)
16 */
17olecmd. commandtext = "insert into [div_link $] (F1) values ('" + dt_1.rows [I] [1]. tostring () + "')";
18olecmd. executenonquery ();
19}
20oleconn. Close ();