代码改变世界

Excel To dataSet

2018-12-05 15:47  Evan.Pei  阅读(249)  评论(0)    收藏  举报
private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog file = new OpenFileDialog();
            file.ShowDialog();
            DataSet ds=ExcelToDS(file.FileName);//文件路径
            textBox1.Text=DataSetToJson(ds);
        }


        //访问Excel文件,excel转 DataSet
        public static DataSet ExcelToDS(string Path)
        {
            string strConn_1 = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'", Path);
            using (OleDbConnection conn_1 = new OleDbConnection(strConn_1))
            {
                conn_1.Open();
                string strExcel = "";
                strExcel = "select * from [sheet1$]";//$A:B
                using (OleDbDataAdapter myCommand_1 = new OleDbDataAdapter(strExcel, strConn_1))
                {
                    using (DataSet ds1 = new DataSet())
                    {
                        myCommand_1.Fill(ds1, "table1");

                        myCommand_1.Dispose();
                        conn_1.Dispose();
                        conn_1.Close();
                        return ds1;
                    }
                }
            }
        }