if (dgvResult.Rows.Count == 0)
{
MessageBox.Show("列表为空");
}
//创建Excel对象
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Application.Workbooks.Add(true);
// 生成字段名称
excel.Cells[1, 1] = "序号";
excel.Cells[1, 2] = "年龄";
excel.Cells[1, 3] = "家庭人数";
excel.Cells[1, 4] = "平均收入";
excel.Cells[1, 5] = "婚姻状况";
excel.Cells[1, 6] = "孩子状况";
excel.Cells[1, 7] = "户口状况";
excel.Cells[1, 8] = "学历等级";
excel.Cells[1, 9] = "购房指数";
excel.Cells[1, 10] = "预期购房指数";
excel.Cells[1, 11] = "是否购房";
//填充数据
for (int i = 0; i < dgvResult.RowCount - 1; i++) //循环行
{
for (int j = 0; j < dgvResult.ColumnCount; j++) //循环列
{
if (dgvResult[j, i].ValueType == typeof(string))
{
excel.Cells[i + 2, j + 1] = "‘" + dgvResult.Rows[i].Cells[j].Value.ToString();
}
else
{
excel.Cells[i + 2, j + 1] = dgvResult.Rows[i].Cells[j].Value.ToString();
}
}
}
//设置禁止弹出保存和覆盖的询问提示框
excel.Visible = false;
excel.DisplayAlerts = false;
excel.AlertBeforeOverwriting = false;
//保存文件
excel.Save(fBD.SelectedPath + "1234.xls");//fbd为folderbrowserdialog控件
MessageBox.Show("保存成功");
excel.Quit();
}
最后添加引用Microsoft.Office.Interop.Excel
引用网址:http://zhidao.baidu.com/link?url=-3gV9-vkonOId6ynayjW3sypaSFrzZCxaLdPaF6R1ELRjQVybyBDuzlHHSPtIVglsF1atAoJBvRyWlH0oWbTnK
winform导出datagridview数据到excle