主要思路:在word文档中需要插入数据的地方添加书签,然后通过获取word文档中的书签添加文字/表格
引用包:Microsoft.Office.Interop.Word
Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();Microsoft.Office.Interop.Word.Document doc = new Microsoft.Office.Interop.Word.Document();object miss = System.Reflection.Missing.Value;DataTable dt_purCode = (DataTable)dataGridView1.DataSource; //需要插入word文档的表格数据string appPath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;//获取模板路径object templatePath = appPath + "Template\\Report - 副本.docx";Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application();object objDocType = Microsoft.Office.Interop.Word.WdDocumentType.wdTypeDocument;object objfalse = false;object objtrue = true;doc = (Microsoft.Office.Interop.Word.Document)appWord.Documents.Add(ref templatePath, ref objfalse, ref objDocType, ref objtrue);try{//获取模板中所有的书签Microsoft.Office.Interop.Word.Bookmarks odf = doc.Bookmarks;//在word文档 name 书签位置插入“张三”odf.get_Item("name").Range.Text = "张三";//在word文档 item书签位置插入表格数据Microsoft.Office.Interop.Word.Table dtWord = doc.Tables.Add(odf.get_Item("item").Range, dt_purCode.Rows.Count, dt_purCode.Columns.Count);dtWord.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleDot;dtWord.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleDot;//循环往表格里赋值for (int i = 1; i <= dt_purCode.Rows.Count; i++){for (int j = 1; j <= dt_purCode.Columns.Count; j++){dtWord.Rows[i].Cells[j].Range.Text = dt_purCode.Rows[i - 1][j - 1].ToString();dtWord.Rows[i].Cells[j].Range.Font.Size = 10; //设置表格字体 10//如果表格字段包含箭头 设置字体颜色为红色if (dt_purCode.Rows[i - 1][j - 1].ToString().Contains("↓") || dt_purCode.Rows[i - 1][j - 1].ToString().Contains("↑")){dtWord.Rows[i].Cells[j].Range.Font.TextColor.RGB = (int)Microsoft.Office.Interop.Word.WdColor.wdColorRed; }}}}catch{throw;}finally{doc.Close();application.Quit();}