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

C#中DataGridView导出Excel的两种方法

程序员文章站 2022-10-01 19:10:48
第一种是用数据流导出:#region savefiledialog savefiledialog = new savefiledialog(); savefiledialog.fi...

第一种是用数据流导出:

#region
      savefiledialog savefiledialog = new savefiledialog();
      savefiledialog.filter = "execl files (*.xls)|*.xls";
      savefiledialog.filterindex = 0;
      savefiledialog.restoredirectory = true;
      savefiledialog.createprompt = true;
      savefiledialog.title = "export excel file";
      savefiledialog.showdialog();
      if (savefiledialog.filename == "")
        return;
      stream mystream;
      mystream = savefiledialog.openfile();
      streamwriter sw = new streamwriter(mystream, system.text.encoding.getencoding(-0));
 
      string str = "";
      try
      {
        for (int i = 0; i < datagridview1.columncount; i++)
        {
          if (i > 0)
          {
            str += "\t";
          }
          str += datagridview1.columns[i].headertext;
        }
        sw.writeline(str);
        for (int j = 0; j < datagridview1.rows.count; j++)
        {
          string tempstr = "";
          for (int k = 0; k < datagridview1.columns.count; k++)
          {
            if (k > 0)
            {
              tempstr += "\t";
            }
            tempstr += datagridview1.rows[j].cells[k].value.tostring();
          }
          sw.writeline(tempstr);
        }
        sw.close();
        mystream.close();
      }
 
      catch (exception ex)
      {
        //messagebox.show(ex.tostring());
      }
      finally
      {
        sw.close();
        mystream.close();
      }
#endregion

这种方法的优点就是导出比较快,但是excel的表格里面设置标题,字体样式等都不能弄,因为你是用数据流直接导出为excel的,除非你能在数据流中设置这些样式,这个我还没这本事,哪位大哥会的教一下...嘿嘿

第二种方法是直接写一个类,这个类直接操作excel的:

using system;
using system.collections.generic;
using system.windows.forms;
using system.text;
using system.diagnostics;
using system.io;
using microsoft.office.interop.excel;
 
namespace excel
{
  public class export
  {
    /// <summary>
    /// datagridview导出excel
    /// </summary>
    /// <param name="strcaption">excel文件中的标题</param>
    /// <param name="mydgv">datagridview 控件</param>
    /// <returns>0:成功;1:datagridview中无记录;2:excel无法启动;9999:异常错误</returns>
    public int exportexcel(string strcaption, datagridview mydgv, savefiledialog savefiledialog)
    {
      int result = 9999;
      
      //保存
      
      savefiledialog.filter = "execl files (*.xls)|*.xls";
      savefiledialog.filterindex = 0;
      savefiledialog.restoredirectory = true;
      //savefiledialog.createprompt = true;
      savefiledialog.title = "export excel file";
      if ( savefiledialog.showdialog()== dialogresult.ok)
      {
        if (savefiledialog.filename == "")
        {
          messagebox.show("请输入保存文件名!");
          savefiledialog.showdialog();
        }
          // 列索引,行索引,总列数,总行数
        int colindex = 0;
        int rowindex = 0;
        int colcount = mydgv.columncount;
        int rowcount = mydgv.rowcount;
 
        if (mydgv.rowcount == 0)
        {
          result = 1;
        }
 
        // 创建excel对象
        microsoft.office.interop.excel.application xlapp = new microsoft.office.interop.excel.applicationclass();
        if (xlapp == null)
        {
          result = 2;
        }
        try
        {
          // 创建excel工作薄
          microsoft.office.interop.excel.workbook xlbook = xlapp.workbooks.add(true);
          microsoft.office.interop.excel.worksheet xlsheet = (microsoft.office.interop.excel.worksheet)xlbook.worksheets[1];
          // 设置标题
          microsoft.office.interop.excel.range range = xlsheet.get_range(xlapp.cells[1, 1], xlapp.cells[1, colcount]); //标题所占的单元格数与datagridview中的列数相同
          range.mergecells = true;
          xlapp.activecell.formular1c1 = strcaption;
          xlapp.activecell.font.size = 20;
          xlapp.activecell.font.bold = true;
          xlapp.activecell.horizontalalignment = microsoft.office.interop.excel.constants.xlcenter;
          // 创建缓存数据
          object[,] objdata = new object[rowcount + 1, colcount];
          //获取列标题
          foreach (datagridviewcolumn col in mydgv.columns)
          {
            objdata[rowindex, colindex++] = col.headertext;
          }
          // 获取数据
          for (rowindex = 1; rowindex < rowcount; rowindex++)
          {
            for (colindex = 0; colindex < colcount; colindex++)
            {
              if (mydgv[colindex, rowindex - 1].valuetype == typeof(string)
                || mydgv[colindex, rowindex - 1].valuetype == typeof(datetime))//这里就是验证datagridview单元格中的类型,如果是string或是datatime类型,则在放入缓存时在该内容前加入" ";
              {
                objdata[rowindex, colindex] = "" + mydgv[colindex, rowindex - 1].value;
              }
              else
              {
                objdata[rowindex, colindex] = mydgv[colindex, rowindex - 1].value;
              }
            }
            system.windows.forms.application.doevents();
          }
          // 写入excel
          range = xlsheet.get_range(xlapp.cells[2, 1], xlapp.cells[rowcount, colcount]);
          range.value2 = objdata;
 
          xlbook.saved = true;
          xlbook.savecopyas(savefiledialog.filename);
        }
        catch (exception err)
        {
          result = 9999;
        }
        finally
        {
          xlapp.quit();
          gc.collect(); //强制回收
        }
        //返回值
        result = 0;
      }
      
      return result;
    }
 
 
  }
}

这个优点是能设置样式什么的。缺点就是导出速度慢...

以上两种方法都是参考了很多料的..写在这里以便于相互学习..

补充一下:用第二种方法导出excel会有格式方面的变化,比如身份证号码按科学计算法导出了,不是按原先的模型

改进方法是在写入excel时添加一个格式声明:range.numberformatlocal = "@";

如:// 写入excel

range = xlsheet.get_range(xlapp.cells[2, 1], xlapp.cells[rowcount + 2, colcount]);
range.numberformatlocal = "@";
range.value2 = objdata;

到此这篇关于c#中datagridview导出excel的两种方法的文章就介绍到这了,更多相关c# datagridview导出excel内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!