码迷,mamicode.com
首页 > Windows程序 > 详细

C# DataGridView导出Excel

时间:2014-11-13 14:44:36      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:datagridview   blog   http   io   ar   os   sp   for   数据   

using Microsoft.Office.Interop.Excel;               
using Excel=Microsoft.Office.Interop.Excel;

    //这里Excel和Interop报错,请参考我的另一篇http://blog.csdn.net/xtfnpgy/article/details/41076849


 public bool ExportDataGridview(DataGridView gridView,string str_path)

    {
      if(gridView.Rows.Count==0)
        return false;
      //建立Excel对象
      Excel.Application excel=new Excel.Application();
      excel.Application.Workbooks.Add(true);
      excel.Visible=false;
      //生成字段名称
      for(int i=0;i<gridView.ColumnCount;i++)
      {
        excel.Cells[1,i+1]=gridView.Columns[i].HeaderText;
      }
      //填充数据
      for(int i=0;i<gridView.RowCount-1;i++)
      {
        for(int j=0;j<gridView.ColumnCount;j++)
        {
          if(gridView[j,i].ValueType==typeof(string))
          {
            excel.Cells[i+2,j+1]="‘"+gridView[j,i].Value.ToString();
          }
          else
          {
            excel.Cells[i+2,j+1]=gridView[j,i].Value.ToString();
          }
        }
      }
      excel.SaveWorkspace(str_path);
      excel.Quit();
      excel=null;
      return true;

    }

调用:
 if(!ExportDataGridview(dataGridView1,"d:\\abc.xls"))
   MessageBox.Show("表格中没有数据,无法导出数据!");

C# DataGridView导出Excel

标签:datagridview   blog   http   io   ar   os   sp   for   数据   

原文地址:http://blog.csdn.net/xtfnpgy/article/details/41078063

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!