/// <summary> /// 表格中插入数据 /// </summary> /// <param name="fileName"></param> /// <param name="data"></param> public static Table AddTable(WordprocessingDocument wordDoc, TOffice office) { string[] data = new string[] { office.Name + "|" + office.NameEn, office.Address, office.AddressEn, "Tel:" + office.Telephone, "Fax:" + office.Fax }; var doc = wordDoc.MainDocumentPart.Document; Table table = new Table(); TableProperties tableProps = GetTableProperties(); //table properties table.AppendChild <TableProperties>(tableProps); for (var i = 0; i < data.Length; i++) { TableRow tr = new TableRow() { RsidTableRowAddition = "00BF0C52", RsidTableRowProperties = "001640FD" }; TableCell tc = new TableCell(); Paragraph p = new Paragraph(new ParagraphProperties(new SpacingBetweenLines() { Line = "140", LineRule = LineSpacingRuleValues.Exact })); Run run = new Run(); if (i == 0) { Drawing r = InsertAPicture(wordDoc, @"D:\mapicon.jpg"); run.Append(r); } RunProperties rPr = GetFontProperites(i + 1); //font properties run.AppendChild <RunProperties>(rPr); Text text = new Text(data[i]); run.Append(text); p.Append(run); tc.Append(p); //tc.Append(new TableCellProperties(new TableCellWidth { Type = TableWidthUnitValues.Auto })); tr.Append(tc); table.Append(tr); } return(table); // doc.Body.Append(table); // doc.Save(); }
static void Main(string[] args) { //创建文档 //CreateWordDoc(@"D:\Test.docx", "Hello World"); //写文档 //WriteToWordDoc(@"D:\Test.docx", "测试1"); //插入Table //InsertTableInDoc(@"D:\Test.docx"); //读取文档 //string contentDoc = GetCommentsFromDocument(@"D:\Test.docx"); //替换书签 //ModifyBM(@"D:\Test.docx", "test","这是测试"); //查找书签 //WordprocessingDocument doc = WordprocessingDocument.Open(@"D:\LegalServiceTemplate.docx", true); // BookmarkStart bs = findBookMarkStart(doc, "table_test"); //在表格中插入数据 //const string fileName = @"D:\Test.docx"; //AddTable(fileName, new string[,] // { { "Texas", "TX","dc" }, // { "California", "CA","dd" }, // { "New York", "NY","" }, // { "Massachusetts", "MA","cy" } } //); //查找书签 //AddTableByBookMark(@"D:\Test.docx", data, "table_Address"); //AddTable(@"D:\test.docx", data); //string document = @"D:\Test.docx"; //string fileName = @"D:\mapicon.jpg"; //InsertAPicture(document, fileName); //测试模板页面 using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(@"D:\test1.docx", true)) { TOffice office = new TOffice(); var lst = office.GetListTOffice(); //2.根据书签获取word位置信息 BookmarkStart bmAddress1 = findBookMarkStart(wordDoc, "table_Address1"); BookmarkStart bmAddress2 = findBookMarkStart(wordDoc, "table_Address2"); //3.创建表格填充数据 int i = 0; foreach (var item in lst) { i++; if (i % 2 != 0) { Table tb = AddTable(wordDoc, item); bmAddress1.Parent.InsertAfterSelf(tb); //add table at bookmark } else { Table tb = AddTable(wordDoc, item); bmAddress2.Parent.InsertAfterSelf(tb); //add table at bookmark } } } }