现在的位置: 首页 > 综合 > 正文

C#中怎么从如何将DataGridView中的数据导出到Excel中

2018年01月27日 ⁄ 综合 ⁄ 共 1057字 ⁄ 字号 评论关闭

private   void   menuItem16_Click(object   sender,   System.EventArgs   e)  
  {  
  ds.Tables["CurrentTable"].AcceptChanges();  
  this.Cursor=Cursors.WaitCursor;  
  Excel.Application   myExcel=new   Excel.Application();  
  myExcel.Application.Workbooks.Add(true);  
  myExcel.Visible=true;  
  myExcel.Cells[1,1]=this.dataGrid1.CaptionText;  
  //Object   Date[ds.Tables["CurrentTable"].Rows.Count][ds.Tables["CurrentTable"].Columns.Count];  
  //生成标题  
  for(int   i=0;i<ds.Tables["CurrentTable"].Columns.Count;i++)  
  {  
  myExcel.Cells[2,i+1]=ds.Tables["CurrentTable"].Columns[i].Caption;  
  }  
  //填充数据  
  for(int   i=0;i<ds.Tables["CurrentTable"].Rows.Count;i++)  
  {  
  for(int   j=0;j<ds.Tables["CurrentTable"].Columns.Count;j++)  
  {  
  if(ds.Tables["CurrentTable"].Rows[i][j].GetType()==typeof(System.String))  
   
  {  
   
  myExcel.Cells[i+3,j+1]="'"+ds.Tables["CurrentTable"].Rows[i][j].ToString();  
  }  
  else  
  {  
  myExcel.Cells[i+3,j+1]=ds.Tables["CurrentTable"].Rows[i][j].ToString();  
  }  
  }  
  }  
   
  this.Cursor=Cursors.Default;  
  MessageBox.Show("导出成功!                               ","恭喜",MessageBoxButtons.OK,MessageBoxIcon.Asterisk);  
  }

抱歉!评论已关闭.