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("表格中没有数据,无法导出数据!");