C#操作excel高手进
我这样连接并读取EXCEL,想问下,要想修改excel某个表的值,怎么写代码,麻烦大大给写个例子,比如想改phone2 = Convert.ToString(ds.Tables[0].Rows[num][4]);
string strConn = "Provider=Microsoft.Jet.Oledb.4.0;Data Source=" + label1.Text + ";Extended Properties=Excel 8.0";
string strComm = "SELECT * FROM [Sheet1$]";
OleDbConnection myConn = new OleDbConnection(strConn);
myConn.Open();
OleDbDataAdapter myAdp = new OleDbDataAdapter(strComm, strConn);
DataSet ds = new DataSet();
myAdp.Fill(ds);
myConn.Close();
DataTable table = ds.Tables[0];
int num = Int32.Parse(textBox6.Text)-1;
string strname = string.Empty;
string strphone = string.Empty;
string strid = string.Empty;
string strliuyan = string.Empty;
string phone2 = string.Empty;
strname = Convert.ToString(ds.Tables[0].Rows[num][0]);
strphone = Convert.ToString(ds.Tables[0].Rows[num][1]);
strid = Convert.ToString(ds.Tables[0].Rows[num][2]);
strliuyan = Convert.ToString(ds.Tables[0].Rows[num][3]);
phone2 = Convert.ToString(ds.Tables[0].Rows[num][4]);
------解决方案--------------------
你以这种方式访问excel文件的时候,可以把excel文件当成个数据库,直接update就可以了
比如你要改第一行phone2的值可以这样:
C# code
string strComm = "update [Sheet1$] set phone2='6666666' where id = 1";
OleDbConnection myConn = new OleDbConnection(strConn);
myConn.Open();
OleDbCommand com = new OleDbCommand(strComm, myConn);
com.ExecuteNonQuery();
myConn.Close();