public void ChangeLastNameForSecondRow(string pFileName, string pTextValue) { var fileName = Path.Combine(DocumentFolder, pFileName); if (!File.Exists(fileName)) { CreateDocumentWithTableFromArray(fileName); } // Open our document, second parameter indicates edit more using (var document = WordprocessingDocument.Open(fileName, true)) { // Get the sole table in the document Table table = document.MainDocumentPart.Document.Body.Elements <Table>().First(); // Find the second row in the table. TableRow row = table.Elements <TableRow>().ElementAt(1); // Find the second cell in the row. TableCell cell = row.Elements <TableCell>().ElementAt(1); // Find the first paragraph in the table cell. Paragraph p = cell.Elements <Paragraph>().First(); // Find the first run in the paragraph. Run run = p.Elements <Run>().First(); // Set the text for the run. Text text = run.Elements <Text>().First(); text.Text = pTextValue; document.Save(); } }
public void W005_AddCommentsPart() { const string author = "Some Name"; const string comment = "A comment."; const string initials = "ABC"; const string id = "0"; using (var stream = GetStream(TestFiles.Plain, true)) using (var doc = WordprocessingDocument.Open(stream, true)) { W.Paragraph firstParagraph = doc.MainDocumentPart.Document.Descendants <W.Paragraph>().First(); W.Comments comments = null; WordprocessingCommentsPart commentPart = doc.MainDocumentPart.AddNewPart <WordprocessingCommentsPart>(); commentPart.Comments = new W.Comments(); comments = commentPart.Comments; var p = new W.Paragraph(new W.Run(new W.Text(comment))); var cmt = new W.Comment() { Id = id, Author = author, Initials = initials, Date = DateTime.Now, }; cmt.AppendChild(p); comments.AppendChild(cmt); comments.Save(); firstParagraph.InsertBefore( new W.CommentRangeStart() { Id = id }, firstParagraph.GetFirstChild <W.Run>()); var cmtEnd = firstParagraph.InsertAfter( new W.CommentRangeEnd() { Id = id }, firstParagraph.Elements <W.Run>().Last()); firstParagraph.InsertAfter(new W.Run(new W.CommentReference() { Id = id }), cmtEnd); var v = new OpenXmlValidator(FileFormatVersions.Office2013); var errs = v.Validate(doc); Assert.Empty(errs); } }
//:::::WORD DOCUMENT PROCESSING PART::::: public static void AddToTable(String fileName, String tableName, int elemNo, String txt, int elemRow = 0) { List <WordP.Table> tables = null; using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(fileName, true)) { tables = new List <WordP.Table>(wordDoc.MainDocumentPart.Document.Body.Elements <WordP.Table>()); tables.ForEach(table => { WordP.TableProperties tblProperties = table.GetFirstChild <WordP.TableProperties>(); if (tblProperties != null) { WordP.TableCaption caption = tblProperties.GetFirstChild <WordP.TableCaption>(); if (caption != null) { if (caption.Val.HasValue && caption.Val.Value.Equals(tableName)) { WordP.TableRow row = table.Elements <WordP.TableRow>().ElementAt(elemNo); // Find the third cell in the row. WordP.TableCell cell = row.Elements <WordP.TableCell>().ElementAt(elemRow); // Find the first paragraph in the table cell. WordP.Paragraph p = cell.Elements <WordP.Paragraph>().First(); // Find the first run in the paragraph. WordP.Run r = p.Elements <WordP.Run>().First(); // Set the text for the run. WordP.Text t = r.Elements <WordP.Text>().First(); t.Text = txt; // you have got your table. process the rest. } } } }); } }
private string GetText(Paragraph paragraph, DqStyleTable dqStyleTable, DqFontScheme fontScheme, DqNumberingTable dqNumberingTable) { var buffer = new StringBuilder(); foreach (var child in paragraph.Elements()) { switch (child) { case Run run: buffer.Append(GetText(run, dqStyleTable, fontScheme, dqNumberingTable)); break; case DocumentFormat.OpenXml.Wordprocessing.Hyperlink hyperlink: foreach (var run in hyperlink.Elements <Run>()) { buffer.Append(GetText(run, dqStyleTable, fontScheme, dqNumberingTable)); } break; } } return(buffer.ToString()); }
private void insertHABehaveTables(Boolean auto, wp.Paragraph par) { List<ReportRow> results; MediasCompetencia medias; wp.Paragraph tempPar = new wp.Paragraph(); ; wp.TableRow tRow; int count; wp.Run rSymbol; setupHABehaveTableTemplate(); wp.Table novaTabela = tempTable.Clone() as wp.Table; String vh, va; clearParagraphText(par); foreach (FamiliaCompetencias fam in _Modelo.Familias.Values) foreach (Competencia comp in fam.Competencias.Values.Where(a => a.Type != "D")) { if ("Orientação para Resultados" == repCalcs.getCompetenciaText(comp.CompetenciaID)) vh = ""; results = repCalcs.getAvaliacaoComportamentosCriticosExtendedOne2One(comp.CompetenciaID); medias = repCalcs.getMediasCompetencia(comp.CompetenciaID); tRow = tempRowHeader.Clone() as wp.TableRow; setText(repCalcs.getCompetenciaText(comp.CompetenciaID), tRow.Elements<wp.TableCell>().ElementAt(0)); setText(medias.mS.ToString("0.00"), tRow.Elements<wp.TableCell>().ElementAt(2)); setText(medias.mT.ToString("0.00"), tRow.Elements<wp.TableCell>().ElementAt(3)); tempPar = tRow.Elements<wp.TableCell>().ElementAt(1).Elements<wp.Paragraph>().First(); rSymbol = tempPar.Elements<wp.Run>().First(); if (medias.mS > medias.mT) { rSymbol.Elements<wp.SymbolChar>().First().Char = symbUp.Char; } else if (medias.mS < medias.mT) { rSymbol.Elements<wp.SymbolChar>().First().Char = symbDw.Char; } else { rSymbol.Elements<wp.SymbolChar>().First().Char = symbH.Char; } novaTabela.Append(tRow); tRow = tempRowHeader2.Clone() as wp.TableRow; //segundo header novaTabela.Append(tRow); count = 1; results.RemoveAt(0); // para retirara as legendas que aqui naão são utilizadas foreach (ReportRow rr in results) { vh = ""; va = ""; if (count % 2 == 0) { //par tRow = tempRowPar.Clone() as wp.TableRow; } else { //impar tRow = tempRowImpar.Clone() as wp.TableRow; } setText(rr.dados[0], tRow.Elements<wp.TableCell>().ElementAt(0)); tempPar = tRow.Elements<wp.TableCell>().ElementAt(1).Elements<wp.Paragraph>().First(); rSymbol = tempPar.Elements<wp.Run>().First(); if (rr.dados[6] == "-1,00") vh = "-"; else vh = rr.dados[6]; if (rr.dados[7] == "-1,00") va = "-"; else va = rr.dados[7]; setText(vh, tRow.Elements<wp.TableCell>().ElementAt(2)); setText(va, tRow.Elements<wp.TableCell>().ElementAt(3)); // o dados de 7 e o dados de 6 podem viR A nullo if (va != "-" && vh != "-" && rr.dados[7] != null && rr.dados[6] != null) { if (float.Parse(rr.dados[6].Replace(",", ".")) > float.Parse(rr.dados[7].Replace(",", "."))) { rSymbol.Elements<wp.SymbolChar>().First().Char = symbUp.Char; CountUps++; } else if (float.Parse(rr.dados[6].Replace(",", ".")) < float.Parse(rr.dados[7].Replace(",", "."))) { rSymbol.Elements<wp.SymbolChar>().First().Char = symbDw.Char; CountDown++; } else { rSymbol.Elements<wp.SymbolChar>().First().Char = symbH.Char; CountHoriz++; } } else rSymbol.Elements<wp.SymbolChar>().First().Char = "F09F"; novaTabela.Append(tRow); count++; } // colocar um parágrafo novaTabela.Append(tempParagraph.Clone() as wp.Paragraph); } par.Append(novaTabela); }
public static void ReplaceComments(string filePath, Dictionary<string, Object> dictmark) { if (dictmark == null) dictmark = new Dictionary<string, Object>(); FileStream fs = new FileStream(filePath, FileMode.Open); WordprocessingDocument WORD = WordprocessingDocument.Open(fs, true); #region 生成Word try { Document doc = WORD.MainDocumentPart.Document;//找到正文处顶级 MainDocumentPart MainPart = WORD.MainDocumentPart; IEnumerable<Comment> comments = WORD.MainDocumentPart.WordprocessingCommentsPart.Comments.Descendants<Comment>();//找到所有批注 var CommentRangeStarts = doc.Descendants<CommentRangeStart>(); var CommentRangeEnds = doc.Descendants<CommentRangeEnd>(); var CommentReferences = doc.Descendants<CommentReference>(); foreach (Comment comment in comments) { string id = comment.Id; string key = comment.InnerText.Trim(); var Startnode = CommentRangeStarts.First(p => p.Id == id); var Startnode_a = CommentRangeStarts.First(p => p.Id == id); var Endnode = CommentRangeEnds.First(p => p.Id == id); var Refernode = CommentReferences.First(p => p.Id == id); if (dictmark.ContainsKey(key)) { Object value = dictmark[key]; if (value is String) { var str = value as string; if (str.Contains("\r\n") || str.Contains("\n")) { var strArray = str.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries); value = strArray; } else { Run run = Startnode.NextSibling<Run>(); run.ReplaceChild<Text>(new Text(value.ToString()), run.GetFirstChild<Text>()); OpenXmlElement nextNode = null; while ((nextNode = run.NextSibling()) is Run) nextNode.Remove(); } } if (value is System.Drawing.Image) { // System.Drawing.Image img = value as System.Drawing.Image; ImagePart imagePart = MainPart.AddImagePart(ImageDict[img.RawFormat]); using (MemoryStream ms = new MemoryStream()) { img.Save(ms, img.RawFormat); ms.Position = 0; imagePart.FeedData(ms); } Run imagerun = CreateImageRun.GenerateRun(MainPart.GetIdOfPart(imagePart), img); // OpenXmlElement nextNode = null; while ((nextNode = Startnode.NextSibling()) is Run) nextNode.Remove(); Startnode.InsertAfterSelf<Run>(imagerun); } if (value is ImageTextArray[]) { OpenXmlElement nextNode = null; RunProperties TempStyle = new RunProperties();//= run.RunProperties.Clone() as RunProperties; // OpenXmlElement replacenode = Startnode.Parent; while ((nextNode = Startnode.NextSibling()) is Run) { nextNode.Remove(); } ImageTextArray[] imgArray = value as ImageTextArray[]; //imgArray = imgArray.OrderByDescending(i=>i).ToArray(); //图片 for (int i = imgArray.Length - 1; i >= 0; i--) { var img = imgArray[i].Images; var str = imgArray[i].Foots; var text = imgArray[i].Text; //判断是否是手签图片,若不是则将文字套入 if (img != null) { #region insert img ImagePart imagePart = MainPart.AddImagePart(ImageDict[img.RawFormat]); using (MemoryStream ms = new MemoryStream()) { img.Save(ms, img.RawFormat); ms.Position = 0; imagePart.FeedData(ms); ms.Close(); } Run imagerun = CreateImageRun.GenerateRun(MainPart.GetIdOfPart(imagePart), img); // //if (i == 0) //{ // Startnode.InsertAfterSelf<Run>(imagerun); //} //else //{ Paragraph imgPgf = new Paragraph(imagerun); // 进入该段落的ParagraphProperties部分,如果没有,创建新的。 if (!imgPgf.Elements<ParagraphProperties>().Any()) { imgPgf.PrependChild<ParagraphProperties>(new ParagraphProperties()); } ParagraphProperties imgpPr = imgPgf.ParagraphProperties; if (!imgpPr.Elements<Justification>().Any()) { imgpPr.PrependChild<Justification>(new Justification()); } imgpPr.Justification.Val = imgArray[i].ImageAlign; replacenode.InsertBeforeSelf<Paragraph>(imgPgf); //} #endregion } else { //文字内容 RunProperties styles_T = new RunProperties(TempStyle.OuterXml); styles_T.Append(new FontSize() { Val = "24" }); styles_T.Append(new RunFonts() { Ascii = "仿宋", HighAnsi = "仿宋", EastAsia = "仿宋" }); Paragraph pgf_T = new Paragraph(new Run(styles_T, new Text(text))); if (!pgf_T.Elements<ParagraphProperties>().Any()) { pgf_T.PrependChild<ParagraphProperties>(new ParagraphProperties()); } ParagraphProperties pPr_T = pgf_T.ParagraphProperties; replacenode.InsertBeforeSelf<Paragraph>(pgf_T); } #region 插入用户名与日期 RunProperties styles = new RunProperties(TempStyle.OuterXml); styles.Append(new RunFonts() { Ascii = "仿宋", HighAnsi = "仿宋", EastAsia = "仿宋" }); styles.Append(new FontSize() { Val = "24" }, new Bold()); Paragraph pgf = new Paragraph(new Run(styles, new Text(str))); // 进入该段落的ParagraphProperties部分,如果没有,创建新的。 if (!pgf.Elements<ParagraphProperties>().Any()) { pgf.PrependChild<ParagraphProperties>(new ParagraphProperties()); } ParagraphProperties pPr = pgf.ParagraphProperties; if (!pPr.Elements<Justification>().Any()) { pPr.PrependChild<Justification>(new Justification()); } pPr.Justification.Val = imgArray[i].FootAlign; replacenode.InsertBeforeSelf<Paragraph>(pgf); //RunProperties styles2 = new RunProperties(TempStyle.OuterXml); //Paragraph pgf2 = new Paragraph(new Run(styles2, new Text("系统dddd"))); //// 进入该段落的ParagraphProperties部分,如果没有,创建新的。 //if (!pgf2.Elements<ParagraphProperties>().Any()) //{ // pgf2.PrependChild<ParagraphProperties>(new ParagraphProperties()); //} //ParagraphProperties pPr2 = pgf2.ParagraphProperties; //if (!pPr2.Elements<Justification>().Any()) //{ // pPr2.PrependChild<Justification>(new Justification()); //} //pPr2.Justification.Val = imgArray[i].FootAlign; //replacenode.InsertBeforeSelf<Paragraph>(pgf2); #endregion if (img != null) { img.Dispose(); } } //RunProperties stylesLast = new RunProperties(TempStyle.OuterXml); //Paragraph pgfLast = new Paragraph(new Run(stylesLast, new Break())); //// 进入该段落的ParagraphProperties部分,如果没有,创建新的。 //if (!pgfLast.Elements<ParagraphProperties>().Any()) //{ // pgfLast.PrependChild<ParagraphProperties>(new ParagraphProperties()); //} //replacenode.InsertAfterSelf<Paragraph>(pgfLast); } if (value is System.Data.DataTable) { System.Data.DataTable table = value as System.Data.DataTable; Table tb = CreateTable.GenerateTable(doc, table.Copy()); OpenXmlElement nextNode = null; while ((nextNode = Startnode.NextSibling()) is Run) nextNode.Remove(); Startnode.Parent.InsertAfterSelf<Table>(tb); Startnode.Parent.Remove(); } if (value is DataTableArray) { DataTableArray tableArray = value as DataTableArray; int index = tableArray.addIndexNum; System.Data.DataTable table = tableArray.dataTable; Table tbl = (Table)doc.MainDocumentPart.Document.Body.ChildElements[index]; //Table tbl = doc.MainDocumentPart.Document.Body.GetFirstChild<Table>(); for (int j = 0; j < table.Rows.Count; j++) { TableRow tableRow2 = new TableRow() { RsidTableRowAddition = "00344722", RsidTableRowProperties = "00164A46", ParagraphId = "47CB71AF", TextId = "77777777" }; TableRowProperties tableRowProperties2 = new TableRowProperties(); TableJustification tableJustification3 = new TableJustification() { Val = TableRowAlignmentValues.Center }; tableRowProperties2.Append(tableJustification3); tableRow2.Append(tableRowProperties2); for (int i = 0; i < table.Columns.Count; i++) { //var cells = tbl.ToList()[2].ChildElements[i]; TableCell tableCell11 = new TableCell(); TableCellProperties tableCellProperties11 = new TableCellProperties(); TableCellWidth tableCellWidth11 = new TableCellWidth() { Width = "405", Type = TableWidthUnitValues.Pct }; TableCellVerticalAlignment tableCellVerticalAlignment11 = new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }; tableCellProperties11.Append(tableCellWidth11); tableCellProperties11.Append(tableCellVerticalAlignment11); Paragraph paragraph16 = new Paragraph() { RsidParagraphAddition = "00344722", RsidParagraphProperties = "007F3CE0", RsidRunAdditionDefault = "00344722", ParagraphId = "3113A1DD", TextId = "62D52A14" }; ParagraphProperties paragraphProperties16 = new ParagraphProperties(); Justification justification16 = new Justification() { Val = JustificationValues.Center }; ParagraphMarkRunProperties paragraphMarkRunProperties1 = new ParagraphMarkRunProperties(); RunFonts runFonts19 = new RunFonts() { Hint = FontTypeHintValues.EastAsia }; paragraphMarkRunProperties1.Append(runFonts19); paragraphProperties16.Append(justification16); paragraphProperties16.Append(paragraphMarkRunProperties1); Run run19 = new Run(); RunProperties runProperties19 = new RunProperties(); RunFonts runFonts20 = new RunFonts() { Hint = FontTypeHintValues.EastAsia }; runProperties19.Append(runFonts20); Text text19 = new Text(); text19.Text = table.Rows[j][i].ToString(); run19.Append(runProperties19); run19.Append(text19); paragraph16.Append(paragraphProperties16); paragraph16.Append(run19); tableCell11.Append(tableCellProperties11); tableCell11.Append(paragraph16); tableRow2.Append(tableCell11); } tbl.Append(tableRow2); } //删除表中多余的元素 if (!string.IsNullOrEmpty(tableArray.deleteNumber)) { Paragraph deleteParagraph = (Paragraph)doc.MainDocumentPart.Document.Body.ChildElements[int.Parse(tableArray.deleteNumber)]; doc.MainDocumentPart.Document.Body.RemoveChild(deleteParagraph); } } if (value is IEnumerable<string>) { IEnumerable<string> lst = value as IEnumerable<string>; // Run run = Startnode.NextSibling<Run>(); run.ReplaceChild<Text>(new Text(lst.First().ToString()), run.GetFirstChild<Text>()); // OpenXmlElement nextNode = null; while ((nextNode = run.NextSibling()) is Run) nextNode.Remove(); // RunProperties TempStyle = run.RunProperties.Clone() as RunProperties; TempStyle.Append(new FontSize() { Val = "24" }); TempStyle.Append(new RunFonts() { Ascii = "方正仿宋_GBK", HighAnsi = "方正仿宋_GBK", EastAsia = "方正仿宋_GBK" }); // OpenXmlElement replacenode = Startnode.Parent; // IEnumerable<string> Afterlst = lst.Reverse(); // 方正仿宋_GBK // int sum = 0; foreach (string str in Afterlst) { if (sum == Afterlst.Count() - 1) break; //RunProperties styles = new RunProperties(TempStyle.OuterXml); RunProperties TempStyle2 = run.RunProperties.Clone() as RunProperties; TempStyle2.Append(new FontSize() { Val = "24" }); TempStyle2.Append(new RunFonts() { Ascii = "方正仿宋_GBK", HighAnsi = "方正仿宋_GBK", EastAsia = "方正仿宋_GBK" }); TempStyle2.Append(new SpacingBetweenLines() { Line = "10000", LineRule = LineSpacingRuleValues.Exact }); Paragraph pgf = new Paragraph(new Run(TempStyle2, new Text(str))); replacenode.InsertAfterSelf(pgf); //replacenode.AppendChild(pgf as OpenXmlElement); sum++; } // } } Startnode.Remove(); Endnode.Remove(); Refernode.Parent.Remove(); } WORD.MainDocumentPart.RemoveAnnotations<Comments>(); doc.Save(); } finally { WORD.Close(); fs.Close(); } #endregion }
public static void ReplaceComments(string filePath, Dictionary<string, Object> dictmark) { if (dictmark == null) dictmark = new Dictionary<string, Object>(); FileStream fs = new FileStream(filePath, FileMode.Open); WordprocessingDocument WORD = WordprocessingDocument.Open(fs, true); #region 生成Word try { Document doc = WORD.MainDocumentPart.Document;//找到正文处顶级 MainDocumentPart MainPart = WORD.MainDocumentPart; IEnumerable<Comment> comments = WORD.MainDocumentPart.WordprocessingCommentsPart.Comments.Descendants<Comment>();//找到所有批注 var CommentRangeStarts = doc.Descendants<CommentRangeStart>(); var CommentRangeEnds = doc.Descendants<CommentRangeEnd>(); var CommentReferences = doc.Descendants<CommentReference>(); foreach (Comment comment in comments) { string id = comment.Id; string key = comment.InnerText.Trim(); var Startnode = CommentRangeStarts.First(p => p.Id == id); var Startnode_a = CommentRangeStarts.First(p => p.Id == id); var Endnode = CommentRangeEnds.First(p => p.Id == id); var Refernode = CommentReferences.First(p => p.Id == id); if (dictmark.ContainsKey(key)) { Object value = dictmark[key]; if (value is String) { var str = value as string; if (str.Contains("\r\n") || str.Contains("\n")) { var strArray = str.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries); value = strArray; } else { Run run = Startnode.NextSibling<Run>(); run.ReplaceChild<Text>(new Text(value.ToString()), run.GetFirstChild<Text>()); OpenXmlElement nextNode = null; while ((nextNode = run.NextSibling()) is Run) nextNode.Remove(); } } if (value is System.Drawing.Image) { // System.Drawing.Image img = value as System.Drawing.Image; ImagePart imagePart = MainPart.AddImagePart(ImageDict[img.RawFormat]); using (MemoryStream ms = new MemoryStream()) { img.Save(ms, img.RawFormat); ms.Position = 0; imagePart.FeedData(ms); } Run imagerun = CreateImageRun.GenerateRun(MainPart.GetIdOfPart(imagePart), img); // OpenXmlElement nextNode = null; while ((nextNode = Startnode.NextSibling()) is Run) nextNode.Remove(); Startnode.InsertAfterSelf<Run>(imagerun); } if (value is ImageTextArray[]) { OpenXmlElement nextNode = null; RunProperties TempStyle = new RunProperties();//= run.RunProperties.Clone() as RunProperties; // OpenXmlElement replacenode = Startnode.Parent; while ((nextNode = Startnode.NextSibling()) is Run) { nextNode.Remove(); } ImageTextArray[] imgArray = value as ImageTextArray[]; //imgArray = imgArray.OrderByDescending(i=>i).ToArray(); //图片 for (int i = imgArray.Length - 1; i >= 0; i--) { var img = imgArray[i].Images; var str = imgArray[i].Foots; var text = imgArray[i].Text; //判断是否是手签图片,若不是则将文字套入 if (img != null) { #region insert img ImagePart imagePart = MainPart.AddImagePart(ImageDict[img.RawFormat]); using (MemoryStream ms = new MemoryStream()) { img.Save(ms, img.RawFormat); ms.Position = 0; imagePart.FeedData(ms); ms.Close(); } Run imagerun = CreateImageRun.GenerateRun(MainPart.GetIdOfPart(imagePart), img); // //if (i == 0) //{ // Startnode.InsertAfterSelf<Run>(imagerun); //} //else //{ Paragraph imgPgf = new Paragraph(imagerun); // 进入该段落的ParagraphProperties部分,如果没有,创建新的。 if (!imgPgf.Elements<ParagraphProperties>().Any()) { imgPgf.PrependChild<ParagraphProperties>(new ParagraphProperties()); } ParagraphProperties imgpPr = imgPgf.ParagraphProperties; if (!imgpPr.Elements<Justification>().Any()) { imgpPr.PrependChild<Justification>(new Justification()); } imgpPr.Justification.Val = imgArray[i].ImageAlign; replacenode.InsertBeforeSelf<Paragraph>(imgPgf); //} #endregion } else { //文字内容 RunProperties styles_T = new RunProperties(TempStyle.OuterXml); styles_T.Append(new FontSize() { Val = "24" }); styles_T.Append(new RunFonts() { Ascii = "仿宋", HighAnsi = "仿宋", EastAsia = "仿宋" }); Paragraph pgf_T = new Paragraph(new Run(styles_T, new Text(text))); if (!pgf_T.Elements<ParagraphProperties>().Any()) { pgf_T.PrependChild<ParagraphProperties>(new ParagraphProperties()); } ParagraphProperties pPr_T = pgf_T.ParagraphProperties; replacenode.InsertBeforeSelf<Paragraph>(pgf_T); } #region 插入用户名与日期 RunProperties styles = new RunProperties(TempStyle.OuterXml); styles.Append(new RunFonts() { Ascii = "仿宋", HighAnsi = "仿宋", EastAsia = "仿宋" }); styles.Append(new FontSize() { Val = "24" }, new Bold()); Paragraph pgf = new Paragraph(new Run(styles, new Text(str))); // 进入该段落的ParagraphProperties部分,如果没有,创建新的。 if (!pgf.Elements<ParagraphProperties>().Any()) { pgf.PrependChild<ParagraphProperties>(new ParagraphProperties()); } ParagraphProperties pPr = pgf.ParagraphProperties; if (!pPr.Elements<Justification>().Any()) { pPr.PrependChild<Justification>(new Justification()); } pPr.Justification.Val = imgArray[i].FootAlign; replacenode.InsertBeforeSelf<Paragraph>(pgf); #endregion if (img != null) { img.Dispose(); } } //RunProperties stylesLast = new RunProperties(TempStyle.OuterXml); //Paragraph pgfLast = new Paragraph(new Run(stylesLast, new Break())); //// 进入该段落的ParagraphProperties部分,如果没有,创建新的。 //if (!pgfLast.Elements<ParagraphProperties>().Any()) //{ // pgfLast.PrependChild<ParagraphProperties>(new ParagraphProperties()); //} //replacenode.InsertAfterSelf<Paragraph>(pgfLast); } if (value is System.Data.DataTable) { System.Data.DataTable table = value as System.Data.DataTable; Table tb = CreateTable.GenerateTable(doc, table.Copy()); OpenXmlElement nextNode = null; while ((nextNode = Startnode.NextSibling()) is Run) nextNode.Remove(); Startnode.Parent.InsertAfterSelf<Table>(tb); Startnode.Parent.Remove(); } if (value is IEnumerable<string>) { IEnumerable<string> lst = value as IEnumerable<string>; // Run run = Startnode.NextSibling<Run>(); run.ReplaceChild<Text>(new Text(lst.First().ToString()), run.GetFirstChild<Text>()); // OpenXmlElement nextNode = null; while ((nextNode = run.NextSibling()) is Run) nextNode.Remove(); // RunProperties TempStyle = run.RunProperties.Clone() as RunProperties; TempStyle.Append(new FontSize() { Val = "24" }); TempStyle.Append(new RunFonts() { Ascii = "仿宋", HighAnsi = "仿宋", EastAsia = "仿宋" }); // OpenXmlElement replacenode = Startnode.Parent; // IEnumerable<string> Afterlst = lst.Reverse(); // 方正仿宋_GBK // int sum = 0; foreach (string str in Afterlst) { if (sum == Afterlst.Count() - 1) break; //RunProperties styles = new RunProperties(TempStyle.OuterXml); RunProperties TempStyle2 = run.RunProperties.Clone() as RunProperties; TempStyle2.Append(new FontSize() { Val = "32" }); TempStyle2.Append(new RunFonts() { Ascii = "方正仿宋_GBK", HighAnsi = "方正仿宋_GBK", EastAsia = "方正仿宋_GBK" }); TempStyle2.Append(new SpacingBetweenLines() { Line = "10000", LineRule = LineSpacingRuleValues.Exact }); Paragraph pgf = new Paragraph(new Run(TempStyle2, new Text(str))); replacenode.InsertAfterSelf(pgf); //replacenode.AppendChild(pgf as OpenXmlElement); sum++; } // } } Startnode.Remove(); Endnode.Remove(); Refernode.Parent.Remove(); } WORD.MainDocumentPart.RemoveAnnotations<Comments>(); doc.Save(); } finally { WORD.Close(); fs.Close(); } #endregion }
/// <summary> /// Get paragraph's numbering level object by searching abstractNums with the numbering level ID. /// </summary> /// <param name="pg"></param> /// <returns></returns> public Word.Level GetNumbering(Word.Paragraph pg) { Word.Level ret = null; if (pg == null || this.numbering == null) { return(ret); } Word.ParagraphProperties pgpr = pg.Elements <Word.ParagraphProperties>().FirstOrDefault(); if (pgpr == null) { return(ret); } // direct numbering Word.NumberingProperties numPr = pgpr.Elements <Word.NumberingProperties>().FirstOrDefault(); if (numPr != null && numPr.NumberingId != null) { int numId = numPr.NumberingId.Val; if (numId > 0) // numId == 0 means this paragraph doesn't have a list item { int? ilvl = null; String refStyleName = null; if (numPr.NumberingLevelReference != null) { // ilvl included in NumberingProperties ilvl = numPr.NumberingLevelReference.Val; } else { // doesn't have ilvl in NumberingProperties, search by referenced style name Word.Style st = pgpr.Elements <Word.Style>().FirstOrDefault(); if (st != null && st.StyleName != null) { refStyleName = st.StyleName.Val; } } // find abstractNumId by numId Word.NumberingInstance numInstance = this.numbering.Elements <Word.NumberingInstance>().FirstOrDefault(c => c.NumberID.Value == numId); if (numInstance != null) { // find abstractNum by abstractNumId Word.AbstractNum abstractNum = (Word.AbstractNum) this.numbering.Elements <Word.AbstractNum>().FirstOrDefault(c => c.AbstractNumberId.Value == numInstance.AbstractNumId.Val); if (abstractNum != null) { if (ilvl != null) // search by ilvl { ret = abstractNum.Elements <Word.Level>().FirstOrDefault(c => c.LevelIndex == ilvl); } else if (refStyleName != null) // search by matching referenced style name { ret = abstractNum.Elements <Word.Level>().FirstOrDefault(c => { return((c.ParagraphStyleIdInLevel != null) ? c.ParagraphStyleIdInLevel.Val == refStyleName : false); }); } } } } } // TODO: linked style if (ret == null) { ; } return(ret); }