/// <summary> /// Check if the target cell have some changes. /// </summary> /// <param name="targetCell"></param> /// <returns></returns> private bool SegmentHasChanges(TableCell targetCell) { if (targetCell.Descendants().Any(e => _trackedRevisionsElements.Contains(e.GetType()))) { return(true); } if (targetCell.Descendants().Any(e => e.GetType() == typeof(CommentRangeStart) || e.GetType() == typeof(CommentRangeStart))) { return(true); } return(false); }
/// <summary> /// Add table /// </summary> /// <param name="table"></param> /// <returns></returns> private string AddTable(Table table) { try { string tableTemplate = @"<table STYLE> TABLE_CONTENT </table>"; string htmlTableStyle = " width=\"100%\" border=\"1\" cellspacing=\"0\" cellpadding=\"0\" style=\"border-collapse:collapse;border:none;\""; string htmlRows = string.Empty; List <TableRow> rows = table.Elements <TableRow>().ToList(); for (int indexRow = 0; indexRow < rows.Count(); indexRow++) { TableRow row = rows[indexRow]; string htmlCells = ""; List <TableCell> cells = row.Elements <TableCell>().ToList(); for (int indexCell = 0; indexCell < cells.Count(); indexCell++) { TableCell cell = cells[indexCell]; string tableCellStyle = string.Format("<td width=\"{0}\" valign=\"top\" style=\"border:solid windowtext 1.0pt;padding:0cm 5.4pt 0cm 5.4pt;\">", 100 / cells.Count); htmlCells += tableCellStyle + AddParagraphs(cell.Descendants <Paragraph>()) + "</td>" + Environment.NewLine; } htmlRows += "<tr>" + htmlCells + "</tr>" + Environment.NewLine; } return(tableTemplate.Replace("STYLE", htmlTableStyle).Replace("TABLE_CONTENT", htmlRows)); } catch (Exception ex) { throw ex; } }
private void SetCCText(TableCell tableCell, string contentControlTag, string text) { SdtRun contentControl = tableCell.Descendants <SdtRun>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == contentControlTag).Single(); SdtContentRun contentRun = contentControl.GetFirstChild <SdtContentRun>(); contentRun.GetFirstChild <Run>().GetFirstChild <Text>().Text = text; }
private static void ProcessWord() { var file = @"test.docx"; using (WordprocessingDocument doc = WordprocessingDocument.Open(file, true)) { var body = doc.MainDocumentPart.Document.Body; if (doc.HasStyleId("2")) { Console.WriteLine("has styleId 2"); } if (doc.HasStyleId("3")) { Console.WriteLine("has styleId 3"); } var styleNames = doc.MainDocumentPart.StyleDefinitionsPart.Styles.Descendants <StyleName>(); if (styleNames.Any()) { } var table = doc.MainDocumentPart.Document.Body.Elements <Table>().First(); TableRow row = table.Elements <TableRow>().ElementAt(0); TableCell cell = row.Elements <TableCell>().ElementAt(0); var pic = cell.Descendants <PIC.Picture>().FirstOrDefault(); if (pic != null) { var imageFile = @"tmp.jpg"; var relationshipId = doc.AddImage(imageFile); pic.BlipFill.Blip.Embed.Value = relationshipId; } } }
byte[] GetImageAsBytes(WordprocessingDocument document, TableCell par) { // this code is copy-pasted var imageParts = from graphic in par.Descendants <DocumentFormat.OpenXml.Drawing.Graphic>() let graphicData = graphic.Descendants <DocumentFormat.OpenXml.Drawing.GraphicData>().FirstOrDefault() let pic = graphicData.ElementAt(0) let nvPicPrt = pic.ElementAt(0).FirstOrDefault() let blip = pic.Descendants <DocumentFormat.OpenXml.Drawing.Blip>().FirstOrDefault() select new { blip }; if (!imageParts.Any()) { return(null); } var imagePart2 = imageParts?.FirstOrDefault(); var id = imagePart2?.blip?.Embed?.Value; var imagePart = (ImagePart)document.MainDocumentPart.GetPartById(id); var stream = imagePart.GetStream(); byte[] imageAsBytes = null; using (var ms = new MemoryStream()) { stream.CopyTo(ms); imageAsBytes = ms.ToArray(); return(imageAsBytes); } }
private void RemoveCCChild(TableCell tableCell, string contentControlTag) { SdtRun contentControl = tableCell.Descendants <SdtRun>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == contentControlTag).Single(); Run contentRun = contentControl.GetFirstChild <SdtContentRun>().GetFirstChild <Run>(); contentRun.RemoveAllChildren <Text>(); }
private void AssertRuleSummaryIdCell(TableCell cell, DiagnosticDescriptor descriptor) { var descendants = cell.Descendants().ToList(); var linkInline = descendants.OfType <LinkInline>().Single(); linkInline.Url.Should().Be($"{descriptor.Id}.md"); linkInline.FirstChild.ToString().Should().Be(descriptor.Id); }
private void AppendCCText(TableCell tableCell, string contentControlTag, string text) { SdtRun contentControl = tableCell.Descendants <SdtRun>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == contentControlTag).Single(); SdtContentRun contentRun = contentControl.GetFirstChild <SdtContentRun>(); Text textElement = contentRun.GetFirstChild <Run>().AppendChild(new Text(text)); textElement.InsertAfterSelf(new Break()); }
private static string GetCellText(TableCell tableCell) { var sb = new StringBuilder(); foreach (var paragraph in tableCell.Descendants <Paragraph>()) { var paragraphText = GetParagraphText(paragraph); sb.Append(paragraphText); } return(sb.ToString()); }
/// <summary> /// set cell margin (null values are left unchanged) /// </summary> public static void SetMargin(this TableCell cell, double?marginLeftMM = null, double?marginTopMM = null, double?marginRightMM = null, double?marginBottomMM = null) { var tcPr = cell.Descendants <TableCellProperties>().FirstOrDefault(); if (tcPr == null) { tcPr = cell.AppendChild(new TableCellProperties()); } var tcMar = tcPr.Descendants <TableCellMargin>().FirstOrDefault(); if (tcMar == null) { tcMar = tcPr.AppendChild(new TableCellMargin()); } if (marginLeftMM.HasValue) { if (tcMar.LeftMargin == null) { tcMar.LeftMargin = new LeftMargin(); } tcMar.LeftMargin.Width = marginLeftMM.Value.MMToTwip().ToString(); tcMar.LeftMargin.Type = TableWidthUnitValues.Dxa; } if (marginTopMM.HasValue) { if (tcMar.TopMargin == null) { tcMar.TopMargin = new TopMargin(); } tcMar.TopMargin.Width = marginTopMM.Value.MMToTwip().ToString(); tcMar.TopMargin.Type = TableWidthUnitValues.Dxa; } if (marginRightMM.HasValue) { if (tcMar.RightMargin == null) { tcMar.RightMargin = new RightMargin(); } tcMar.RightMargin.Width = marginRightMM.Value.MMToTwip().ToString(); tcMar.RightMargin.Type = TableWidthUnitValues.Dxa; } if (marginBottomMM.HasValue) { if (tcMar.BottomMargin == null) { tcMar.BottomMargin = new BottomMargin(); } tcMar.BottomMargin.Width = marginBottomMM.Value.MMToTwip().ToString(); tcMar.BottomMargin.Type = TableWidthUnitValues.Dxa; } }
private static void SetCell(TableRow row, int cellIndex, string text) { TableCell cell = row.Elements <TableCell>().ElementAt(cellIndex); var all_text = cell.Descendants <Text>(); foreach (var item in all_text) { item.Remove(); } cell.LastChild.Append(new Run(new Text(text))); }
private void AddTextToBookmark(TableCell cell, StoryCard storyCard) { var bookmark = cell.Descendants <BookmarkStart>().First(); if (bookmark.Name == "Id") { AppendText(storyCard.Id.ToString(), bookmark); } else if (bookmark.Name == "Iteration") { AppendText(storyCard.Iteration, bookmark); } else if (bookmark.Name == "Titel") { AppendText(storyCard.Title, bookmark); } }
private static object GetCellValue(TableCell tableCell) { object cellValue = null; var nestedTables = tableCell.Descendants <Table>(); // if this table contains other nested tables, then an object will be returned if (nestedTables.Any()) { cellValue = ProcessTables(nestedTables.Where(x => x.Parent == tableCell)); } else { // otherwise, just the text inside cellValue = GetCellText(tableCell); } return(cellValue); }
/// <summary> /// Fills the table bookmark /// </summary> /// <param name="mainDocPart">The main document part</param> /// <param name="firstBookmarkInTable">The first bookmark in the table</param> /// <param name="tableData">The table data</param> static void FillTableBookmark(MainDocumentPart mainDocPart, BookmarkContent bookmarkContent) { // find our bookmark var bookmark = mainDocPart.Document.Body.Descendants <BookmarkStart>().FirstOrDefault(b => b.Name == bookmarkContent.BookmarkContentKey); if (bookmark != null && bookmarkContent.BookmarkContentValue != null && bookmarkContent.BookmarkContentValue is ListOfList <BookmarkContent> ) { // get to first element OpenXmlElement elem = bookmark.Parent; // isolate the table to be worked on while (!(elem is Table)) { elem = elem.Parent; } OpenXmlElement targetTable = elem; // save the row you want to copy each time you have data TableRow oldRow = elem.Elements <TableRow>().Last(); TableRow rowTemplate = (TableRow)oldRow.Clone(); // whack old row elem.RemoveChild(oldRow); // Time to slap our data into the table foreach (var item in bookmarkContent.BookmarkContentValue as ListOfList <BookmarkContent> ) { TableRow newRow = (TableRow)rowTemplate.Clone(); IEnumerable <TableCell> cells = newRow.Elements <TableCell>(); for (int i = 0; i < cells.Count(); i++) { TableCell cell = cells.ElementAt(i); FillBookmarkListOnTableCell(mainDocPart, cell.Descendants <BookmarkStart>().ToList(), item); } targetTable.AppendChild(newRow); } } }
ParseDisciplineNameCodeRealization(TableCell cell) { var name = ""; var engName = ""; var seenBreak = false; var runs = cell.Descendants <Run>(); foreach (var run in runs) { foreach (var element in run.ChildElements) { if (element.LocalName == "br") { seenBreak = true; continue; } if (seenBreak) { engName += element.InnerText; continue; } name += element.InnerText; } } var regexMatch = Regex.Match(name, @"\[(\d+)\]\s+([^(]+)\(?([^)]+)?\)?,?\s?(.+)?"); if (regexMatch.Success) { var code = regexMatch.Groups[1].Value; var rusName = regexMatch.Groups[2].Value.Trim(); var realizationType = "" == regexMatch.Groups[3].Value ? null : regexMatch.Groups[3].Value.Trim(); var trajectory = "" == regexMatch.Groups[4].Value ? null : regexMatch.Groups[4].Value.Trim(); var match = Regex.Match(engName, @"[^(]+"); if (match.Success) { engName = match.Value.Trim(); } return(code, rusName, engName, realizationType, trajectory); } return(default);
public override void Process() { var titleRow = document.MainDocumentPart.Document.Body .Descendants <TableRow>().Where(o => o.Descendants <BookmarkStart>().Any(mark => mark.Name == DataProperty.TagID)).FirstOrDefault(); var sdtElements = titleRow.Descendants <SdtElement>().Where(o => o.SdtProperties.Descendants <SdtAlias>().Any(a => a.Val != null)).ToList(); var bookmarkStart = titleRow.Descendants <BookmarkStart>().Where(o => o.Name == DataProperty.TagID).FirstOrDefault(); List <string> properties = new List <string>(); for (int i = 0; i < sdtElements.Count; i++) { properties.Add(sdtElements[i].Descendants <SdtAlias>().FirstOrDefault().Val.Value); } TableRow curRow = titleRow; foreach (DCTWordDataObject wordDataObj in DataProperty.DataObjects) { TableRow newRow = curRow.InsertAfterSelf <TableRow>((TableRow)curRow.NextSibling <TableRow>().CloneNode(true)); TableCell firstCell = newRow.GetFirstChild <TableCell>(); for (int j = bookmarkStart.ColumnFirst; j <= bookmarkStart.ColumnLast; j++) { DCTDataProperty dataProperty = wordDataObj.PropertyCollection[properties[j - bookmarkStart.ColumnFirst]]; if (dataProperty is DCTSimpleProperty) { DCTSimpleProperty simpleProperty = dataProperty as DCTSimpleProperty; TableCell cell = getCellByIndex(firstCell, j); Paragraph p = cell.Descendants <Paragraph>().FirstOrDefault(); p.RemoveAllChildren(); p.AppendChild <Run>(new Run(new Text((GeneralFormatter.ToString(simpleProperty.Value, simpleProperty.FormatString))))); } } curRow = newRow; } }
public void ExportWordDocument(string filepath) { using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document)) { MainDocumentPart mainPart = wordDocument.AddMainDocumentPart(); mainPart.Document = new Document(); Body body = mainPart.Document.AppendChild(new Body()); #region 标题文字(加粗居中) Paragraph para = body.AppendChild(new Paragraph()); ParagraphProperties pPr = para.AppendChild(new ParagraphProperties()); pPr.Append(new Justification() { Val = JustificationValues.Center }); Run run = para.AppendChild(new Run()); RunProperties rPr = new RunProperties(new RunFonts() { Ascii = "宋体", ComplexScript = "宋体", EastAsia = "宋体", HighAnsi = "宋体" }); rPr.Append(new FontSize() { Val = "40" }); rPr.Append(new Bold() { Val = true }); run.Append(rPr); run.Append(new Text("钢轨探伤仪探伤报告")); #endregion //rPr.FontSize.Val = "40"; //rPr.Append(new RunFonts() { ComplexScript = "宋体" }); //rPr.RunFonts.ComplexScript = "宋体"; //Run r = wordDocument.MainDocumentPart.Document.Descendants<Run>().First(); //r.PrependChild(rPr); #region 表格 Table table = new Table(); #region 表格样式 // Create a TableProperties object and specify its border information. TableProperties tblProp = new TableProperties( new TableBorders( new TopBorder() { Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 1 }, new BottomBorder() { Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 1 }, new LeftBorder() { Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 1 }, new RightBorder() { Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 1 }, new InsideHorizontalBorder() { Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 1 }, new InsideVerticalBorder() { Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 1 } ) ); tblProp.TableWidth = new TableWidth() { Width = "9639", Type = TableWidthUnitValues.Dxa }; tblProp.TableLayout = new TableLayout() { Type = TableLayoutValues.Fixed }; //固定列宽 tblProp.TableLook = new TableLook() { Val = "0000", FirstRow = false, LastRow = false, FirstColumn = false, LastColumn = false }; table.Append(tblProp); #endregion #region 成员模板 //Paragraph tblPara = new Paragraph(); //ParagraphProperties tblpPr = tblPara.AppendChild(new ParagraphProperties()); //tblpPr.AppendChild(new Justification() { Val = JustificationValues.Left }); //tblpPr.AppendChild( // new RunProperties( // new RunFonts() { Ascii = "宋体", ComplexScript = @"宋体", EastAsia = "宋体", HighAnsi = "宋体" }, // new FontSize() { Val = "24" }) // ); TableRow tr = new TableRow(); tr.AppendChild(new TableRowProperties(new TableRowHeight() { Val = 454 })); TableCell tc = new TableCell(); tc.AppendChild(new TableCellProperties( new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center } //,new Shading() { Val = ShadingPatternValues.Clear, Fill = "auto" }// 阴影 )); tc.AppendChild(new TableCellMargin( new LeftMargin() { Width = "100" } )); Run tblRun = new Run(); tblRun.AppendChild(new RunProperties( new RunFonts() { Ascii = "宋体", ComplexScript = @"宋体", EastAsia = "宋体", HighAnsi = "宋体" }, new FontSize() { Val = "24" }, new Bold() { Val = true } )); #endregion #region 例1 { // Create a row. TableRow test1 = new TableRow(tr.OuterXml); // Create a cell. // Create a second table cell by copying the OuterXml value of the first table cell. TableCell tc1 = new TableCell(tc.OuterXml); TableCell tc2 = new TableCell(tc.OuterXml); TableCell tc3 = new TableCell(tc.OuterXml); TableCell tc4 = new TableCell(tc.OuterXml); TableCell tc5 = new TableCell(tc.OuterXml); TableCell tc6 = new TableCell(tc.OuterXml); // Specify the table cell content. Run run1 = new Run(tblRun.OuterXml); Run run2 = new Run(tblRun.OuterXml); Run run3 = new Run(tblRun.OuterXml); Run run4 = new Run(tblRun.OuterXml); Run run5 = new Run(tblRun.OuterXml); Run run6 = new Run(tblRun.OuterXml); run1.Append(new Text("some text 1")); run2.Append(new Text("some text 2")); run3.Append(new Text("some text 3")); run4.Append(new Text("文字4:")); run5.Append(new Text("some text 5")); run6.Append(new Text("text 6")); tc1.Append(new Paragraph(run1)); tc2.Append(new Paragraph(run2)); tc3.Append(new Paragraph(run3)); tc4.Append(new Paragraph(run4)); tc5.Append(new Paragraph(run5)); tc6.Append(new Paragraph(run6)); //Paragraph para1 = new Paragraph(tlbPara.OuterXml); //Paragraph para2 = new Paragraph(tlbPara.OuterXml); //Paragraph para3 = new Paragraph(tlbPara.OuterXml); //Paragraph para4 = new Paragraph(tlbPara.OuterXml); //Paragraph para5 = new Paragraph(tlbPara.OuterXml); //Paragraph para6 = new Paragraph(tlbPara.OuterXml); //para1.Append(new Run(new Text("some text 1"))); //para2.Append(new Run(new Text("some text 2"))); //para3.Append(new Run(new Text("some text 3"))); //para4.Append(new Run(new Text("some text 4"))); //para5.Append(new Run(new Text("some text 5"))); //para6.Append(new Run(new Text("some text 6"))); //tc1.Append(para1); //tc2.Append(para2); //tc3.Append(para3); //tc4.Append(para4); //tc5.Append(para5); //tc6.Append(para6); // Append the table cell to the table row. test1.Append(tc1); test1.Append(tc2); test1.Append(tc3); test1.Append(tc4); test1.Append(tc5); test1.Append(tc6); // Append the table row to the table. //table.Append(test1); } #endregion #region 第一行 { TableRow tr1 = new TableRow(tr.OuterXml); TableCell tc1 = new TableCell(tc.OuterXml); TableCell tc2 = new TableCell(tc.OuterXml); TableCell tc3 = new TableCell(tc.OuterXml); TableCell tc4 = new TableCell(tc.OuterXml); TableCell tc5 = new TableCell(tc.OuterXml); TableCell tc6 = new TableCell(tc.OuterXml); // Specify the table cell content. Run run1 = new Run(tblRun.OuterXml); Run run2 = new Run(tblRun.OuterXml); Run run3 = new Run(tblRun.OuterXml); Run run4 = new Run(tblRun.OuterXml); Run run5 = new Run(tblRun.OuterXml); Run run6 = new Run(tblRun.OuterXml); run1.Append(new Text("线名:")); run2.Append(new Text("000")); run3.Append(new Text("线别:")); run4.Append(new Text("正线")); run5.Append(new Text("股别:")); run6.Append(new Text("右")); tc1.Append(new Paragraph(run1)); tc2.Append(new Paragraph(run2)); tc3.Append(new Paragraph(run3)); tc4.Append(new Paragraph(run4)); tc5.Append(new Paragraph(run5)); tc6.Append(new Paragraph(run6)); // Append the table cell to the table row. tr1.Append(tc1); tr1.Append(tc2); tr1.Append(tc3); tr1.Append(tc4); tr1.Append(tc5); tr1.Append(tc6); // Append the table row to the table. table.Append(tr1); } #endregion #region 第二行 { TableRow tr2 = new TableRow(tr.OuterXml); TableCell tc1 = new TableCell(tc.OuterXml); TableCell tc2 = new TableCell(tc.OuterXml); TableCell tc3 = new TableCell(tc.OuterXml); TableCell tc4 = new TableCell(tc.OuterXml); TableCell tc5 = new TableCell(tc.OuterXml); TableCell tc6 = new TableCell(tc.OuterXml); // Specify the table cell content. Run run1 = new Run(tblRun.OuterXml); Run run2 = new Run(tblRun.OuterXml); Run run3 = new Run(tblRun.OuterXml); Run run4 = new Run(tblRun.OuterXml); Run run5 = new Run(tblRun.OuterXml); Run run6 = new Run(tblRun.OuterXml); run1.Append(new Text("轨型:")); run2.Append(new Text("60")); run3.Append(new Text("伤损类型:")); run4.Append(new Text("")); run5.Append(new Text("生产厂商:")); run6.Append(new Text("")); tc1.Append(new Paragraph(run1)); tc2.Append(new Paragraph(run2)); tc3.Append(new Paragraph(run3)); tc4.Append(new Paragraph(run4)); tc5.Append(new Paragraph(run5)); tc6.Append(new Paragraph(run6)); // Append the table cell to the table row. tr2.Append(tc1); tr2.Append(tc2); tr2.Append(tc3); tr2.Append(tc4); tr2.Append(tc5); tr2.Append(tc6); // Append the table row to the table. table.Append(tr2); } #endregion #region 第三行 { TableRow tr3 = new TableRow(tr.OuterXml); TableCell tc1 = new TableCell(tc.OuterXml); TableCell tc2 = new TableCell(tc.OuterXml); TableCell tc3 = new TableCell(tc.OuterXml); TableCell tc4 = new TableCell(tc.OuterXml); TableCell tc5 = new TableCell(tc.OuterXml); TableCell tc6 = new TableCell(tc.OuterXml); // Specify the table cell content. Run run1 = new Run(tblRun.OuterXml); Run run2 = new Run(tblRun.OuterXml); Run run3 = new Run(tblRun.OuterXml); Run run4 = new Run(tblRun.OuterXml); Run run5 = new Run(tblRun.OuterXml); Run run6 = new Run(tblRun.OuterXml); run1.Append(new Text("伤损编号:")); run2.Append(new Text("")); run3.Append(new Text("探伤时间:")); run4.Append(new Text(DateTime.Now.ToString())); run5.Append(new Text("探伤人员:")); run6.Append(new Text("")); tc1.Append(new Paragraph(run1)); tc2.Append(new Paragraph(run2)); tc3.Append(new Paragraph(run3)); tc4.Append(new Paragraph(run4)); tc5.Append(new Paragraph(run5)); tc6.Append(new Paragraph(run6)); // Append the table cell to the table row. tr3.Append(tc1); tr3.Append(tc2); tr3.Append(tc3); tr3.Append(tc4); tr3.Append(tc5); tr3.Append(tc6); // Append the table row to the table. table.Append(tr3); } #endregion #region 第四行 { TableRow tr4 = new TableRow(tr.OuterXml); TableCell tc1 = new TableCell(tc.OuterXml); TableCell tc2 = new TableCell(tc.OuterXml); TableCellProperties tcPr = tc2.Descendants <TableCellProperties>().First(); tcPr.Append(new GridSpan() { Val = 5 }); // Specify the table cell content. Run run1 = new Run(tblRun.OuterXml); Run run2 = new Run(tblRun.OuterXml); Run run3 = new Run(tblRun.OuterXml); Run run4 = new Run(tblRun.OuterXml); run1.Append(new Text("增益:")); run2.Append(new Text("A:45.0dB B:45.5dB C:45.5dB")); run3.Append(new Text("D:45.5dB E:45.0dB F:45.0dB")); run4.Append(new Text("G:46.5dB H:46.5dB I:52.0dB")); tc1.Append(new Paragraph(run1)); tc2.Append(new Paragraph(run2)); tc2.Append(new Paragraph(run3)); tc2.Append(new Paragraph(run4)); // Append the table cell to the table row. tr4.Append(tc1); tr4.Append(tc2); // Append the table row to the table. table.Append(tr4); } #endregion #region 第五行 { TableRow tr5 = new TableRow(tr.OuterXml); TableCell tc1 = new TableCell(tc.OuterXml); TableRowProperties tblPr4 = tr5.Descendants <TableRowProperties>().First(); tblPr4.AppendChild(new TableRowHeight() { Val = 9000 }); TableCellProperties tcPr = tc1.Descendants <TableCellProperties>().First(); tcPr.Append( new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Top }, new GridSpan() { Val = 6 } ); tcPr.Append(new TableCellMargin(new TopMargin() { Width = "50" })); //new Shading() { Val = ShadingPatternValues.Clear, Fill = "auto" } // Specify the table cell content. Run run1 = new Run(tblRun.OuterXml); Run run2 = new Run(tblRun.OuterXml); Run run3 = new Run(tblRun.OuterXml); Run run4 = new Run(tblRun.OuterXml); //地段:0 //当前里程:0km039m run1.Append(new Text("地段:")); run2.Append(new Text("0")); run3.Append(new Text("当前里程:")); run4.Append(new Text("0km039m")); tc1.Append(new Paragraph(run1, run2)); //tc1.Append(new Paragraph(run2)); tc1.Append(new Paragraph(run3, run4)); //tc1.Append(new Paragraph(run4)); ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg); //Bitmap bitmap = new Bitmap(500, 500); //Graphics g = Graphics.FromImage(bitmap); //g.Clear(System.Drawing.Color.Pink); //using (MemoryStream stream = new MemoryStream()) //{ // bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg); // imagePart.FeedData(stream); //} //////string fileName = @"?D:\Users\KETIZU2\Desktop\images\logo.jpg"; string fileName = @"D:\Users\KETIZU2\Desktop\images\logo.jpg"; using (FileStream stream = new FileStream(fileName, FileMode.Open)) { imagePart.FeedData(stream); } // Define the reference of the image. Paragraph paraImage = AddImageToParagraph(mainPart.GetIdOfPart(imagePart), 6120000L, 2160000L); //wordDoc.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(element))); tc1.AppendChild(paraImage); // Append the table cell to the table row. tr5.Append(tc1); // Append the table row to the table. table.Append(tr5); } #endregion #region 第六行 { TableRow tr6 = new TableRow(tr.OuterXml); TableCell tc1 = new TableCell(tc.OuterXml); TableCell tc2 = new TableCell(tc.OuterXml); TableCellProperties tcPr = tc2.Descendants <TableCellProperties>().First(); tcPr.Append(new GridSpan() { Val = 5 }); // Specify the table cell content. Run run1 = new Run(tblRun.OuterXml); Run run2 = new Run(tblRun.OuterXml); run1.Append(new Text("单位名称:")); run2.Append(new Text("")); tc1.Append(new Paragraph(run1)); tc2.Append(new Paragraph(run2)); // Append the table cell to the table row. tr6.Append(tc1); tr6.Append(tc2); // Append the table row to the table. table.Append(tr6); } #endregion #region 第七行 { TableRow tr7 = new TableRow(tr.OuterXml); TableCell tc1 = new TableCell(tc.OuterXml); TableCell tc2 = new TableCell(tc.OuterXml); TableCell tc3 = new TableCell(tc.OuterXml); TableCell tc4 = new TableCell(tc.OuterXml); TableCellProperties tcPr = tc2.Descendants <TableCellProperties>().First(); tcPr.Append(new GridSpan() { Val = 3 }); // Specify the table cell content. Run run1 = new Run(tblRun.OuterXml); Run run2 = new Run(tblRun.OuterXml); Run run3 = new Run(tblRun.OuterXml); Run run4 = new Run(tblRun.OuterXml); run1.Append(new Text("操作人员:")); run2.Append(new Text("")); run3.Append(new Text("日期:")); run4.Append(new Text(DateTime.Now.ToString())); tc1.Append(new Paragraph(run1)); tc2.Append(new Paragraph(run2)); tc3.Append(new Paragraph(run3)); tc4.Append(new Paragraph(run4)); // Append the table cell to the table row. tr7.Append(tc1); tr7.Append(tc2); tr7.Append(tc3); tr7.Append(tc4); // Append the table row to the table. table.Append(tr7); } #endregion body.Append(table); #endregion #region 文档格式 SectionProperties sectPr = body.AppendChild(new SectionProperties()); sectPr.AppendChild(new PageMargin() { Top = 1134, Right = 1247, Bottom = 1134, Left = 1247, Header = 851, Footer = 992, Gutter = 0 }); #endregion } }
public void CreateMSWordDocument(Guid identifier) { var myResume = _resumeManagerRepository.Get(m => m.Guid.Equals(identifier)).First().Resume; string projPath = HttpContext.Current.Server.MapPath("~/Content/"); string outFilePath = Path.Combine(projPath, "doc", myResume.ResumeManager.Link); byte[] templateBytes = System.IO.File.ReadAllBytes(projPath + "MSWordTemplates\\template4.dotx"); using (MemoryStream templateStream = new MemoryStream()) { templateStream.Write(templateBytes, 0, (int)templateBytes.Length); using (WordprocessingDocument doc = WordprocessingDocument.Open(templateStream, true)) { doc.ChangeDocumentType(WordprocessingDocumentType.Document); var mainPart = doc.MainDocumentPart; // Get the Document Settings Part DocumentSettingsPart documentSettingPart1 = mainPart.DocumentSettingsPart; // Create a new attachedTemplate and specify a relationship ID AttachedTemplate attachedTemplate1 = new AttachedTemplate() { Id = "relationId1" }; // Append the attached template to the DocumentSettingsPart documentSettingPart1.Settings.Append(attachedTemplate1); // Add an ExternalRelationShip of type AttachedTemplate. // Specify the path of template and the relationship ID documentSettingPart1.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate", new Uri(projPath + "MSWordTemplates\\template4.dotx", UriKind.Absolute), "relationId1"); string fullname = string.Format("{0} {1}", myResume.FirstName, myResume.LastName); SetCCText(mainPart, "FullName", fullname); SetCCText(mainPart, "Goal", myResume.Goal); SetCCText(mainPart, "Location", myResume.CurrentLocation); string email = myResume.Contacts.First(c => c.ContactTitle.Title.Equals("EMail")).Data; SetCCText(mainPart, "Email", email); string phone = myResume.Contacts.First(c => c.ContactTitle.Title.Equals("Phone")).Data; SetCCText(mainPart, "Phone", phone); RemoveCCChild(mainPart, "OtherContacts"); foreach (var contact in myResume.Contacts.Where(c => !c.ContactTitle.Title.Equals("EMail") && !c.ContactTitle.Title.Equals("Phone"))) { AppendCCText(mainPart, "OtherContacts", string.Format("{0}: {1}", contact.ContactTitle.Title, contact.Data)); } // ОБРАЗОВАНИЕ if (myResume.Education.Count > 0) { SdtBlock contentControl = mainPart.Document.Body.Descendants <SdtBlock>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "Section_Education").Single(); Table theTable = contentControl.Descendants <Table>().Single(); TableRow defaultRow = theTable.Elements <TableRow>().Last(); foreach (var institution in myResume.Education) { TableRow rowCopy = (TableRow)defaultRow.CloneNode(true); // период учебы var periodRun = rowCopy.Descendants <TableCell>().ElementAt(0).GetFirstChild <Paragraph>().GetFirstChild <Run>(); periodRun.GetFirstChild <Text>().Text = string.Format("{0} –", institution.From.Format()); periodRun.Append(new Break()); periodRun.Append(new Text(institution.To.Format())); // описание уч. заведениия: // название и город TableCell secondColumn = rowCopy.Descendants <TableCell>().ElementAt(1); SetCCText(secondColumn, "InstitutionName", string.Format("{0}, г. {1}", institution.Name, institution.City)); // кафедра if (string.IsNullOrEmpty(institution.Department)) { secondColumn.Descendants <SdtRun>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "InstitutionDepartment").Single().Parent.Remove(); } else { SetCCText(secondColumn, "InstitutionDepartment", institution.Department); } // специальность SetCCText(secondColumn, "InstitutionSpeciality", institution.Specialty); secondColumn.Elements <Paragraph>().Last().Append(new Run(new Break())); theTable.AppendChild(rowCopy); } theTable.RemoveChild(defaultRow); } else { mainPart.Document.Body.Descendants <SdtBlock>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "Section_Education").Single().Remove(); } // ОПЫТ РАБОТЫ if (myResume.WorkExp.Count > 0) { SdtBlock contentControl = mainPart.Document.Body.Descendants <SdtBlock>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "Section_Experience").Single(); Table theTable = contentControl.Descendants <Table>().Single(); TableRow defaultRow = theTable.Elements <TableRow>().Last(); foreach (var workPlace in myResume.WorkExp) { TableRow rowCopy = (TableRow)defaultRow.CloneNode(true); // период в который работали var periodRun = rowCopy.Descendants <TableCell>().ElementAt(0).GetFirstChild <Paragraph>().GetFirstChild <Run>(); periodRun.GetFirstChild <Text>().Text = string.Format("{0} –", workPlace.From.Format()); periodRun.Append(new Break()); periodRun.Append(new Text(workPlace.To.Format())); // описание работы: // название работы и город TableCell secondColumn = rowCopy.Descendants <TableCell>().ElementAt(1); SetCCText(secondColumn, "WorkplaceName", string.Format("{0}, г. {1}", workPlace.Name, workPlace.City)); // должность SetCCText(secondColumn, "WorkplacePosition", workPlace.Position); // обязанности if (workPlace.Duties.Count > 0) { RemoveCCChild(secondColumn, "WorkplaceDuties"); foreach (var duty in workPlace.Duties) { AppendCCText(secondColumn, "WorkplaceDuties", string.Format("– {0}", duty.Name)); } } else { secondColumn.Descendants <SdtRun>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "WorkplaceDuties").Single().Parent.Remove(); } //secondColumn.Elements<Paragraph>().Last().Append(new Run(new Break())); theTable.AppendChild(rowCopy); } theTable.RemoveChild(defaultRow); } else { mainPart.Document.Body.Descendants <SdtBlock>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "Section_Experience").Single().Remove(); } // СЕРТИФИКАТЫ if (myResume.CertificatesAndTrainings.Count > 0) { RemoveCCChild(mainPart, "Certificates"); foreach (var certificate in myResume.CertificatesAndTrainings) { AppendCCText(mainPart, "Certificates", string.Format("{0} – {1}{2}", certificate.Date.Year, certificate.Name, certificate.Location != null ? string.Format(", г. {0}", certificate.Location) : "")); } } else { RemoveCC(mainPart, "Section_Certificates"); } // ЯЗЫКИ if (myResume.Languages.Count > 0) { SdtBlock contentControl = mainPart.Document.Body.Descendants <SdtBlock>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "Languages").Single(); SdtContentBlock contentRun = contentControl.GetFirstChild <SdtContentBlock>(); Paragraph defaultLi = contentRun.GetFirstChild <Paragraph>(); foreach (var language in myResume.Languages) { Paragraph copy = (Paragraph)defaultLi.CloneNode(true); copy.Descendants <Text>().Where(t => t.Text == "lang").Single().Text = language.Name; copy.Descendants <Text>().Where(t => t.Text == "level").Single().Text = language.Level; contentRun.Append(copy); } contentRun.RemoveChild(defaultLi); } else { RemoveCC(mainPart, "Section_Languages"); } // ЛИЧНЫЕ КАЧЕСТВА if (myResume.PersonalQualities.Count > 0) { SdtBlock contentControl = mainPart.Document.Body.Descendants <SdtBlock>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "PersonalQualities").Single(); SdtContentBlock contentRun = contentControl.GetFirstChild <SdtContentBlock>(); Paragraph defaultLi = contentRun.GetFirstChild <Paragraph>(); foreach (var quality in myResume.PersonalQualities) { Paragraph copy = (Paragraph)defaultLi.CloneNode(true); copy.Descendants <Text>().Where(t => t.Text == "quality").Single().Text = quality.Name; contentRun.Append(copy); } contentRun.RemoveChild(defaultLi); } else { mainPart.Document.Body.Descendants <SdtBlock>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "Section_PersonalQualities").Single().Remove(); } // НАВЫКИ if (myResume.Skills.Count > 0) { SdtBlock contentControl = mainPart.Document.Body.Descendants <SdtBlock>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "Skills").Single(); SdtContentBlock contentRun = contentControl.GetFirstChild <SdtContentBlock>(); Paragraph defaultLi = contentRun.GetFirstChild <Paragraph>(); foreach (var skill in myResume.Skills) { Paragraph copy = (Paragraph)defaultLi.CloneNode(true); copy.Descendants <Text>().Where(t => t.Text == "skill").Single().Text = skill.Name; contentRun.Append(copy); } contentRun.RemoveChild(defaultLi); } else { mainPart.Document.Body.Descendants <SdtBlock>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "Section_Skills").Single().Remove(); } mainPart.Document.Save(); } File.WriteAllBytes(outFilePath, templateStream.ToArray()); } }
public static MemoryStream CreateOverTimeWorkApplication(OverTimeManagement overTimeManagement) { MemoryStream ms = new MemoryStream(); SPSecurity.RunWithElevatedPrivileges(delegate() { string templateFileName = "OverTimeWorkApplicationTemplate.docx"; string tempFolderPath = SPUtility.GetVersionedGenericSetupPath(@"TEMPLATE\LAYOUTS\RBVH.Stada.Intranet.ReportTemplates\OverTimeWorkApplication", 15); Directory.CreateDirectory(tempFolderPath); RemoveOldFiles(tempFolderPath, 1); string destFilePath = ""; string newFileName = string.Format("{0}-{1}.docx", "OverTimeWorkApplication", DateTime.Now.Ticks); destFilePath = DownloadFile(SPContext.Current.Site.RootWeb.Url, "Shared Documents", templateFileName, tempFolderPath, newFileName); try { using (WordprocessingDocument wordProcessingDoc = WordprocessingDocument.Open(destFilePath, true)) { List <SdtContentCell> requestedby1 = wordProcessingDoc.MainDocumentPart.Document.GetTextBoxByNameFromTable("requestedby"); requestedby1[0].FillTextBox(!string.IsNullOrEmpty(overTimeManagement.Requester.LookupValue) ? overTimeManagement.Requester.LookupValue : " "); List <SdtBlock> requestedby2 = wordProcessingDoc.MainDocumentPart.Document.GetTextBoxByName("requestedby"); requestedby2[0].FillTextBox(!string.IsNullOrEmpty(overTimeManagement.Requester.LookupValue) ? overTimeManagement.Requester.LookupValue : " "); List <SdtContentCell> department = wordProcessingDoc.MainDocumentPart.Document.GetTextBoxByNameFromTable("department"); department[0].FillTextBox(!string.IsNullOrEmpty(overTimeManagement.CommonDepartment1066.LookupValue) ? overTimeManagement.CommonDepartment1066.LookupValue : " "); var fromDate = overTimeManagement.OverTimeManagementDetailList.Min(x => x.OvertimeFrom).ToString("dd/MM/yyyy"); List <SdtContentCell> from = wordProcessingDoc.MainDocumentPart.Document.GetTextBoxByNameFromTable("from"); from[0].FillTextBox(!string.IsNullOrEmpty(fromDate) ? fromDate : " "); var toDate = overTimeManagement.OverTimeManagementDetailList.Max(x => x.OvertimeTo).ToString("dd/MM/yyyy"); List <SdtContentCell> to = wordProcessingDoc.MainDocumentPart.Document.GetTextBoxByNameFromTable("to"); to[0].FillTextBox(!string.IsNullOrEmpty(toDate) ? toDate : " "); List <SdtContentCell> place = wordProcessingDoc.MainDocumentPart.Document.GetTextBoxByNameFromTable("place"); place[0].FillTextBox(!string.IsNullOrEmpty(overTimeManagement.Place) ? overTimeManagement.Place : " "); List <SdtContentCell> quantity = wordProcessingDoc.MainDocumentPart.Document.GetTextBoxByNameFromTable("quantity"); quantity[0].FillTextBox(overTimeManagement.SumOfEmployee + " "); List <SdtContentCell> serving = wordProcessingDoc.MainDocumentPart.Document.GetTextBoxByNameFromTable("serving"); serving[0].FillTextBox(overTimeManagement.SumOfMeal + " "); List <SdtContentCell> others = wordProcessingDoc.MainDocumentPart.Document.GetTextBoxByNameFromTable("others"); others[0].FillTextBox(!string.IsNullOrEmpty(overTimeManagement.OtherRequirements) ? overTimeManagement.OtherRequirements : " "); List <SdtBlock> tables = wordProcessingDoc.MainDocumentPart.Document.GetTextBoxByName("table1"); if (tables != null && tables.Count() > 0) { string templateStr = File.ReadAllText(Path.Combine(SPUtility.GetVersionedGenericSetupPath(@"TEMPLATE\LAYOUTS\RBVH.Stada.Intranet.ReportTemplates\XML", 15), "overtimetabletemplate.xml")); Table newTable = new Table(templateStr); TableRow rowTemplate = newTable.Descendants <TableRow>().Last(); List <string> propertyList = new List <string>() { }; for (int i = 0; i < overTimeManagement.OverTimeManagementDetailList.Count; i++) { var detail = overTimeManagement.OverTimeManagementDetailList[i]; TableRow newTableRow = new TableRow(); newTableRow.TableRowProperties = new TableRowProperties(rowTemplate.TableRowProperties.OuterXml); TableCell cellTemplate1 = rowTemplate.Descendants <TableCell>().ElementAt(0); TableCell newTableCell1 = new TableCell(cellTemplate1.OuterXml); newTableCell1.Descendants <Text>().First().Text = (i + 1).ToString(); newTableRow.Append(newTableCell1); TableCell cellTemplate2 = rowTemplate.Descendants <TableCell>().ElementAt(1); TableCell newTableCell2 = new TableCell(cellTemplate2.OuterXml); newTableCell2.Descendants <Text>().First().Text = detail.Employee.LookupValue; newTableRow.Append(newTableCell2); TableCell cellTemplate3 = rowTemplate.Descendants <TableCell>().ElementAt(2); TableCell newTableCell3 = new TableCell(cellTemplate3.OuterXml); newTableCell3.Descendants <Text>().First().Text = detail.EmployeeID.LookupValue; newTableRow.Append(newTableCell3); TableCell cellTemplate4 = rowTemplate.Descendants <TableCell>().ElementAt(3); TableCell newTableCell4 = new TableCell(cellTemplate4.OuterXml); newTableCell4.Descendants <Text>().First().Text = WORKING_HOUR_IN_PDF; newTableRow.Append(newTableCell4); TableCell cellTemplate5 = rowTemplate.Descendants <TableCell>().ElementAt(4); TableCell newTableCell5 = new TableCell(cellTemplate5.OuterXml); newTableCell5.Descendants <Text>().First().Text = detail.OvertimeHours; newTableRow.Append(newTableCell5); TableCell cellTemplate6 = rowTemplate.Descendants <TableCell>().ElementAt(5); TableCell newTableCell6 = new TableCell(cellTemplate6.OuterXml); newTableCell6.Descendants <Text>().First().Text = detail.Task == null ? "" : detail.Task; newTableRow.Append(newTableCell6); TableCell cellTemplate7 = rowTemplate.Descendants <TableCell>().ElementAt(6); TableCell newTableCell7 = new TableCell(cellTemplate7.OuterXml); newTableCell7.Descendants <Text>().First().Text = detail.CompanyTransport; newTableRow.Append(newTableCell7); TableCell cellTemplate8 = rowTemplate.Descendants <TableCell>().ElementAt(7); TableCell newTableCell8 = new TableCell(cellTemplate8.OuterXml); newTableCell8.Descendants <Text>().First().Text = ""; newTableRow.Append(newTableCell8); newTable.Append(newTableRow); } newTable.Descendants <TableRow>().ElementAt(1).Remove(); tables[0].Parent.InsertAfter(newTable, tables[0]); tables[0].Remove(); } wordProcessingDoc.MainDocumentPart.Document.Save(); } using (FileStream file = new FileStream(destFilePath, FileMode.Open, FileAccess.Read)) { byte[] bytes = new byte[file.Length]; file.Read(bytes, 0, (int)file.Length); ms.Write(bytes, 0, (int)file.Length); } } catch { } }); return(ms); }