讀取、寫入excel數據

在實際項目中,不可避免的會操做excel表格。一直以來都是讀取excel表格,可今天爲了寫入excel表格,但是煞費苦心,終於完成,記錄下來以便後續使用。數據庫

 

一、讀取excel表格的數據ide

讀取excel數據,而後導入到數據庫中,根據常識,只要是能獲得一個dataset,那全部的問題便迎刃而解了。下面將讀取excel數據獲得dataset:url

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;
        }

 

二、寫入數據到excel表格spa

首先加入兩個引用:excel

using System.Reflection; using Microsoft.Office.Interop.Excel;code

 

1)初始化:orm

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開始的。blog

 

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();
相關文章
相關標籤/搜索