標籤:style blog color 使用 os 檔案
在實際項目中,不可避免的會操作excel表格。一直以來都是讀取excel表格,可今天為了寫入excel表格,可是煞費苦心,終於完成,記錄下來以便後續使用。
1、讀取excel表格的資料
讀取excel資料,然後匯入到資料庫中,根據常識,只要是能得到一個dataset,那所有的問題便迎刃而解了。下面將讀取excel資料得到dataset:
public DataSet ExecleDs(string filenameurl) { string strConn = "Provider=Microsoft.ACE.OleDb.12.0;" + "data source=" + filenameurl + ";Extended Properties=‘Excel 12.0; HDR=YES; IMEX=1‘"; OleDbConnection conn = new OleDbConnection(strConn); conn.Open(); DataSet ds = new DataSet(); string strSql = string.Format("SELECT * FROM [{0}$]", "Sheet1"); OleDbDataAdapter odda = new OleDbDataAdapter(strSql, conn); odda.Fill(ds, "hou"); return ds; }
2、寫入資料到excel表格
首先加入兩個引用:
using System.Reflection; using Microsoft.Office.Interop.Excel;
1)初始化:
object missing = Missing .Value ;Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();//執行個體化excel對象 Microsoft.Office.Interop.Excel.Workbook rsBook = excel.Workbooks.Open(fullFileName, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);//開啟目標檔案Microsoft.Office.Interop.Excel.Worksheet excelSheet = (Microsoft.Office.Interop.Excel.Worksheet)rsBook.Sheets.get_Item(1);//設定第一個工作薄 excelSheet.Activate();//啟用當前活頁簿
2)寫入資料:
for (int i = 1; i < 5; i++) { excelSheet.Cells[i, 1] = i; excelSheet.Cells[i, 2] = i + 5; excelSheet.Cells[i, 3] = i + 10; }
註:excel表格的第一行、第一列都是以1開始的。
3)儲存excel檔案、設定Application的屬性,並回收資源
rsBook.Save(); excel.DisplayAlerts = false; excel.Visible = true; excelSheet = null; rsBook = null; excel = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers();