DataGridView导出到Word
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | #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 |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步