您的位置:首页 > 运维架构

.net对Excel表数据读写操作

2011-06-29 11:53 330 查看
            //读取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();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息