c#读取excel文件

读取Excel文件到DataSet中

  1.         /// <summary> 
  2.         /// 读取Excel文档 
  3.         /// </summary> 
  4.         /// <param name="Path">文件名称</param> 
  5.         /// <returns>返回一个数据集</returns> 
  6.         public DataSet ExcelToDS(string Path)
  7.         {
  8.             string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;";
  9.             OleDbConnection conn = new OleDbConnection(strConn);
  10.             conn.Open();
  11.             string strExcel = "";
  12.             OleDbDataAdapter myCommand = null;
  13.             DataSet ds = null;
  14.             strExcel = "select * from [Recovered_Sheet1$]";
  15.             myCommand = new OleDbDataAdapter(strExcel, strConn);
  16.             ds = new DataSet();
  17.             myCommand.Fill(ds);
  18.             return ds;
  19.         }

写入Excel文件

  1.     // <summary> 
  2.         // 写入Excel文档 
  3.         // <//summary> 
  4.         // <param name="Path">文件名称<//param> 
  5.         public bool SaveFP2toExcel(string Path)
  6.         {
  7.             try
  8.             {
  9.                 string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;";
  10.                 OleDbConnection conn = new OleDbConnection(strConn);
  11.                 conn.Open();
  12.                 System.Data.OleDb.OleDbCommand cmd = new OleDbCommand();
  13.                 cmd.Connection = conn;
  14.                 cmd.CommandText ="UPDATE [sheet1$] SET 姓名='2005-01-01' WHERE 工号='日期'"
  15.                 cmd.ExecuteNonQuery (); 
  16.                 for (int i = 0; i < fp2.Sheets[0].RowCount - 1; i++)
  17.                 {
  18.                     if (fp2.Sheets[0].Cells[i, 0].Text != "")
  19.                     {
  20.                         cmd.CommandText = "INSERT INTO [sheet1$] (工号,姓名,部门,职务,日期,时间) VALUES('" + fp2.Sheets[0].Cells[i, 0].Text + "','" +
  21.                         fp2.Sheets[0].Cells[i, 1].Text + "','" + fp2.Sheets[0].Cells[i, 2].Text + "','" + fp2.Sheets[0].Cells[i, 3].Text +
  22.                         "','" + fp2.Sheets[0].Cells[i, 4].Text + "','" + fp2.Sheets[0].Cells[i, 5].Text + "')";
  23.                         cmd.ExecuteNonQuery();
  24.                     }
  25.                 }
  26.                 conn.Close();
  27.                 return true;
  28.             }
  29.             catch (System.Data.OleDb.OleDbException ex)
  30.             {
  31.                 System.Diagnostics.Debug.WriteLine("写入Excel发生错误:" + ex.Message);
  32.             }
  33.             return false;
  34.         }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值