1. 程式人生 > >【C#.NET】將excel或將CSV檔案中的sheet1匯入到dataGridView1中 ,或者匯入到DataTable,匯入到DataSet

【C#.NET】將excel或將CSV檔案中的sheet1匯入到dataGridView1中 ,或者匯入到DataTable,匯入到DataSet

實現的效果:


using System;
using System.Data;
using System.Data.OleDb;
using System.Windows.Forms;


namespace 淘寶單據接收器
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private string filePath;
        private string fileName;
        private OleDbConnection conn;
        private DataTable readDataTable;
        private string connString;
        private FileType fileType = FileType.noset;
        private enum FileType
        {
            noset,
            xls,
            xlsx,
            csv
        }
        //選擇路徑
        private void SetFileInfo(string path) 
        {
            filePath = path;
            fileName = this.filePath.Remove(0, this.filePath.LastIndexOf("\\") + 1);
            string filettType= fileName.Split('.')[1];
            switch (filettType)//判斷選擇的檔案是xls還是XLSX,還是CSV
            {
                case "xls":
                    //connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'"; fileType = FileType.xls;                    
                    connString = "Provider=Microsoft.Ace.OleDb.12.0;" + "Data Source=" + path + ";" + "Extended Properties=Excel 8.0;  ";
                    break;
                case "xlsx":
                    connString = "Provider=Microsoft.Ace.OleDb.12.0;" + "Data Source=" + path + ";" + "Extended Properties=Excel 8.0;  ";
                    //connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'"; fileType = FileType.xlsx;
                    break;
                case "csv":
                    connString = "Provider=Microsoft.Ace.OleDb.12.0;Data Source=" + filePath.Remove(filePath.LastIndexOf("\\") + 1) + ";Extended Properties='Text;FMT=Delimited;HDR=YES;'"; fileType = FileType.csv;
                    //connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath.Remove(filePath.LastIndexOf("\\") + 1) + ";Extended Properties='Text;FMT=Delimited;HDR=YES;'"; fileType = FileType.csv;
                    break;
            }
        }




        public DataTable ReadFile(string path)
        {
            try
            {
                if (System.IO.File.Exists(path))
                {
                    SetFileInfo(path);
                    OleDbDataAdapter myCommand = null;
                    DataSet ds = null;
                    using (conn = new OleDbConnection(connString))
                    {
                        conn.Open();
                        DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);


                        //DataTable dt2 = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);//獲取選中的EXECEL裡的所有工作簿
                        int dtname = schemaTable.Rows.Count - 1; //提示dt2,表的第3列就是EXCEL所有工作簿的名字
                        string sheetName = schemaTable.Rows[dtname][2].ToString().Trim();//獲取EXECEL第一個工作簿的名字
                        string tableName = fileType == FileType.csv ? sheetName : sheetName;//不管是CSV還是EXE都是取第一個工作
                        string strExcel = string.Empty;
                        strExcel = "Select   *   From   [" + tableName + "]";
                        myCommand = new OleDbDataAdapter(strExcel, conn);
                        ds = new DataSet();
                        ds.Clear();
                        myCommand.Fill(ds, tableName);
                        readDataTable = ds.Tables[0];
                        conn.Close();
                        this.label2.Text = sheetName;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("選擇的檔案匯入錯誤,請核實匯入的格式是否正確:錯誤資訊\n\r"+ex.Message);
            }
            finally
            {
            }


            
            return readDataTable;
        }


        private void bttSDDataTime_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.OpenFileDialog fd = new OpenFileDialog();//彈出選擇對話方塊
            if (fd.ShowDialog() == DialogResult.OK)//選擇了需要匯入的檔案
            {
                this.label1.Text = fd.SafeFileName.ToString();//選擇的檔名
                
                DataTable dt = ReadFile(fd.FileName);
                this.dataGridView1.DataSource = dt;
                //ExcelToDataGridView1();     
            }   
        }
        //將excel中的sheet1匯入到dataGridView1中 ,或者匯入到DataTable
        public DataTable ExcelToDataGridView1()
        {            
            OleDbDataAdapter myCommand = null;
            OleDbConnection conn = null;
            DataTable dt = null;
            DataSet ds = new DataSet();             
            try
            {
                System.Windows.Forms.OpenFileDialog fd = new OpenFileDialog();//彈出選擇對話方塊
                if (fd.ShowDialog() == DialogResult.OK)//選擇了需要匯入的檔案
                {
                    //string strConn = "Provider=Microsoft.Jet.OleDb.4.0;" + "data source=" + Server.MapPath("ExcelFiles/MyExcelFile.xls") + ";Extended Properties='Excel 8.0; HDR=Yes; IMEX=1'"; 
                    //此連線只能操作Excel2007之前(.xls)檔案
                    //string strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + excelFile.MapPath("ExcelFiles/Mydata2007.xlsx") + ";Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'"; 
                    //此連線可以操作.xls與.xlsx檔案 (支援Excel2003 和 Excel2007 的連線字串)          
                    //備註: "HDR=yes;"是說Excel檔案的第一行是列名而不是資料,"HDR=No;"正好與前面的相反。
                    //      "IMEX=1 "如果列中的資料型別不一致,使用"IMEX=1"可必免資料型別衝突。                                                                                                                                                                                             
                    //獲取全部資料  
                    //string exename =fd.FileName.ToString();//選擇中的檔案路徑和檔名
                    this.label1.Text = fd.SafeFileName.ToString();//選擇的檔名
                    string strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "Data Source=" + fd.FileName + ";" + "Extended Properties=Excel 8.0;  ";
                    conn=new OleDbConnection(strConn);
                    conn.Open();
                    DataTable dt2 = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);//獲取選中的EXECEL裡的所有工作簿
                    int dtname = dt2.Rows.Count-1; //提示dt2,表的第3列就是EXCEL所有工作簿的名字
                    string sheetName =dt2.Rows[dtname][2].ToString().Trim();//獲取EXECEL第一個工作簿的名字
                    string strExcel =string.Format("select * from [{0}]", sheetName);
                    myCommand = new OleDbDataAdapter(strExcel, strConn);
                    myCommand.Fill(ds, sheetName);
                    this.dataGridView1.DataSource = ds.Tables[0].DefaultView;                    
                    dt = ds.Tables[0] as DataTable;
                    
                    conn.Close();
                    this.label2.Text = sheetName;//選擇的檔名
                }
            }
            catch (Exception ex)
            {
               MessageBox.Show("匯入EXCEL資料異常:"+ex.Message);                
            }
            finally
            {
               
            }
            return dt;
            // 3、需要使用的時候從dataset呼叫即可。
            //例如得到excel中第i行第0列的資料的語句為:myDs.Tables[0].Rows[i].ItemArray[0].ToString()  注意都是從0開始的。
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            this.label1.Text = "";
            this.label2.Text = "";
        }


        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {


        }


        //END
    }
}