#region 使用Interop.Word.dll将DataGridView导出到Word /// <summary> /// 使用Interop.Word.dll将DataGridView导出到Word /// </summary> /// <param name="dGV"></param> /*保会通财务软件公司*/ public static void DataGridViewExportToWord_WordDll(DataGridView dGV) { Microsoft.Office.Interop.Word.Document mydoc = new Microsoft.Office.Interop.Word.Document(); //实例化Word文档对象 Word.Table mytable; //声明Word表格 Word.Selection mysel; //声明Word选区 Object myobj; if (dGV.Rows.Count == 0) return; //建立Word对象 Word.Application word = new Word.Application(); myobj = System.Reflection.Missing.Value; mydoc = word.Documents.Add(ref myobj, ref myobj, ref myobj, ref myobj); word.Visible = true; mydoc.Select(); mysel = word.Selection; //将数据生成Word表格文件 mytable = mydoc.Tables.Add(mysel.Range, dGV.RowCount, dGV.ColumnCount, ref myobj, ref myobj); //设置列宽 mytable.Columns.SetWidth(80, Word.WdRulerStyle.wdAdjustNone); //mytable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleThickThinLargeGap; mytable.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle; mytable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle; //输出列标题数据 for (int i = 0; i < dGV.ColumnCount; i++) { mytable.Cell(1, i + 1).Range.InsertAfter(dGV.Columns[i].HeaderText); } //输出控件中的记录 for (int i = 0; i < dGV.RowCount - 1; i++) { for (int j = 0; j < dGV.ColumnCount; j++) { mytable.Cell(i + 2, j + 1).Range.InsertAfter(dGV[j, i].FormattedValue.ToString()); } } GC.Collect(); } #endregion