C#:使用OleDb從Excel表格中讀取資訊到DataTable

來源:互聯網
上載者:User

標籤:style   http   io   ar   os   使用   sp   for   檔案   

從Excel表格中將資料讀入到DataTable資料類型中,我是通過使用OLEDB來實現的

(OLEDB是Object Linking and Embedding Database的縮寫)

現有一個副檔名為xlsx的活頁簿檔案“節氣表.xlsx”,在工作表Sheet1中有24個節氣的資訊

本文中的樣本程式(代碼將在後面給出)讀取這個資料表後的效果如:

可以看出:OleDb讀入一個Excel工作表(Sheet)的資料後,工作表的第一行會變成標題,第二行起,逐行變為DataTable的一個資料行(Row)

樣本程式控制項說明:


程式碼:

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Data.OleDb;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;namespace ExcelReader{    public partial class FormMain : Form    {        public FormMain()        {            InitializeComponent();        }        private void FormMain_Load(object sender, EventArgs e)        {            txtXlsxPath.Text = @"節氣表.xlsx";            txtSheetName.Text  = @"Sheet1";        }        /// <summary>        /// 按鈕:從EXCEL活頁簿中讀取資訊        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void btnRead_Click(object sender, EventArgs e)        {            dgvTable.DataSource = ReadFromExcel(txtXlsxPath.Text, txtSheetName.Text);        }        /// <summary>        /// 從EXCEL活頁簿中讀取資訊到DataTable(需要System.Data.OleDb)        /// </summary>        /// <param name="sXlsxPath">EXCEL活頁簿檔案地址</param>        /// <param name="sSheetName">工作表名稱</param>        private DataTable ReadFromExcel(string sXlsxPath, string sSheetName)        {            string sExt = System.IO.Path.GetExtension(sXlsxPath);            string sConn = "";            if (sExt == ".xlsx") //Excel2007            {                sConn =                     "Provider=Microsoft.ACE.OLEDB.12.0;" +                      "Data Source=" + sXlsxPath + ";" +                      "Extended Properties=‘Excel 12.0;HDR=YES‘";            }            else if (sExt == ".xls") //Excel2003            {                sConn =                    "Provider=Microsoft.Jet.OLEDB.4.0;" +                    "Data Source=" + sXlsxPath + ";" +                    "Extended Properties=Excel 8.0";            }            else            {                throw new Exception("未知的檔案類型");            }            OleDbConnection oledbConn = new OleDbConnection(sConn);            oledbConn.Open();            OleDbDataAdapter command = new OleDbDataAdapter(                "SELECT * FROM [" + sSheetName + "$]", oledbConn);            DataSet ds = new DataSet();            command.Fill(ds, sSheetName);            oledbConn.Close();                       return ds.Tables[sSheetName];        }    }}

編寫這個程式的時候遇到過兩個異常,解決方案如下:

1)異常“外部表格不是預期的格式”:

寫串連運算式時(上面代碼中的sConn),要對副檔名為.xlsx和.xls分類討論

2)異常:“找不到可安裝的ISAM”:

讀取.xlsx格式的Excel表格時,串連運算式的Extended Properties部分,等號後面的字元是用單引號括起來的,如果漏寫單引號引起的,補上就好了

END


C#:使用OleDb從Excel表格中讀取資訊到DataTable

聯繫我們

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