.net对Excel表数据读写操作

来源:互联网 发布:战地3低配置优化补丁 编辑:程序博客网 时间:2024/04/30 22:19

            //读取Excel表数据

            string conStr ="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:/a.xls;Extended Properties='Excel 8.0;HDR=yes;IMEX=1;'";

                  //此连接仅可以操作.xls文件;HDR为yes时指Sheet第一行作为字段名

                  //当 IMEX=0 时为“汇出模式”,这个模式开启的 Excel 档案只能用来做“写入”用途。
                  //当 IMEX=1 时为“汇入模式”,这个模式开启的 Excel 档案只能用来做“读取”用途。
                  //当 IMEX=2 时为“连結模式”,这个模式开启的 Excel 档案可同时支援“读取”与“写入”用途。

            string conStr =
                "Provider=Microsoft.Ace.OLEDB.12.0;Data Source=D:/a.xls;Extended Properties='Excel 12.0;HDR=yes;IMEX=1;';"; //此连接可以操作.xls与.xlsx文件
            OleDbConnection conn=new OleDbConnection(conStr);
            string sql = string.Format("select * from [{0}$]", "sht001"); //sht001 Sheet标签页名称
            OleDbDataAdapter da=new OleDbDataAdapter(sql,conStr);
            DataSet ds = new DataSet();

            conn.Open();
            da.Fill(ds);
            dataGridView1.DataSource = ds.Tables[0].DefaultView;

  

 

            //写入数据

            string conStr ="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:/a.xls;Extended Properties=Excel 8.0;";
            OleDbConnection conn = new OleDbConnection(conStr);
            //添加数据

            string sqlInsert = string.Format("insert into [{0}$] values ('9','孟子','UUUKKK')", "sht001");

            //更新数据

            string sqlInsert = string.Format("update [{0}$] set name='孔子' where name='孟子'", "sht001");
            OleDbCommand com=new OleDbCommand(sqlInsert,conn);
            conn.Open();
            com.ExecuteNonQuery();
            conn.Close();

原创粉丝点击