C#创建、读取和修改Excel的方法
本文实例讲述了C#创建、读取和修改Excel的方法。分享给大家供大家参考。具体如下:
windows下我们可以通过JetOLEDB访问Excel,就行访问数据库一样
//Namespaces,Variables,andConstants usingSystem; usingSystem.Configuration; usingSystem.Data; privateOleDbDataAdapterda; privateDataTabledt; privatevoidExcel_Load(objectsender,System.EventArgse) { //CreatetheDataAdapter. da=newOleDbDataAdapter("SELECT*FROM[Sheet1$]",ConfigurationSettings.AppSettings["ExcelConnectString1"]); //Createtheinsertcommand. StringinsertSql="INSERTINTO[Sheet1$](CategoryID,CategoryName,Description)VALUES(?,?,?)"; da.InsertCommand=newOleDbCommand(insertSql,da.SelectCommand.Connection); da.InsertCommand.Parameters.Add("@CategoryID",OleDbType.Integer,0,"CategoryID"); da.InsertCommand.Parameters.Add("@CategoryName",OleDbType.Char,15,"CategoryName"); da.InsertCommand.Parameters.Add("@Description",OleDbType.VarChar,100,"Description"); //Createtheupdatecommand. StringupdateSql="UPDATE[Sheet1$]SETCategoryName=?,Description=?"WHERECategoryID=?"; da.UpdateCommand=newOleDbCommand(updateSql,da.SelectCommand.Connection); da.UpdateCommand.Parameters.Add("@CategoryName",OleDbType.Char,15,"CategoryName"); da.UpdateCommand.Parameters.Add("@Description",OleDbType.VarChar,100,"Description"); da.UpdateCommand.Parameters.Add("@CategoryID",OleDbType.Integer,0,"CategoryID"); //FillthetablefromtheExcelspreadsheet. dt=newDataTable(); da.Fill(dt); //Definetheprimarykey. dt.PrimaryKey=newDataColumn[]{dt.Columns[0]}; //Recordscanonlybeinsertedusingthistechnique. dt.DefaultView.AllowDelete=false; dt.DefaultView.AllowEdit=true; dt.DefaultView.AllowNew=true; //Bindthedefaultviewofthetabletothegrid. dataGrid.DataSource=dt.DefaultView; } privatevoidupdateButton_Click(objectsender,System.EventArgse) { da.Update(dt); }
希望本文所述对大家的C#程序设计有所帮助。