C#導入Excel、Excel導入、導入.xls 、導入.xlsx、Excel2003版本、Excel2007版本


C#導入Excel:

  1、選擇Excel 03版文件

  2、選擇需要讀取數據的Excel工作表

    3、選擇工作表中需要讀取的

源碼地址在圖片下面,不要點擊圖片,點擊下載地址跳轉下載。

 

 下載源碼:

http://files.cnblogs.com/files/lanyubaicl/%E8%AF%BB%E5%8F%96Excel0.zip

 

using System;
using System.Collections;
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.Windows.Forms;

namespace Read
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 連接字符串
        /// </summary>
        static string strConn = "";
        /// <summary>
        /// 搜索彈出選擇Excel框,選擇Excel,獲取所有工作表。
        /// 將工作表名賦值給comboBox1,顯示所有工作表,用戶可以篩選工作表讀取數據
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void label5_Click(object sender, EventArgs e)
        { 
            //清空comboBox1中現有的工作表
            comboBoxSheet.Items.Clear();   
            //打開一個文件選擇框
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "Excel文件";
            ofd.FileName = "";
            ofd.Filter = "Excel文件(*.xls)|*";
            try
            {
                //選中文件
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    //獲取選中文件的路徑
                    this.textBoxFilePath.Text = ofd.FileName;                 
                    //獲取文件后綴名 
                    if (System.IO.Path.GetExtension(ofd.FileName).ToLower() == ".xls")
                    {
                        //如果是07以下(.xls)的版本的Excel文件就使用這條連接字符串
                        strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ofd.FileName + ";Extended Properties=Excel 8.0;";
                    }
                    else
                    {  
                        //如果是07以上(.xlsx)的版本的Excel文件就使用這條連接字符串
                        strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + ofd.FileName + ";Extended Properties='Excel 12.0; HDR=NO; IMEX=1'"; //此連接可以操作.xls與.xlsx文件
                    }
                    if (System.IO.Path.GetExtension(ofd.FileName).ToLower().Contains( ".xls"))
                    {
                        //打開Excel的連接,設置連接對象
                        OleDbConnection conn = new OleDbConnection(strConn);
                        conn.Open();
                        DataTable sheetNames = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
                        conn.Close();
                        int i = 0;
                        //遍歷Excel文件獲取Excel工作表,並將所有工作表名稱加載到comboBox控件中
                        foreach (DataRow dr in sheetNames.Rows)
                        {
                            if (i == 0)
                            {
                                this.comboBoxSheet.Text = dr[2].ToString();
                            }
                            //添加工作表名稱
                            comboBoxSheet.Items.Add(dr[2]);
                            i++;
                        }
                    }
                    else
                    {
                        MessageBox.Show("excel 格式不正確!");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("導入文件時出錯,文件可能正被打開\r\n"+ex.Message.ToString(), "提示");
            }
        }

        /// <summary>
        /// 查看所有列
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void label3_Click(object sender, EventArgs e)
        {
            //設置鼠標指針為等待狀態
            this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
            try
            {
                //清空所有節點
                this.treeView1.Nodes.Clear();
                OleDbConnection conn = new OleDbConnection(strConn);
                //當前選中的工作表前幾行數據,獲取數據列
                OleDbDataAdapter oada = new OleDbDataAdapter("select top 5 * from [" + comboBoxSheet.Text + "]", strConn);
                DataTable ds = new DataTable();
                oada.Fill(ds);
                //將列加載到樹節點上
                for (int i = 0; i < ds.Columns.Count; i++)
                { 
                    TreeNode node = new TreeNode();
                    node.Name = i.ToString();
                    node.Text = ds.Columns[i].ColumnName.ToString();
                    this.treeView1.Nodes.Add(node);
                }
                conn.Close();                 
            }
            catch (Exception ex)
            {
                
            }
            //設置鼠標指針狀態為默認狀態
            this.Cursor = System.Windows.Forms.Cursors.Default;           

        } 
        /// <summary>
        /// 刪除選擇項目
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            //遍歷樹節點
            for (int i = treeView1.Nodes.Count - 1; i >= 0; i--)
            {
                TreeNode node = new TreeNode();
                node = treeView1.Nodes[i];
                if (node.Checked)
                {
                    //刪除已經勾選的節點,倒序刪除,防止異常
                    treeView1.Nodes.Remove(treeView1.Nodes[i]);
                }
            }
        }
        /// <summary>
        /// 檢索數據
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void label1_Click(object sender, EventArgs e)
        {
            try
            {
                //存儲需要查詢數據的列
                string strName = "";
                //遍歷列名,每個列名用逗號隔開
                for (int i = 0; i < treeView1.Nodes.Count; i++)
                {
                    TreeNode n = new TreeNode();
                    n = treeView1.Nodes[i];
                    strName = strName + "[" + n.Text + "],";
                }
                strName = strName.Substring(0, strName.Length - 1); 
                //獲取用戶沒有刪掉留下來的列,讀取這些列的數據
                //建立Excel連接
                OleDbConnection conn = new OleDbConnection(strConn);
                //讀取數據
                OleDbDataAdapter oada = new OleDbDataAdapter("select  " + strName + " from [" + comboBoxSheet.Text + "]", strConn);
                DataTable dt = new DataTable();
                //填入DataTable
                oada.Fill(dt);
                conn.Close();
                //顯示這些列的數據
                dataGridView1.DataSource = dt;
            }
            catch (Exception ex)
            {
                 
            }
        }
        private void label5_MouseEnter(object sender, EventArgs e)
        {
            this.Cursor = Cursors.Hand;
            ((Label)sender).BackColor = Color.LightGray;
        }
        private void label5_MouseLeave(object sender, EventArgs e)
        {
            this.Cursor = Cursors.Default;
            ((Label)sender).BackColor = Control.DefaultBackColor;
        } 
    }
}

 

 

 

 

 

 

 下載源碼:http://files.cnblogs.com/files/lanyubaicl/%E8%AF%BB%E5%8F%96Excel0.zip

 

 

這里是tb地址

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM