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 夜雨祝福语简短10字
16 蛋糕祝福语简短闺蜜
17 部门过年祝福语简短独特
18 简短精炼的结婚祝福语