C#弹出打开资源对话框(OpenFileDialog)并读取Excel表格(office2007或office2010)

最近需要把Excel表格里面的数据导入到数据库里面,就研究了一下Excle,怎样把所有表单里面的数据读取出来,下面是代码:

 private void button_leadIn_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Microsoft Excel files(*.xls)|*.xls;*.xlsx";//过滤一下,只要表格格式的
            ofd.InitialDirectory = "c:\\";
            ofd.RestoreDirectory = true;
            ofd.FilterIndex = 1;
            ofd.AddExtension = true;
            ofd.CheckFileExists = true;
            ofd.CheckPathExists = true;
            ofd.ShowHelp = true;//是否显示帮助按钮
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                string DBString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source =" + ofd.FileName +";Extended Properties=Excel 12.0";
                OleDbConnection con = new OleDbConnection(DBString);
                con.Open();
                DataTable datatable = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

                //获取表单,原始的是:Sheet1,Sheet2,Sheet3
                for (int i = 0; i < datatable.Rows.Count; i++)
                {

                    //获取表单的名字
                    String sheet = datatable.Rows[i][2].ToString().Trim();
                    OleDbDataAdapter ole = new OleDbDataAdapter("select * from ["+sheet+"]", con);
                    DataSet ds = new DataSet();
                    ole.Fill(ds);

                   //输出表格里面的内容,我这里就两列数据,如果数据列数不确定就需要写循环了:Rows.Count
                    foreach (DataRow col in ds.Tables[0].Rows)
                    {
                        Console.WriteLine(col[0].ToString());
                        Console.WriteLine(col[1].ToString());
                    }
                }
                con.Close();
            }
        }

你可能感兴趣的:(C#学习)