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#程序设计有所帮助。
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短