[C#] C#创建、读取和修改Excel →→→→→进入此内容的聊天室

来自 , 2020-09-16, 写在 C#, 查看 141 次.
URL http://www.code666.cn/view/a376802c
  1. // Namespaces, Variables, and Constants
  2. using System;
  3. using System.Configuration;
  4. using System.Data;
  5.  
  6. private OleDbDataAdapter da;
  7. private DataTable dt;
  8.  
  9. private void Excel_Load(object sender, System.EventArgs e)
  10. {
  11.     // Create the DataAdapter.
  12.     da = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", ConfigurationSettings.AppSettings["ExcelConnectString1"]);
  13.  
  14.     // Create the insert command.
  15.     String insertSql = "INSERT INTO [Sheet1$] (CategoryID, CategoryName, Description) VALUES (?, ?, ?)";
  16.     da.InsertCommand = new OleDbCommand(insertSql, da.SelectCommand.Connection);
  17.     da.InsertCommand.Parameters.Add("@CategoryID", OleDbType.Integer, 0, "CategoryID");
  18.     da.InsertCommand.Parameters.Add("@CategoryName", OleDbType.Char, 15, "CategoryName");
  19.     da.InsertCommand.Parameters.Add("@Description", OleDbType.VarChar, 100, "Description");
  20.  
  21.     // Create the update command.
  22.     String updateSql = "UPDATE [Sheet1$] SET CategoryName=?, Description=? " WHERE CategoryID=?";
  23.    da.UpdateCommand = new OleDbCommand(updateSql, da.SelectCommand.Connection);
  24.    da.UpdateCommand.Parameters.Add("@CategoryName", OleDbType.Char, 15, "CategoryName");
  25.    da.UpdateCommand.Parameters.Add("@Description", OleDbType.VarChar, 100, "Description");
  26.    da.UpdateCommand.Parameters.Add("@CategoryID", OleDbType.Integer, 0, "CategoryID");
  27.  
  28.    // Fill the table from the Excel spreadsheet.
  29.    dt = new DataTable( );
  30.    da.Fill(dt);
  31.    // Define the primary key.
  32.    dt.PrimaryKey = new DataColumn[] {dt.Columns[0]};
  33.  
  34.    // Records can only be inserted using this technique.
  35.    dt.DefaultView.AllowDelete = false;
  36.    dt.DefaultView.AllowEdit = true;
  37.    dt.DefaultView.AllowNew = true;
  38.    // Bind the default view of the table to the grid.
  39.    dataGrid.DataSource = dt.DefaultView;
  40. }
  41. private void updateButton_Click(object sender, System.EventArgs e)
  42. {
  43.    da.Update(dt);
  44. }
  45. //csharp/7754

回复 "C#创建、读取和修改Excel"

这儿你可以回复上面这条便签

captcha