C#操作Excel(导入导出)

  1. class ExampleOfLegalsoft   
  2. {   
  3.     /// <summary>    
  4.     /// 读取Excel文档    
  5.     /// </summary>    
  6.     /// <param name="Path">文件名称</param>    
  7.     /// <returns>返回一个数据集</returns>    
  8.     public DataSet ExcelToDS(string Path)   
  9.     {   
  10.         string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;";   
  11.         OleDbConnection conn = new OleDbConnection(strConn);   
  12.         conn.Open();   
  13.         string strExcel = "";   
  14.         OleDbDataAdapter myCommand = null;   
  15.         DataSet ds = null;   
  16.         strExcel = "select * from [sheet1$]";   
  17.         myCommand = new OleDbDataAdapter(strExcel, strConn);   
  18.         ds = new DataSet();   
  19.         myCommand.Fill(ds, "table1");   
  20.         return ds;   
  21.     }   
  22.     /// <summary>    
  23.     /// 写入Excel文档    
  24.     /// </summary>    
  25.     /// <param name="Path">文件名称</param>    
  26.     public bool SaveFP2toExcel(string Path)   
  27.     {   
  28.         try  
  29.         {   
  30.             string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;";   
  31.             OleDbConnection conn = new OleDbConnection(strConn);   
  32.             conn.Open();   
  33.             System.Data.OleDb.OleDbCommand cmd = new OleDbCommand();   
  34.             cmd.Connection = conn;   
  35.             //cmd.CommandText ="UPDATE [sheet1$] SET 姓名="2005-01-01" WHERE 工号="日期"";    
  36.             //cmd.ExecuteNonQuery ();    
  37.             for (int i = 0; i < fp2.Sheets[0].RowCount - 1; i++)   
  38.             {   
  39.                 if (fp2.Sheets[0].Cells[i, 0].Text != "")   
  40.                 {   
  41.                     cmd.CommandText = "INSERT INTO [sheet1$] (工号,姓名,部门,职务,日期,时间) VALUES(" + fp2.Sheets[0].Cells[i, 0].Text + "," +   
  42.                     fp2.Sheets[0].Cells[i, 1].Text + "," + fp2.Sheets[0].Cells[i, 2].Text + "," + fp2.Sheets[0].Cells[i, 3].Text +   
  43.                     "," + fp2.Sheets[0].Cells[i, 4].Text + "," + fp2.Sheets[0].Cells[i, 5].Text + ")";   
  44.                     cmd.ExecuteNonQuery();   
  45.                 }   
  46.             }   
  47.             conn.Close();   
  48.             return true;   
  49.         }   
  50.         catch (System.Data.OleDb.OleDbException ex)   
  51.         {   
  52.             System.Diagnostics.Debug.WriteLine("写入Excel发生错误:" + ex.Message);   
  53.         }   
  54.         return false;   
  55.     }   
原文地址:https://www.cnblogs.com/bluedy1229/p/1431576.html