讀取、寫入excel資料

來源:互聯網
上載者:User

標籤: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();

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.