C#下Excel檔案的讀取

來源:互聯網
上載者:User

標籤:c#   excel   檔案   讀取   

具體的源碼如下,顯示開啟檔案瀏覽器選擇Excel檔案,對檔案進行讀取,最後展示出讀取的部分內容。

 public partial class MainWindow : Window    {        public MainWindow()        {            InitializeComponent();                    }        //添加兩個函數,一個是讀取Excel檔案的函數,另一個是寫資料進入Excel檔案的函數。        public static DataTable LoadDataFromExcel(string filePath,string sheetName)        {            DataSet getdata = new DataSet();            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";            string strExcel = string.Format("select * from [{0}$]",sheetName);            //串連資料來源            OleDbConnection conn = new OleDbConnection(strConn);            conn.Open();            //適配到資料來源            OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, strConn);            adapter.Fill(getdata, sheetName);            conn.Close();            return getdata.Tables[sheetName];        }        public static void WriteDataToExcel(DataSet DS, string filePath)        {        }        //開啟檔案瀏覽器,選擇需要的檔案        private void btnOpen_Click(object sender, RoutedEventArgs e)        {            OpenFileDialog fileDialog = new OpenFileDialog();            fileDialog.Multiselect = false;            fileDialog.Title = "請選擇檔案";            fileDialog.Filter = "Excel file|*.xlsx";            if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)            {                string file = fileDialog.FileName;                //System.Windows.Forms.MessageBox.Show("已選擇的檔案:" + file);                Pathtxt.Text = file;            }        }        private void btnTransfer_Click(object sender, RoutedEventArgs e)        {            DataTable FurTable = LoadDataFromExcel(Pathtxt.Text, "Nov FUR");            DataRow dtRow = FurTable.Rows[0];            object[] RowItem = dtRow.ItemArray;            Pathtxt.Text = "";            foreach (object item in RowItem)            {                if (item.ToString() != null)                {                    Pathtxt.Text += item.ToString();                    Pathtxt.Text += "  ";                }            }            //System.Windows.Forms.MessageBox.Show(dtRow[0].ToString());        }    }

C#下Excel檔案的讀取

相關文章

聯繫我們

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