日期:2014-05-18 浏览次数:21396 次
public void ExportDataGridView(DataGridView srcDgv) { SaveFileDialog sfile = new SaveFileDialog(); sfile.AddExtension = true; sfile.DefaultExt = ".doc"; sfile.Filter = "(*.doc)|*.doc"; if (sfile.ShowDialog() == DialogResult.OK) { object path = sfile.FileName; Object none = System.Reflection.Missing.Value; Word.Application wordApp = new Word.Application(); Word.Document document = wordApp.Documents.Add(ref none, ref none, ref none, ref none); //建立表格 Word.Table table = document.Tables.Add(document.Paragraphs.Last.Range, srcDgv.Rows.Count , srcDgv.Columns.Count, ref none, ref none); try { for (int i = 0; i < srcDgv.Columns.Count; i++)//设置标题 { table.Cell(0, i + 1).Range.Text = srcDgv.Columns[i].HeaderText; } for (int i = 1; i < srcDgv.Rows.Count; i++)//填充数据 { for (int j = 0; j < srcDgv.Columns.Count; j++) { table.Cell(i+1, j + 1).Range.Text = srcDgv[j, i - 1].Value.ToString(); } } 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); } finally { wordApp.Quit(ref none, ref none, ref none); } } }