首页 > 开发 > 综合 > 正文

C#操作Excel(导入导出)

2024-07-21 02:17:54
字体:
来源:转载
供稿:网友
 

前些日子,有很多朋友说需要c#导出到excel的代码,现共享给大家

/// <summary>
  /// 读取excel文档
  /// </summary>
  /// <param name="path">文件名称</param>
  /// <returns>返回一个数据集</returns>
  public dataset exceltods(string path)
  {
   string strconn = "provider=microsoft.jet.oledb.4.0;" +"data source="+ path +";"+"extended properties=excel 8.0;";
   oledbconnection conn = new oledbconnection(strconn);
   conn.open(); 
   string strexcel = "";  
   oledbdataadapter mycommand = null;
   dataset ds = null;
   strexcel="select * from [sheet1$]";
   mycommand = new oledbdataadapter(strexcel, strconn);
   ds = new dataset();
   mycommand.fill(ds,"table1");  
   return ds;
  }

/// <summary>
  /// 写入excel文档
  /// </summary>
  /// <param name="path">文件名称</param>
  public bool savefp2toexcel(string path)
  {
   try
   {
    string strconn = "provider=microsoft.jet.oledb.4.0;" +"data source="+ path +";"+"extended properties=excel 8.0;";
    oledbconnection conn = new oledbconnection(strconn);
    conn.open(); 
    system.data.oledb.oledbcommand cmd=new oledbcommand ();
    cmd.connection =conn;
    //cmd.commandtext ="update [sheet1$] set 姓名='2005-01-01' where 工号='日期'";
    //cmd.executenonquery ();
    for(int i=0;i<fp2.sheets [0].rowcount -1;i++)
    {
     if(fp2.sheets [0].cells[i,0].text!="")
     {
      cmd.commandtext ="insert into [sheet1$] (工号,姓名,部门,职务,日期,时间) values('"+fp2.sheets [0].cells[i,0].text+ "','"+
       fp2.sheets [0].cells[i,1].text+"','"+fp2.sheets [0].cells[i,2].text+"','"+fp2.sheets [0].cells[i,3].text+
       "','"+fp2.sheets [0].cells[i,4].text+"','"+fp2.sheets [0].cells[i,5].text+"')";
      cmd.executenonquery ();
     }
    }
    conn.close ();
    return true;
   }
   catch(system.data.oledb.oledbexception ex)
   {
    system.diagnostics.debug.writeline ("写入excel发生错误:"+ex.message );
   }
   return false;
  }

这种方法目前最有效,如果有不明白的地方可以来信交流

a

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表