欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# Winform实现导入和导出Excel文件

程序员文章站 2023-12-14 09:59:58
本文实例为大家分享了winform实现导入导出excel文件的具体代码,供大家参考,具体内容如下 /// /// 导出e...

本文实例为大家分享了winform实现导入导出excel文件的具体代码,供大家参考,具体内容如下

/// <summary>
    /// 导出excel文件
    /// </summary>
    /// /// <param name="dataset"></param>
    /// <param name="datatable">数据集</param>
    /// <param name="isshowexcle">导出后是否打开文件</param>
    /// <returns></returns>
    public static bool datatabletoexcel(string filepath, system.data.datatable datatable, bool isshowexcle)
    {
      //system.data.datatable datatable = dataset.tables[0];
      int rownumber = datatable.rows.count;
      int columnnumber = datatable.columns.count;
      int colindex = 0;
 
      if (rownumber == 0)
      {
        return false;
      }
 
      microsoft.office.interop.excel.application excel = new microsoft.office.interop.excel.application();
      microsoft.office.interop.excel.workbook workbook = excel.workbooks.add(microsoft.office.interop.excel.xlwbatemplate.xlwbatworksheet);
      microsoft.office.interop.excel.worksheet worksheet = (microsoft.office.interop.excel.worksheet)workbook.worksheets[1];
      excel.visible = isshowexcle;
      microsoft.office.interop.excel.range range;
 
 
      foreach (datacolumn col in datatable.columns)
      {
        colindex++;
        excel.cells[1, colindex] = col.columnname;
      }
 
      object[,] objdata = new object[rownumber, columnnumber];
 
      for (int r = 0; r < rownumber; r++)
      {
        for (int c = 0; c < columnnumber; c++)
        {
          objdata[r, c] =datatable.rows[r][c];
        }
      }
 
      range = worksheet.get_range(excel.cells[2, 1], excel.cells[rownumber + 1, columnnumber]);
 
      range.value2 = objdata;
 
      range.numberformatlocal = "@";
 
      worksheet.saveas(filepath, type.missing, type.missing, type.missing, type.missing, type.missing, type.missing, type.missing, type.missing, type.missing);
 
      //excel.quit();
      return true;
    }

读取excel文件数据到datatable

 /// <summary>
    /// 读取excel文件数据到datatable
    /// </summary>
    /// <param name="filepath">excel文件路径</param>
    private void import_excel(string filepath)
    {
      string sqlconn = "provider=microsoft.jet.oledb.4.0;data source=" + filepath + ";extended properties='excel 8.0;hdr=false;imex=1'";
 
      string sql = @"select * from [sheet1$]";
 
      try
      {
        using (oledbconnection conn = new oledbconnection(sqlconn))
        {
          using (oledbdataadapter adapter = new oledbdataadapter(sql, conn))
          {
            system.data.datatable dt = new system.data.datatable();
            adapter.fill(dt);
 
            this.loaddatagridview(dt);
          }
        }
      }
      catch (exception ex)
      {
        messagebox.show("打开文件出错,错误信息:" + ex.message.tostring(), "提示");
      }
    }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:

下一篇: