public void DataGridViewToWord(DataGridView dgv)
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.DefaultExt = "doc ";
dlg.Filter = "WORD文件(*.DOC)|*.doc ";
dlg.InitialDirectory = Directory.GetCurrentDirectory();
if (dlg.ShowDialog() == DialogResult.Cancel)
{
return;
}
string fileNameString = dlg.FileName;
if (fileNameString.Trim() == " ")
{
return;
}
Object path = fileNameString;
Object none = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document document = wordApp.Documents.Add(ref none, ref none, ref none, ref none);
//建立表格
Microsoft.Office.Interop.Word.Table table = document.Tables.Add(document.Paragraphs.Last.Range, dgv.Rows.Count, dgv.Columns.Count, ref none, ref none);
try
{
int displayColumnsCount = 1;
for (int i = 0; i < dgv.Columns.Count; i++)
{
if (dgv.Columns[i].Visible)
{
table.Cell(0, displayColumnsCount).Range.Text = dgv.Columns[i].HeaderText.Trim();
displayColumnsCount++;
}
}
tempProgressBar.Refresh();
tempProgressBar.Visible = true;
tempProgressBar.Minimum = 1;
tempProgressBar.Maximum = dgv.Rows.Count;
tempProgressBar.Step = 5;
for (int row = 0; row < dgv.Rows.Count; row++)
{
if (row % 5 == 0)
{
tempProgressBar.PerformStep();
}
displayColumnsCount = 1;
for (int col = 0; col < dgv.Columns.Count; col++)
{
if (dgv.Columns[col].Visible)
{
try
{
table.Cell(row + 2, displayColumnsCount).Range.Text = dgv.Rows[row].Cells[col].Value.ToString().Trim();
displayColumnsCount++;
}
catch (Exception error)
{
MessageBox.Show(error.Message, "导出错误 ", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
}
}
}
tempProgressBar.Visible = false;
document.SaveAs(ref path, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none);
document.Close(ref none, ref none, ref none);
}
catch (Exception error)
{
MessageBox.Show(error.Message, "导出错误 ", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
finally
{
wordApp.Quit(ref none, ref none, ref none);
}
}