private void btnDaochu_Click(object sender, EventArgs e)
{
//导出Excel表
Microsoft.Office.Interop.Excel._Application excel = new Microsoft.Office.Interop.Excel.Application();
if (dataGridView1.Rows.Count == 0)
{
return;
}
//实例化一个Excel.Applaction对象
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.DefaultExt = "xls";
saveFileDialog.Filter = "Excel文件(*.xls)|*.xls";
saveFileDialog.ShowDialog();
string filepath = saveFileDialog.FileName;
if (filepath.ToString().Length < 1)
{
return;
}
else
{
//让后台执行设置为不可见,为true的话会看到打开一个Excel,然后数据在往里写
excel.Visible = false;
//新增加一个工作簿,Workbook是直接保存,不会弹出保存对话框,加上Application会弹出保存对话框,值为false会报错
//使用此方法在导出是不会占用进程
Workbooks workbooks = excel.Workbooks;
_Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
设置禁止弹出保存和覆盖的询问提示框
excel.DisplayAlerts = false;
excel.AlertBeforeOverwriting = false;
this.progressBar1.Visible = true;//设置进度条的可见性
this.progressBar1.Minimum = 0;//最小值
this.progressBar1.Maximum = dataGridView1.RowCount;//最大值
//生成Excel中列头名称
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
excel.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText;
}
//把DataGridView当前页的数据保存在Excel中
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
excel.Cells[i + 2, j + 1] = dataGridView1[j, i].Value.ToString();
}
this.progressBar1.Value += 1;
this.progressBar1.Refresh();
}
workbook.SaveCopyAs(filepath);
workbook.Saved = true;
excel.UserControl = false;
excel.Quit();
MessageBox.Show("导出成功!!");
}
}