public Task <DataTable> GetTable(int tbl, string _filename) { return(Task.Run(() => { GetTableArrayProgress(0, 100); var dataTableForReturn = new DataTable(); using (WordprocessingDocument myDocument = WordprocessingDocument.Open(_filename, false)) { DocumentFormat.OpenXml.Wordprocessing.Table tabl = myDocument.MainDocumentPart.Document.Body .Elements <DocumentFormat.OpenXml.Wordprocessing.Table>().ElementAt(tbl); if (tabl != null) { int rowNumber = tabl.Elements <TableRow>().Count(); for (int i = 0; i < rowNumber; i++) { DataRow nrow = null; int coumnNumber = tabl.Elements <TableRow>().ElementAt(i).Elements <TableCell>().Count(); if (i > 0) { nrow = dataTableForReturn.NewRow(); } for (int j = 0; j < coumnNumber; j++) { string cell = tabl.Elements <TableRow>().ElementAt(i).Elements <TableCell>().ElementAt(j).InnerText.Trim(' '); if (i == 0) { dataTableForReturn.Columns.Add(cell); continue; } if (dataTableForReturn.Columns.Count < coumnNumber) { dataTableForReturn.Columns.Add(cell); } if (nrow != null) { nrow[j] = ReplaceTex.EnterSimbol(cell); } } if (nrow != null) { dataTableForReturn.Rows.Add(nrow); } GetTableArrayProgress(i, rowNumber); } } } return dataTableForReturn; })); }
/* * static void Main(string[] args) * { * string appPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); * * string wordFile = appPath + "\\TestDoc.docx"; * * DataTable dataTable = ReadWordTable(wordFile); * * if (dataTable != null) * { * string sFile = appPath + "\\ExportExcel.xlsx"; * * ExportDataTableToExcel(dataTable, sFile); * * Console.WriteLine("Contents of word table exported to excel spreadsheet"); * * Console.ReadKey(); * } * } */ /// <summary> /// This method reads the contents of table using openxml sdk /// </summary> /// <param name="fileName"></param> /// <returns></returns> public static DataTable ReadWordTable(Word.Table myTable) { DataTable table; try { List <List <string> > totalRows = new List <List <string> >(); int maxCol = 0; foreach (TableRow row in myTable.Elements <TableRow>()) { List <string> tempRowValues = new List <string>(); foreach (TableCell cell in row.Elements <TableCell>()) { tempRowValues.Add(cell.InnerText); } maxCol = ProcessList(tempRowValues, totalRows, maxCol); } table = ConvertListListStringToDataTable(totalRows, maxCol); return(table); } catch (Exception ex) { Console.WriteLine(ex.Message); return(null); } }
/// <summary> /// Get table gridCols information and convert to twip to Points. /// </summary> /// <param name="table"></param> /// <returns></returns> private float[] getTableGridCols(Word.Table table) { float[] grids = null; if (table == null) { return(grids); } // Get grids and their width Word.TableGrid grid = (Word.TableGrid)table.Elements <Word.TableGrid>().FirstOrDefault(); if (grid != null) { List <Word.GridColumn> gridCols = grid.Elements <Word.GridColumn>().ToList(); if (gridCols.Count > 0) { grids = new float[gridCols.Count]; for (int i = 0; i < gridCols.Count; i++) { if (gridCols[i].Width != null) { grids[i] = Tools.ConvertToPoint(gridCols[i].Width.Value, Tools.SizeEnum.TwentiethsOfPoint, -1f); } else { grids[i] = 0f; } } } } return(grids); }
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 ReadWordTableToSave(string filePath) { using (var document = WordprocessingDocument.Open(filePath, true)) { var docPart = document.MainDocumentPart; var doc = docPart.Document; DocumentFormat.OpenXml.Wordprocessing.Table myTable = doc.Body.Descendants <DocumentFormat.OpenXml.Wordprocessing.Table>().FirstOrDefault(); List <List <string> > totalRows = new List <List <string> >(); int rows = 0; int columns = 0; List <PositionInfo> pInfoList = new List <PositionInfo>(); PositionInfo pInfo; foreach (TableRow row in myTable.Elements <TableRow>()) { rows++; columns = 0; List <string> tempRowValues = new List <string>(); foreach (TableCell cell in row.Elements <TableCell>()) { columns++; pInfo = new PositionInfo(); pInfo.RowIndex = rows; pInfo.ColumnIndex = columns; pInfo.Content = cell.InnerText; pInfoList.Add(pInfo); } } } }
private void ChangeTextWord(WordprocessingDocument doc) { // Encuentra la primera tabla en el documento. Table table = doc.MainDocumentPart.Document.Body.Elements <Table>().First(); // Encuentra la segunda y tercera fila en la tabla. TableRow row1 = table.Elements <TableRow>().ElementAt(1); TableRow row2 = table.Elements <TableRow>().ElementAt(2); // Encuentra las celdas a modificar. TableCell cellNombre = row1.Elements <TableCell>().ElementAt(1); TableCell cellApellido = row1.Elements <TableCell>().ElementAt(3); TableCell cellEdad = row2.Elements <TableCell>().ElementAt(1); TableCell cellDireccion = row2.Elements <TableCell>().ElementAt(3); // Llena las celdas con los datos de la primera fila de la primera tabla del dataset. cellNombre.AppendChild(new Paragraph(new Run(new Text("Freddy")))); cellApellido.AppendChild(new Paragraph(new Run(new Text("Quintero")))); cellEdad.AppendChild(new Paragraph(new Run(new Text("29")))); cellDireccion.AppendChild(new Paragraph(new Run(new Text("Porlamar")))); }
public void InsertProfiloRischio(string profiloRischio) { T table = FindByCaption("TABELLACLASSEDIRISCHIO"); TableRow innerRow = table.Elements <TableRow>().ElementAt(0); foreach (TableCell innerCell in innerRow.Elements <TableCell>()) { if (innerCell.InnerText == profiloRischio) { innerCell.TableCellProperties.Shading.Fill = "CC9900"; } } }
//字体正确返回1错误返回0 //字号正确返回1错误返回0 //Center正确返回1错误返回0 protected int[] TableText(DocumentFormat.OpenXml.Wordprocessing.Table table, WordprocessingDocument doc, string font, string enFont, string size, string justification) { int[] a = new int[4] { 1, 1, 1, 1 }; IEnumerable <TableRow> tr = table.Elements <TableRow>(); if (tr != null) { foreach (TableRow trs in tr) { IEnumerable <TableCell> tc = trs.Elements <TableCell>(); if (tc != null) { foreach (TableCell tcs in tc) { IEnumerable <DocumentFormat.OpenXml.Wordprocessing.Paragraph> paras = tcs.Elements <DocumentFormat.OpenXml.Wordprocessing.Paragraph>(); if (paras != null) { foreach (DocumentFormat.OpenXml.Wordprocessing.Paragraph p in paras) { if (p != null) { if (Util.correctfonts(p, doc, font, enFont) == false) { a[0] = 0; } if (Util.correctsize(p, doc, size) == false) { a[1] = 0; } if (Util.correctJustification(p, doc, justification) == false) { a[2] = 0; } if (Util.correctBold(p, doc, false) == false) { a[3] = 0; } } } } } } } } return(a); }
/// <summary> /// This method reads the contents of table using openxml sdk /// </summary> /// <param name="fileName"></param> /// <returns></returns> public static DataTable ReadWordTable(string fileName) { DataTable table; try { using (var document = WordprocessingDocument.Open(fileName, false)) { var docPart = document.MainDocumentPart; var doc = docPart.Document; DocumentFormat.OpenXml.Wordprocessing.Table myTable = doc.Body.Descendants <DocumentFormat.OpenXml.Wordprocessing.Table>().First(); List <List <string> > totalRows = new List <List <string> >(); int maxCol = 0; foreach (TableRow row in myTable.Elements <TableRow>()) { List <string> tempRowValues = new List <string>(); foreach (TableCell cell in row.Elements <TableCell>()) { tempRowValues.Add(cell.InnerText); } maxCol = ProcessList(tempRowValues, totalRows, maxCol); } table = ConvertListListStringToDataTable(totalRows, maxCol); } return(table); } catch (Exception ex) { Console.WriteLine(ex.Message); return(null); } }
// TODO: get row height (not total row height): http://kuujinbo.info/iTextSharp/rowHeights.aspx public void ParseTable(Word.Table t) { if (t == null) { return; } this.table = t; this.tableColumnsWidth = this.getTableGridCols(this.table); this.colLen = this.tableColumnsWidth.Count(); int cellId = 0; int rowId = 0; foreach (Word.TableRow row in table.Elements <Word.TableRow>()) { bool rowStart = true; // w:gridBefore Word.GridBefore tmpGridBefore = (Word.GridBefore)StHelper.GetAppliedElement <Word.GridBefore>(row); int skipGridsBefore = (tmpGridBefore != null && tmpGridBefore.Val != null) ? tmpGridBefore.Val.Value : 0; // w:gridAfter Word.GridAfter tmpGridAfter = (Word.GridAfter)StHelper.GetAppliedElement <Word.GridAfter>(row); int skipGridsAfter = (tmpGridAfter != null && tmpGridAfter.Val != null) ? tmpGridAfter.Val.Value : 0; int colId = 0; // gridBefore (with same cellId and set as blank) if (skipGridsBefore > 0) { for (int i = 0; i < skipGridsBefore; i++) { cells.Add(new TableHelperCell(this, cellId, rowId, colId)); colId++; // increase for each cells.Add() Debug.Write(String.Format("{0:X} ", cellId)); } cellId++; } foreach (Word.TableCell col in row.Elements <Word.TableCell>()) { int _cellId = cellId; int _cellcount = 1; TableHelperCell basecell = new TableHelperCell(this, _cellId, rowId, colId); if (rowStart) { basecell.rowStart = true; rowStart = false; } basecell.row = row; basecell.cell = col; // process rowspan and colspan if (col.TableCellProperties != null) { // colspan if (col.TableCellProperties.GridSpan != null) { _cellcount = col.TableCellProperties.GridSpan.Val; } // rowspan if (col.TableCellProperties.VerticalMerge != null) { // "continue": get cellId from (rowId-1):(colId) if (col.TableCellProperties.VerticalMerge.Val == null || col.TableCellProperties.VerticalMerge.Val == "continue") { _cellId = cells[(this.ColumnLength * (rowId - 1)) + colId].cellId; } // "restart": the begin of rowspan else { _cellId = cellId; } } } basecell.cellId = _cellId; cells.Add(basecell); colId++; // increase for each cells.Add() Debug.Write(String.Format("{0:X} ", _cellId)); for (int i = 1; i < _cellcount; i++) { // Add spanned cells cells.Add(new TableHelperCell(this, _cellId, rowId, colId)); colId++; // increase for each cells.Add() Debug.Write(String.Format("{0:X} ", _cellId)); } // The latest cellId was used, then we must increase it for future usage if (cellId == _cellId) { cellId++; } } int rowEndIndex = cells.Count - 1; int rowEndCellId = cells[rowEndIndex].cellId; while (rowEndIndex > 0 && cells[rowEndIndex - 1].cellId == rowEndCellId) { rowEndIndex--; } cells[rowEndIndex].rowEnd = true; // gridAfter (with same cellId and set as blank) if (skipGridsAfter > 0 && colId < this.ColumnLength) { for (int i = 0; i < skipGridsAfter; i++) { cells.Add(new TableHelperCell(this, cellId, rowId, colId)); colId++; // increase for each cells.Add() Debug.Write(String.Format("{0:X} ", cellId)); } cellId++; } rowId++; Debug.Write("\n"); } this.rowLen = rowId; // ====== Adjust table columns width by their content ====== this.adjustTableColumnsWidth(); // ====== Resolve cell border conflict ====== // prepare table conditional formatting (border), which will be used in // applyCellBorders() so must be called before applyCellBorders() this.rollingUpTableBorders(); for (int r = 0; r < this.RowLength; r++) { // The following handles the situation where // if table innerV is set, and cnd format for first row specifies nill border, then nil border wins. // if table innerH is set, and cnd format for first columns specifies nil border, then table innerH wins. //// TODO: if row's cellspacing is not zero then bypass this row //Word.TableCellSpacing tcspacing = _CvrtCell.GetTableRow(cells, r).TableRowProperties.Descendants<Word.TableCellSpacing>().FirstOrDefault(); //if (tcspacing.Type.Value != Word.TableWidthUnitValues.Nil) // continue; for (int c = 0; c < this.ColumnLength; c++) { TableHelperCell me = this.GetCell(r, c); if (me.Blank) { continue; } if (me.Borders == null) { me.Borders = this.applyCellBorders(me.cell.Descendants <Word.TableCellBorders>().FirstOrDefault(), (me.colId == 0) | me.rowStart, (me.colId + this.GetColSpan(me.cellId) == this.ColumnLength) | me.rowEnd, (me.rowId == 0), (me.rowId + this.GetRowSpan(me.cellId) == this.RowLength) ); } int colspan = this.GetColSpan(me.cellId); int rowspan = this.GetRowSpan(me.cellId); // Process the cells at the right side of me // Can bypass column-spanned cells because they never exist if ((c + (colspan - 1) + 1) < this.ColumnLength) // not last column { List <TableHelperCell> rights = new List <TableHelperCell>(); for (int i = 0; i < rowspan; i++) { TableHelperCell tmp = this.GetCell(r + i, c + (colspan - 1) + 1); if (tmp != null && !tmp.Blank) { rights.Add(tmp); } } if (rights.Count > 0) { foreach (TableHelperCell right in rights) { if (right.Borders == null) { right.Borders = this.applyCellBorders(right.cell.Descendants <Word.TableCellBorders>().FirstOrDefault(), (right.colId == 0) | right.rowStart, (right.colId + this.GetColSpan(right.cellId) == this.ColumnLength) | right.rowEnd, (right.rowId == 0), (right.rowId + this.GetRowSpan(right.cellId) == this.RowLength) ); } bool meWin = compareBorder(me.Borders, right.Borders, compareDirection.Horizontal); if (meWin) { StyleHelper.CopyAttributes(right.Borders.LeftBorder, me.Borders.RightBorder); } } me.Borders.RightBorder.ClearAllAttributes(); } } // Process the cells below me // Can't bypass row-spanned cells because they still have tcBorders property if ((r + 1) < this.RowLength) // not last row { List <TableHelperCell> bottoms = new List <TableHelperCell>(); for (int i = 0; i < colspan; i++) { TableHelperCell tmp = this.GetCell(r + 1, c + i); if (tmp != null && !tmp.Blank) { bottoms.Add(tmp); } } foreach (TableHelperCell bottom in bottoms) { if (bottom.Borders == null) { bottom.Borders = this.applyCellBorders(bottom.cell.Descendants <Word.TableCellBorders>().FirstOrDefault(), (bottom.colId == 0) | bottom.rowStart, (bottom.colId + this.GetColSpan(bottom.cellId) == this.ColumnLength) | bottom.rowEnd, (bottom.rowId == 0), (bottom.rowId + this.GetRowSpan(bottom.cellId) == this.RowLength) ); } bool meWin = compareBorder(me.Borders, bottom.Borders, compareDirection.Vertical); if (meWin) { StyleHelper.CopyAttributes(bottom.Borders.TopBorder, me.Borders.BottomBorder); } } } } } if (this.cells.Count > 0) { // re-process each cell's border conflict with its bottom cell for (int i = 0; i < this.cells[this.cells.Count - 1].cellId; i++) { TableHelperCell me = this.GetCellByCellId(i); if (me.Blank) // ignore gridBefore/gridAfter cells { continue; } if (me.RowSpan > 1) { // merge bottom border from the last cell of row-spanned cells TableHelperCell meRowEnd = this.GetCell(me.rowId + (me.RowSpan - 1), me.colId); if (meRowEnd != null && meRowEnd.Borders != null && meRowEnd.Borders.BottomBorder != null) { StyleHelper.CopyAttributes(me.Borders.BottomBorder, meRowEnd.Borders.BottomBorder); } } if (me.rowId + me.RowSpan < this.RowLength) { // if me is not at the last row, compare the border with the cell below it TableHelperCell bottom = this.GetCellByCellId(this.GetCell(me.rowId + me.RowSpan, me.colId).cellId); bool meWin = compareBorder(me.Borders, bottom.Borders, compareDirection.Vertical); if (!meWin) { me.Borders.BottomBorder.ClearAllAttributes(); } } } } }
private void setupGapTables() { gapTables = true; String templateDoc = _projecto.Template_Mnemonica; String filename = templatePath + "\\" + templateDoc + "_GAP.docx"; String[] tempShadingKey = {"T","G1","G2","G3","G4"}; using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(filename, true)) { tableRankT = (wp.Table)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Table>().ElementAt(0).Clone(); tableRankB = (wp.Table)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Table>().ElementAt(1).Clone(); tableRankC = (wp.Table)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Table>().ElementAt(2).Clone(); tableRankP = (wp.Table)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Table>().ElementAt(3).Clone(); tableRankO = (wp.Table)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Table>().ElementAt(4).Clone(); wp.Shading shading = (wp.Shading)tableRankT.Elements<wp.TableRow>().First().Elements<wp.TableCell>().First().Elements<wp.TableCellProperties>().First().Elements<wp.Shading>().First(); GroupShading.Add(tempShadingKey[0], shading.Fill); shading = (wp.Shading)tableRankB.Elements<wp.TableRow>().First().Elements<wp.TableCell>().First().Elements<wp.TableCellProperties>().First().Elements<wp.Shading>().First(); GroupShading.Add(tempShadingKey[1], shading.Fill); shading = (wp.Shading)tableRankC.Elements<wp.TableRow>().First().Elements<wp.TableCell>().First().Elements<wp.TableCellProperties>().First().Elements<wp.Shading>().First(); GroupShading.Add(tempShadingKey[2], shading.Fill); shading = (wp.Shading)tableRankP.Elements<wp.TableRow>().First().Elements<wp.TableCell>().First().Elements<wp.TableCellProperties>().First().Elements<wp.Shading>().First(); GroupShading.Add(tempShadingKey[3], shading.Fill); shading = (wp.Shading)tableRankO.Elements<wp.TableRow>().First().Elements<wp.TableCell>().First().Elements<wp.TableCellProperties>().First().Elements<wp.Shading>().First(); GroupShading.Add(tempShadingKey[4], shading.Fill); trRankRowImpar = (wp.TableRow)tableRankT.Elements<wp.TableRow>().ElementAt(1); trRankRowPar = (wp.TableRow)tableRankT.Elements<wp.TableRow>().ElementAt(2); symbUp = trRankRowImpar.Elements<wp.TableCell>().ElementAt(3).Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Elements<wp.SymbolChar>().First() as wp.SymbolChar; symbH = trRankRowPar.Elements<wp.TableCell>().ElementAt(3).Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Elements<wp.SymbolChar>().First() as wp.SymbolChar; symbDw = tableRankT.Elements<wp.TableRow>().ElementAt(3).Elements<wp.TableCell>().ElementAt(3).Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Elements<wp.SymbolChar>().First() as wp.SymbolChar; symbUpRun = trRankRowImpar.Elements<wp.TableCell>().ElementAt(3).Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Clone() as wp.Run; symbHRun = trRankRowPar.Elements<wp.TableCell>().ElementAt(3).Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Clone() as wp.Run; symbDwRun = tableRankT.Elements<wp.TableRow>().ElementAt(3).Elements<wp.TableCell>().ElementAt(3).Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Clone() as wp.Run; tableRankT.Elements<wp.TableRow>().ElementAt(1).Remove(); tableRankT.Elements<wp.TableRow>().ElementAt(1).Remove(); tableRankT.Elements<wp.TableRow>().ElementAt(1).Remove(); trRankRowImpar.Elements<wp.TableCell>().ElementAt(3).Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Remove(); trRankRowPar.Elements<wp.TableCell>().ElementAt(3).Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Remove(); parHeadingParT = (wp.Paragraph)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Paragraph>().ElementAt(0); parHeadingParB = (wp.Paragraph)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Paragraph>().ElementAt(1); parHeadingParC = (wp.Paragraph)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Paragraph>().ElementAt(2); parHeadingParP = (wp.Paragraph)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Paragraph>().ElementAt(3); parHeadingParO = (wp.Paragraph)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Paragraph>().ElementAt(4); } }
private void setupHARankTable() { String templateDoc = _projecto.Template_Mnemonica; String filename = rootPath + "docTemplates\\" + templateDoc + "_RANK_HA.docx"; using (WordprocessingDocument tempDoc = WordprocessingDocument.Open(filename, true)) { tempTable = (wp.Table)tempDoc.MainDocumentPart.Document.Body.Elements<wp.Table>().ElementAt(0).Clone(); tempRowHeader = (wp.TableRow)tempTable.Elements<wp.TableRow>().ElementAt(0).Clone(); tempRowImpar = (wp.TableRow)tempTable.Elements<wp.TableRow>().ElementAt(1).Clone(); tempTable.Elements<wp.TableRow>().ElementAt(1).Remove(); tempParagraph = tempDoc.MainDocumentPart.Document.Body.Descendants<wp.Paragraph>().ElementAt(0).Clone() as wp.Paragraph; } }
//判断是否为三线表 是为true protected bool correctTable(DocumentFormat.OpenXml.Wordprocessing.Table t) { int tcCount = 0; IEnumerable <TableRow> trList = t.Elements <TableRow>(); int rowCount = trList.Count <TableRow>(); TableProperties tpr = t.GetFirstChild <TableProperties>(); TableBorders tb = tpr.GetFirstChild <TableBorders>(); if (tpr != null) { if (tb != null) { if (rowCount <= 2) { return(true); } foreach (TableRow tr in trList) { tcCount++; IEnumerable <TableCell> tcList = tr.Elements <TableCell>(); foreach (TableCell tc in tcList) { TableCellProperties tcp = tc.GetFirstChild <TableCellProperties>(); int bottom = 1; if (tcp != null) { TableCellBorders tcb = tcp.GetFirstChild <TableCellBorders>(); if (tcb != null) { if (tcb.GetFirstChild <LeftBorder>() != null) { if (tcb.GetFirstChild <LeftBorder>().Val != "nil") { return(false); } } if (tcb.GetFirstChild <RightBorder>() != null) { if (tcb.GetFirstChild <RightBorder>().Val != "nil") { return(false); } } //第一行 if (tcCount == 1) { if (tcb.GetFirstChild <BottomBorder>() != null) { if (tcb.GetFirstChild <BottomBorder>().Val == "nil") { bottom = 0; } } else { if (tb.GetFirstChild <InsideHorizontalBorder>() != null) { if (tb.GetFirstChild <InsideHorizontalBorder>().Val == "none") { return(false); } } } if (tcb.GetFirstChild <TopBorder>() != null) { if (tcb.GetFirstChild <TopBorder>().Val == "nil") { return(false); } } else { if (tb.GetFirstChild <TopBorder>() != null) { if (tb.GetFirstChild <TopBorder>().Val == "none") { return(false); } } } } //第二行的top if (tcCount == 2) { if (tcb.GetFirstChild <TopBorder>() != null) { if (tcb.GetFirstChild <TopBorder>().Val == "nil" && bottom == 0) { return(false); } } } //除去第一行和最后一行的其他所有行 if (tcCount != 1 && tcCount != rowCount) { if (tcb.GetFirstChild <BottomBorder>() != null) { if (tcb.GetFirstChild <BottomBorder>().Val == "single") { return(false); } } else { if (tcCount != 2 && tb.GetFirstChild <InsideHorizontalBorder>() != null && tb.GetFirstChild <InsideHorizontalBorder>().Val == "single") { return(false); } } } //最后一行并且不是第二行 if (tcCount == rowCount && tcCount != 2) { if (tcb.GetFirstChild <TopBorder>() != null) { if (tcb.GetFirstChild <TopBorder>().Val == "single") { return(false); } } else { if (tb.GetFirstChild <InsideHorizontalBorder>() != null && tb.GetFirstChild <InsideHorizontalBorder>().Val == "single") { return(false); } } if (tcb.GetFirstChild <BottomBorder>() != null) { if (tcb.GetFirstChild <BottomBorder>().Val == "nil") { return(false); } } else { if (tb.GetFirstChild <BottomBorder>() != null) { if (tb.GetFirstChild <BottomBorder>().Val == "none") { return(false); } } } } } //没有tcb的情况 else { //第一行 if (tcCount == 1) { if (tb.GetFirstChild <TopBorder>() != null) { if (tb.GetFirstChild <TopBorder>().Val == "none") { return(false); } } if (tb.GetFirstChild <InsideHorizontalBorder>() != null) { if (tb.GetFirstChild <InsideHorizontalBorder>().Val == "none") { return(false); } } } //中间行 if (tcCount != 1 && tcCount != rowCount) { if (tcCount != 2 && tb.GetFirstChild <InsideHorizontalBorder>() != null && tb.GetFirstChild <InsideHorizontalBorder>().Val == "single") { return(false); } } //最后一行 if (tcCount == rowCount && tcCount - 1 != rowCount) { if (tb.GetFirstChild <InsideHorizontalBorder>() != null && tb.GetFirstChild <InsideHorizontalBorder>().Val == "single") { return(false); } if (tb.GetFirstChild <BottomBorder>() != null) { if (tb.GetFirstChild <BottomBorder>().Val == "none") { return(false); } } } } } } } } } return(true); }
public static void Fill(OpenXmlElement docNode, XmlElement macroListXml, WordprocessingDocument wdDoc) { /* Форматированный текст для встроенных элементов */ IEnumerable <Paragraph> paragraphs = docNode.Elements <Paragraph>(); foreach (Paragraph paragraph in paragraphs) { IEnumerable <SdtRun> sdtRuns = paragraph.Elements <SdtRun>(); foreach (SdtRun sdtRun in sdtRuns) { // Из SdtProperties взять Tag для идентификации Content Control SdtProperties sdtProperties = sdtRun.GetFirstChild <SdtProperties>(); Tag tag = sdtProperties.GetFirstChild <Tag>(); // Найти в macroListXml Node макропеременной String macroVarValue = FindMacroVar(macroListXml, tag.Val); if (macroVarValue != null) { // Сохранить старый стиль Run SdtContentRun sdtContentRun = sdtRun.GetFirstChild <SdtContentRun>(); OpenXmlElement oldRunProps = sdtContentRun.GetFirstChild <Run>().GetFirstChild <RunProperties>().CloneNode(true); // Очистить Node Content Control sdtContentRun.RemoveAllChildren(); // Создать новую Run Node Run newRun = sdtContentRun.AppendChild(new Run()); // Вернуть старый стиль newRun.AppendChild(oldRunProps); // Вставить текст (без переносов строк!!!) newRun.AppendChild(new Text(macroVarValue)); } } } /* Получить остальные Content Control */ IEnumerable <SdtBlock> sdtBlocks = docNode.Elements <SdtBlock>(); foreach (SdtBlock sdtBlock in sdtBlocks) { // Получить параметры(SdtProperties) Content Control SdtProperties sdtProperties = sdtBlock.GetFirstChild <SdtProperties>(); // Получить Tag для идентификации Content Control Tag tag = sdtProperties.GetFirstChild <Tag>(); // Получить значение макроперенной из macroListXml Console.WriteLine("Tag: " + tag.Val); String macroVarValue = FindMacroVar(macroListXml, tag.Val); // Если макропеременная есть в MacroListXml if (macroVarValue != null) { Console.WriteLine("Value: " + macroVarValue); // Получить блок содержимого Content Control SdtContentBlock sdtContentBlock = sdtBlock.GetFirstChild <SdtContentBlock>(); /* Форматированный текст для абзацев */ if (sdtProperties.GetFirstChild <SdtPlaceholder>() != null && sdtContentBlock.GetFirstChild <Paragraph>() != null) { // Сохранить старый стиль параграфа ParagraphProperties oldParagraphProperties = sdtContentBlock.GetFirstChild <Paragraph>().GetFirstChild <ParagraphProperties>().CloneNode(true) as ParagraphProperties; String oldParagraphPropertiesXml = oldParagraphProperties.InnerXml; // Очистить ноду с контентом sdtContentBlock.RemoveAllChildren(); InsertText(macroVarValue, oldParagraphPropertiesXml, sdtContentBlock); } /* Таблицы */ if (sdtProperties.GetFirstChild <SdtPlaceholder>() != null && sdtContentBlock.GetFirstChild <Table>() != null) { // Получить ноду таблицы Table table = sdtContentBlock.GetFirstChild <Table>(); // Получить все строки таблицы IEnumerable <TableRow> tableRows = table.Elements <TableRow>(); // Получить вторую строку из таблицы TableRow tableRow = tableRows.ElementAt(1) as TableRow; Type tableRowType = tableRow.GetType(); // Получить все стили столбцов List <String> paragraphCellStyles = new List <string>(); IEnumerable <OpenXmlElement> tableCells = tableRow.Elements <TableCell>(); foreach (OpenXmlElement tableCell in tableCells) { String paragraphCellStyleXml = tableCell.GetFirstChild <Paragraph>().GetFirstChild <ParagraphProperties>().InnerXml; paragraphCellStyles.Add(paragraphCellStyleXml); } // Удалить все строки, после первой while (tableRows.Count <TableRow>() > 1) { TableRow lastTableRows = tableRows.Last <TableRow>(); lastTableRows.Remove(); } // Удалить последний элемент, если это не TableRow OpenXmlElement lastNode = table.LastChild; if (lastNode.GetType() != tableRowType) { lastNode.Remove(); } string[] rowDelimiters = new string[] { "|||" }; string[] columnDelimiters = new string[] { "^^^" }; // Получить массив строк из макропеременной String[] rowsXml = macroVarValue.Split(rowDelimiters, StringSplitOptions.None); int i = 0; while (i < rowsXml.Length) { // Получить строку String rowXml = rowsXml[i]; // Добавить ноду строки таблицы TableRow newTableRow = table.AppendChild(new TableRow()); // Получить из строки массив ячеек String[] cellsXml = rowXml.Split(columnDelimiters, StringSplitOptions.None); int j = 0; while (j < cellsXml.Length) { // Получить ячейку String cellXml = cellsXml[j]; // Убрать символ CRLF в конце строки cellXml = cellXml.TrimEnd(new char[] { '\n', '\r' }); // Добавить ноду ячейку в строку таблицы TableCell newTableCell = newTableRow.AppendChild(new TableCell()); // Вставить текст InsertText(cellXml, paragraphCellStyles[j], newTableCell); j++; } i++; } } /* Картинки */ if (sdtProperties.GetFirstChild <SdtContentPicture>() != null) { // Получить путь к файлу String imageFilePath = macroVarValue; // Получить расширение файла String extension = System.IO.Path.GetExtension(imageFilePath).ToLower(); ImagePartType imagePartType; switch (extension) { case "jpeg": imagePartType = ImagePartType.Jpeg; break; case "jpg": imagePartType = ImagePartType.Jpeg; break; case "png": imagePartType = ImagePartType.Png; break; case "bmp": imagePartType = ImagePartType.Bmp; break; case "gif": imagePartType = ImagePartType.Gif; break; default: imagePartType = ImagePartType.Jpeg; break; } ; // Добавить ImagePart в документ ImagePart imagePart = wdDoc.MainDocumentPart.AddImagePart(imagePartType); // Получить картинку using (FileStream stream = new FileStream(imageFilePath, FileMode.Open)) { imagePart.FeedData(stream); } // Вычислить width и height Bitmap img = new Bitmap(imageFilePath); var widthPx = img.Width; var heightPx = img.Height; var horzRezDpi = img.HorizontalResolution; var vertRezDpi = img.VerticalResolution; const int emusPerInch = 914400; const int emusPerCm = 360000; var widthEmus = (long)(widthPx / horzRezDpi * emusPerInch); var heightEmus = (long)(heightPx / vertRezDpi * emusPerInch); // Получить ID ImagePart string relationShipId = wdDoc.MainDocumentPart.GetIdOfPart(imagePart); Paragraph paragraph = sdtContentBlock.GetFirstChild <Paragraph>(); Run run = paragraph.GetFirstChild <Run>(); Drawing drawing = run.GetFirstChild <Drawing>(); Inline inline = drawing.GetFirstChild <Inline>(); Graphic graphic = inline.GetFirstChild <Graphic>(); GraphicData graphicData = graphic.GetFirstChild <GraphicData>(); Picture pic = graphicData.GetFirstChild <Picture>(); BlipFill blipFill = pic.GetFirstChild <BlipFill>(); Blip blip = blipFill.GetFirstChild <Blip>(); string prefix = "r"; string localName = "embed"; string namespaceUri = @"http://schemas.openxmlformats.org/officeDocument/2006/relationships"; OpenXmlAttribute oldEmbedAttribute = blip.GetAttribute("embed", namespaceUri); IList <OpenXmlAttribute> attributes = blip.GetAttributes(); if (oldEmbedAttribute != null) { attributes.Remove(oldEmbedAttribute); } // Удалить хз что, выявлено практическим путем blipFill.RemoveAllChildren <SourceRectangle>(); // Установить новую картинку blip.SetAttribute(new OpenXmlAttribute(prefix, localName, namespaceUri, relationShipId)); blip.SetAttribute(new OpenXmlAttribute("cstate", "", "print")); // Подогнать размеры Extent extent = inline.GetFirstChild <Extent>(); OpenXmlAttribute oldCxExtent = extent.GetAttribute("cx", ""); if (oldCxExtent != null) { var maxWidthEmus = long.Parse(oldCxExtent.Value); if (widthEmus > maxWidthEmus) { var ratio = (heightEmus * 1.0m) / widthEmus; widthEmus = maxWidthEmus; heightEmus = (long)(widthEmus * ratio); } extent.GetAttributes().Remove(oldCxExtent); } OpenXmlAttribute oldCyExtent = extent.GetAttribute("cy", ""); if (oldCyExtent != null) { extent.GetAttributes().Remove(oldCyExtent); } extent.SetAttribute(new OpenXmlAttribute("cx", "", widthEmus.ToString())); extent.SetAttribute(new OpenXmlAttribute("cy", "", heightEmus.ToString())); ShapeProperties shapeProperties = pic.GetFirstChild <ShapeProperties>(); Transform2D transform2D = shapeProperties.GetFirstChild <Transform2D>(); Extents extents = transform2D.GetFirstChild <Extents>(); OpenXmlAttribute oldCxExtents = extents.GetAttribute("cx", ""); if (oldCxExtents != null) { extents.GetAttributes().Remove(oldCxExtents); } OpenXmlAttribute oldCyExtents = extents.GetAttribute("cy", ""); if (oldCyExtents != null) { extents.GetAttributes().Remove(oldCyExtents); } extents.SetAttribute(new OpenXmlAttribute("cx", "", widthEmus.ToString())); extents.SetAttribute(new OpenXmlAttribute("cy", "", heightEmus.ToString())); // Удалить placeholder ShowingPlaceholder showingPlaceholder = sdtProperties.GetFirstChild <ShowingPlaceholder>(); if (showingPlaceholder != null) { sdtProperties.RemoveChild <ShowingPlaceholder>(showingPlaceholder); } } /* Повторяющийся раздел */ if (sdtProperties.GetFirstChild <SdtRepeatedSection>() != null) { // Представить repeatedSection как новый xml документ (сделать корнем) XmlDocument repeatedSectionXml = new XmlDocument(); repeatedSectionXml.LoadXml(macroVarValue); // Получить корневой элемент repeatedSection XmlElement rootRepeatedSectionXml = repeatedSectionXml.DocumentElement; // Получить количество repeatedSectionItem XmlNodeList repeatedSectionItems = rootRepeatedSectionXml.SelectNodes("repeatedSectionItem"); int repeatedItemCount = repeatedSectionItems.Count; Console.WriteLine("Количество repeatedSectionItem: " + repeatedItemCount); /* Блок клонирования ноды повтор. раздела до нужного количества */ for (int i = 0; i < repeatedItemCount; i++) { XmlElement macroListRepeatedSectionItem = rootRepeatedSectionXml.SelectSingleNode(String.Format(@"repeatedSectionItem[@id=""{0}""]", i)) as XmlElement; Console.WriteLine("Item " + i + ": " + macroListRepeatedSectionItem.OuterXml); SdtContentBlock sdtContentBlockRepeatedSectionItem = sdtContentBlock.Elements <SdtBlock>().Last <SdtBlock>().GetFirstChild <SdtContentBlock>(); Fill(sdtContentBlockRepeatedSectionItem, macroListRepeatedSectionItem, wdDoc); if (i + 1 < repeatedItemCount) { SdtBlock clonedRepeatedSectionItem = sdtContentBlock.GetFirstChild <SdtBlock>().Clone() as SdtBlock; sdtContentBlock.AppendChild <SdtBlock>(clonedRepeatedSectionItem); } } /**/ //Fill(sdtContentBlock, macroListRepeatedSection, wdDoc); } } Console.WriteLine(); } }
private void setupHAAADerailersTableTemplate() { String templateDoc = _projecto.Template_Mnemonica; String filename = rootPath + "docTemplates\\" + templateDoc + "_DERAILER_HAAA.docx"; using (WordprocessingDocument tempDoc = WordprocessingDocument.Open(filename, true)) { tempTable = (wp.Table)tempDoc.MainDocumentPart.Document.Body.Elements<wp.Table>().ElementAt(0).Clone(); // selecciona as linhas tempRowHeader = (wp.TableRow)tempTable.Elements<wp.TableRow>().ElementAt(0).Clone(); tempRowSeparador = (wp.TableRow)tempTable.Elements<wp.TableRow>().ElementAt(1).Clone(); tempRowHeader2 = (wp.TableRow)tempTable.Elements<wp.TableRow>().ElementAt(2).Clone(); tempRowImpar = (wp.TableRow)tempTable.Elements<wp.TableRow>().ElementAt(3).Clone(); tempRowPar = (wp.TableRow)tempTable.Elements<wp.TableRow>().ElementAt(4).Clone(); // selecciona os símbolos // Target // Neutro // A Desenvolver // linhas 3,4 e 5 Coluna 1 symbDelevop = tempRowImpar.Elements<wp.TableCell>().ElementAt(3).Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Elements<wp.SymbolChar>().First() as wp.SymbolChar; tempRowImpar.Elements<wp.TableCell>().ElementAt(3).Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Elements<wp.SymbolChar>().First().Remove(); symbNeutral = tempRowPar.Elements<wp.TableCell>().ElementAt(3).Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Elements<wp.SymbolChar>().First() as wp.SymbolChar; tempRowPar.Elements<wp.TableCell>().ElementAt(3).Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Elements<wp.SymbolChar>().First().Remove(); symbTarget = tempTable.Elements<wp.TableRow>().ElementAt(5).Elements<wp.TableCell>().ElementAt(3).Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Elements<wp.SymbolChar>().First() as wp.SymbolChar; tempTable.Elements<wp.TableRow>().ElementAt(5).Elements<wp.TableCell>().ElementAt(3).Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Elements<wp.SymbolChar>().First().Remove(); // limpa a tabela tempTable.Elements<wp.TableRow>().ElementAt(0).Remove(); tempTable.Elements<wp.TableRow>().ElementAt(0).Remove(); tempTable.Elements<wp.TableRow>().ElementAt(0).Remove(); tempTable.Elements<wp.TableRow>().ElementAt(0).Remove(); tempTable.Elements<wp.TableRow>().ElementAt(0).Remove(); tempTable.Elements<wp.TableRow>().ElementAt(0).Remove(); tempParagraph = tempDoc.MainDocumentPart.Document.Body.Descendants<wp.Paragraph>().ElementAt(0).Clone() as wp.Paragraph; } }
private void setupHABehaveTableTemplate() { String templateDoc = _projecto.Template_Mnemonica; String filename = rootPath + "docTemplates\\" + templateDoc + "_BEHAVE_HA.docx"; using (WordprocessingDocument tempDoc = WordprocessingDocument.Open(filename, true)) { tempTable = (wp.Table)tempDoc.MainDocumentPart.Document.Body.Elements<wp.Table>().ElementAt(0).Clone(); tempRowHeader = (wp.TableRow)tempTable.Elements<wp.TableRow>().ElementAt(0).Clone(); tempRowHeader2 = (wp.TableRow)tempTable.Elements<wp.TableRow>().ElementAt(1).Clone(); tempRowImpar = (wp.TableRow)tempTable.Elements<wp.TableRow>().ElementAt(2).Clone(); tempRowPar = (wp.TableRow)tempTable.Elements<wp.TableRow>().ElementAt(3).Clone(); symbUp = tempRowImpar.Elements<wp.TableCell>().ElementAt(1).Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Elements<wp.SymbolChar>().First() as wp.SymbolChar; symbH = tempRowPar.Elements<wp.TableCell>().ElementAt(1).Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Elements<wp.SymbolChar>().First() as wp.SymbolChar; symbDw = tempTable.Elements<wp.TableRow>().ElementAt(4).Elements<wp.TableCell>().ElementAt(1).Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Elements<wp.SymbolChar>().First() as wp.SymbolChar; tempTable.Elements<wp.TableRow>().ElementAt(0).Remove(); tempTable.Elements<wp.TableRow>().ElementAt(0).Remove(); tempTable.Elements<wp.TableRow>().ElementAt(0).Remove(); tempTable.Elements<wp.TableRow>().ElementAt(0).Remove(); tempTable.Elements<wp.TableRow>().ElementAt(0).Remove(); tempParagraph = tempDoc.MainDocumentPart.Document.Body.Descendants<wp.Paragraph>().ElementAt(0).Clone() as wp.Paragraph; } }
private void InsertTableWord(WordprocessingDocument doc) { // Encuentra la segunda tabla en el documento. Table table = doc.MainDocumentPart.Document.Body.Elements <Table>().ElementAt(1); // Encuentra la segunda fila en la tabla. TableRow row = table.Elements <TableRow>().ElementAt(1); // Encuentra la celda a modificar. TableCell cell = row.Elements <TableCell>().First(); // Crea la tabla. Table tbl = new Table(); // Establece estiloy y anchura a la tabla. TableProperties tableProp = new TableProperties(); TableStyle tableStyle = new TableStyle() { Val = "TableGrid" }; // Hace que la tabla ocupe el 100% de la pagina. TableWidth tableWidth = new TableWidth() { Width = "5000", Type = TableWidthUnitValues.Pct }; // Aplicar propiedades a la tabla. tableProp.Append(tableStyle, tableWidth); tbl.AppendChild(tableProp); // Define las columnas de la tabla. TableGrid tg = new TableGrid(); foreach (DataColumn column in ds.Tables[0].Columns) { tg.AppendChild(new GridColumn()); } tbl.AppendChild(tg); // Fila para las columnas de la tabla. TableRow tblRowColumns = new TableRow(); tbl.AppendChild(tblRowColumns); // Obtiene y asigna nombres a las columnas de la tabla. foreach (DataColumn column in ds.Tables[0].Columns) { TableCell tblCell = new TableCell(new Paragraph(new Run(new Text(column.ColumnName)))); tblRowColumns.AppendChild(tblCell); } // Agrega el resto de las filas a la tabla. foreach (DataRow dtRow in ds.Tables[0].Rows) { TableRow tblRow = new TableRow(); for (int i = 0; i < dtRow.Table.Columns.Count; i++) { TableCell tblCell = new TableCell(new Paragraph(new Run(new Text(dtRow[i].ToString())))); tblRow.AppendChild(tblCell); } tbl.AppendChild(tblRow); } // Agrega la tabla al placeholder correspondiente. cell.AppendChild(new Paragraph(new Run(tbl))); }
private void setupRankingTables() { rankingTables = true; String templateDoc = _projecto.Template_Mnemonica; String filename = rootPath + "docTemplates\\" + templateDoc + "_RANKING.docx"; using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(filename, true)) { tableRankS = (wp.Table)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Table>().ElementAt(0).Clone(); tableRankT = (wp.Table)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Table>().ElementAt(1).Clone(); tableRankB = (wp.Table)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Table>().ElementAt(2).Clone(); tableRankC = (wp.Table)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Table>().ElementAt(3).Clone(); tableRankP = (wp.Table)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Table>().ElementAt(4).Clone(); tableRankO = (wp.Table)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Table>().ElementAt(5).Clone(); trRankRowImpar = (wp.TableRow)tableRankS.Elements<wp.TableRow>().ElementAt(1); trRankRowPar = (wp.TableRow)tableRankS.Elements<wp.TableRow>().ElementAt(2); tableRankS.Elements<wp.TableRow>().ElementAt(1).Remove(); tableRankS.Elements<wp.TableRow>().ElementAt(1).Remove(); parHeadingParS = (wp.Paragraph)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Paragraph>().ElementAt(0); parHeadingParT = (wp.Paragraph)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Paragraph>().ElementAt(1); parHeadingParB = (wp.Paragraph)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Paragraph>().ElementAt(2); parHeadingParC = (wp.Paragraph)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Paragraph>().ElementAt(3); parHeadingParP = (wp.Paragraph)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Paragraph>().ElementAt(4); parHeadingParO = (wp.Paragraph)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Paragraph>().ElementAt(5); } }
private void setupAABehaveTableTemplate() { String templateDoc = _projecto.Template_Mnemonica; String filename = templatePath + "\\" + templateDoc + "_BEHAVE_AA.docx"; using (WordprocessingDocument tempDoc = WordprocessingDocument.Open(filename, true)) { tempTable = (wp.Table)tempDoc.MainDocumentPart.Document.Body.Elements<wp.Table>().ElementAt(0).Clone(); tempRowHeader = (wp.TableRow)tempTable.Elements<wp.TableRow>().ElementAt(0).Clone(); tempRowSeparador = (wp.TableRow)tempTable.Elements<wp.TableRow>().ElementAt(1).Clone(); tempRowHeader2 = (wp.TableRow)tempTable.Elements<wp.TableRow>().ElementAt(2).Clone(); tempRowImpar = (wp.TableRow)tempTable.Elements<wp.TableRow>().ElementAt(3).Clone(); tempRowPar = (wp.TableRow)tempTable.Elements<wp.TableRow>().ElementAt(4).Clone(); tempTable.Elements<wp.TableRow>().ElementAt(0).Remove(); tempTable.Elements<wp.TableRow>().ElementAt(0).Remove(); tempTable.Elements<wp.TableRow>().ElementAt(0).Remove(); tempTable.Elements<wp.TableRow>().ElementAt(0).Remove(); tempTable.Elements<wp.TableRow>().ElementAt(0).Remove(); tempParagraph = tempDoc.MainDocumentPart.Document.Body.Descendants<wp.Paragraph>().ElementAt(0).Clone() as wp.Paragraph; } }