public bool DataGridviewToExcel(DataGridView dtgv, bool isShowExcel)
{
if (dtgv.Rows.Count == 0)
{
return false;
}
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Application.Workbooks.Add(true);
excel.Visible = isShowExcel;
for (int i = 0; i < dtgv.ColumnCount; i++)
{
excel.Cells[1,i + 1] = dtgv.Columns[i].HeaderText;
}
for (int i = 0; i < dtgv.ColumnCount - 1; i++)
{
for (int j = 0; j < dtgv.ColumnCount; j++)
{
excel.Cells[i + 2, j + 1] = dtgv[j, i].Value.ToString();
}
}
return true;
}
private void 另存为ToolStripMenuItem2_Click(object sender, EventArgs e)
{
DataGridviewToExcel(dataGridView1, true);
}

