Excel的操作總結

來源:互聯網
上載者:User
程式中建立Excel檔案 1using Excel = Microsoft.Office.Interop.Excel;
 2using System;
 3using System.Runtime;
 4using System.Reflection;
 5//需要添加Excel的COM引用
 6public 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, 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,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//這裡可以直接添加操作Excel檔案的代碼
26}

補充:在上文的注釋處添加的用Jet訪問Excel插入資料的代碼: 1string ConnStr =
 2"provider=Microsoft.Jet.Oledb.4.0;data source=" + FilePath + ";Extended Properties=Excel 8.0;";
 3OleDbConnection OleConn = new OleDbConnection(ConnStr);
 4OleDbCommand OleCmd = new OleDbCommand();
 5OleCmd.Connection = OleConn;
 6OleConn.Open();
 7//DT_1是我的一個資料表
 8for (int i = 0; i < DT_1.Rows.Count; i++)
 9{
10/**//* SQL語句中需要注意的是把Excel當成Jet資料庫時
11*  Excel的WorkSheet就是對應的資料表,
12*  需要給WorkSheet名加上$尾碼,在普通SQL語句中需要用[]將表包起來,
13*  在DTS語句中,不需要用[]封裝WorkSheet名,但仍需要有$尾碼
14*  比如:
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();

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.