Пример #1
0
        /// <summary>
        /// Creates a new Table from the supplied input data.
        /// </summary>
        /// <param name="json">
        /// String in JSON format representing the tabular data for updating the Chart's cached data points.
        /// The JSON object must contain a "fields" attribute as an array containing the field/column names.
        /// The JSON object must contain a "rows" attribute as an array of arrays representing the rows and their values, with values matching the same order and cardinality of the field names.
        /// This is the same data as the underlying Excel spreadsheet contents.</param>
        /// <param name="tableStyle">
        /// String containing the name of the Wordprocessing.TableStyle to apply to the table.</param>
        /// <returns>
        /// Returns a new Wordprocessing.Table containing the tabular data from the JSON input, formatted with the specified TableStyle.</returns>
        public static wp.Table BuildTable(string json, string tableStyle)
        {
            json = ((json == String.Empty) || (json == null)) ? "{\"fields\": [ \"No Results\" ], \"rows\": [[ \"No Results\" ]]}" : json;

            //Splunk JSON data is a series of objects consisting of multiple key(column)/value(row) pairs in the result attribute.
            dynamic input = JsonConvert.DeserializeObject <dynamic>(json);

            if (input["rows"].Count == 0)
            {
                json  = "{\"fields\": [ \"No Results\" ], \"rows\": [[ \"No Results\" ]]}";
                input = JsonConvert.DeserializeObject <dynamic>(json);
            }

            wp.Table result = new wp.Table();

            wp.TableProperties tableProperties1 = new wp.TableProperties();
            wp.TableStyle      tableStyle1      = new wp.TableStyle()
            {
                Val = tableStyle
            };
            wp.TableWidth tableWidth1 = new wp.TableWidth()
            {
                Width = "5000", Type = wp.TableWidthUnitValues.Pct
            };

            tableProperties1.Append(tableStyle1);
            tableProperties1.Append(tableWidth1);
            result.Append(tableProperties1);


            wp.TableGrid tableGrid = new wp.TableGrid();

            //Build table header row
            wp.TableRow headerRow = new wp.TableRow();
            foreach (var columnName in input["fields"])
            {
                headerRow.Append(new wp.TableCell(new wp.Paragraph(new wp.Run(new wp.Text(columnName.ToString())))));
                tableGrid.Append(new wp.GridColumn());
            }
            result.Append(tableGrid);
            result.Append(headerRow);

            //Build table data rows
            foreach (var row in input["rows"])
            {
                wp.TableRow tr = new wp.TableRow();
                foreach (var cell in row)
                {
                    tr.Append(new wp.TableCell(new wp.Paragraph(new wp.Run(new wp.Text(cell.ToString())))));
                }
                result.Append(tr);
            }

            return(result);
        }
Пример #2
0
        private void adjustTableColumnsWidth()
        {
            if (this.table == null)
            {
                return;
            }

            // Get table total width
            float totalWidth = -1f;
            bool  autoWidth  = false;

            Word.TableWidth tableWidth = this.styleHelper.GetAppliedElement <Word.TableWidth>(this.table);
            if (tableWidth != null && tableWidth.Type != null)
            {
                switch (tableWidth.Type.Value)
                {
                case Word.TableWidthUnitValues.Nil:
                case Word.TableWidthUnitValues.Auto:     // fits the contents
                default:
                    autoWidth = true;
                    break;

                case Word.TableWidthUnitValues.Dxa:
                    if (tableWidth.Width != null)
                    {
                        totalWidth = Tools.ConvertToPoint(tableWidth.Width.Value, Tools.SizeEnum.TwentiethsOfPoint, -1f);
                    }
                    break;

                case Word.TableWidthUnitValues.Pct:
                    if (tableWidth.Width != null)
                    {
                        totalWidth = this.styleHelper.PrintablePageWidth * Tools.Percentage(tableWidth.Width.Value);
                        //if (table.Parent.GetType() == typeof(Word.Body))
                        //    totalWidth = (float)((pdfDoc.PageSize.Width - pdfDoc.LeftMargin - pdfDoc.RightMargin) * percentage(tableWidth.Width.Value));
                        //else
                        //    totalWidth = this.getCellWidth(table.Parent as Word.TableCell) * percentage(tableWidth.Width.Value);
                    }
                    break;
                }
            }
            Console.WriteLine("Table total width: " + totalWidth);

            if (!autoWidth)
            {
                scaleTableColumnsWidth(ref this.tableColumnsWidth, totalWidth);
            }
            else
            {
                totalWidth = this.tableColumnsWidth.Sum();
            }

            for (int i = 0; i < this.RowLength; i++)
            {
                // Get all cells in this row
                List <TableHelperCell> cellsInRow = this.cells.FindAll(c => c.rowId == i);
                if (cellsInRow.Count <= 0)
                {
                    continue;
                }

                // Get if any gridBefore & gridAfter
                int             skipGridsBefore = 0, skipGridsAfter = 0;
                float           skipGridsBeforeWidth = 0f, skipGridsAfterWidth = 0f;
                TableHelperCell head = cellsInRow.FirstOrDefault(c => c.rowStart);
                if (head != null)
                {
                    if (head.row.TableRowProperties != null)
                    {
                        // w:gridBefore
                        var tmpGridBefore = head.row.TableRowProperties.Elements <Word.GridBefore>().FirstOrDefault();
                        if (tmpGridBefore != null && tmpGridBefore.Val != null)
                        {
                            skipGridsBefore = tmpGridBefore.Val.Value;
                        }

                        // w:wBefore
                        var tmpGridBeforeWidth = head.row.TableRowProperties.Elements <Word.WidthBeforeTableRow>().FirstOrDefault();
                        if (tmpGridBeforeWidth != null && tmpGridBeforeWidth.Width != null)
                        {
                            skipGridsBeforeWidth = Tools.ConvertToPoint(Convert.ToInt32(tmpGridBeforeWidth.Width.Value), Tools.SizeEnum.TwentiethsOfPoint, -1f);
                        }

                        // w:gridAfter
                        var tmpGridAfter = head.row.TableRowProperties.Elements <Word.GridAfter>().FirstOrDefault();
                        if (tmpGridAfter != null && tmpGridAfter.Val != null)
                        {
                            skipGridsAfter = tmpGridAfter.Val.Value;
                        }

                        // w:wAfter
                        var tmpGridAfterWidth = head.row.TableRowProperties.Elements <Word.WidthAfterTableRow>().FirstOrDefault();
                        if (tmpGridAfterWidth != null && tmpGridAfterWidth.Width != null)
                        {
                            skipGridsAfterWidth = Tools.ConvertToPoint(Convert.ToInt32(tmpGridAfterWidth.Width.Value), Tools.SizeEnum.TwentiethsOfPoint, -1f);
                        }
                    }
                }

                int j = 0;
                int edgeEnd = 0;

                // -------
                // gridBefore
                edgeEnd = skipGridsBefore;
                for (; j < edgeEnd; j++)
                {
                    // deduce specific columns width from required width
                    skipGridsBeforeWidth -= this.tableColumnsWidth[j];
                }
                if (skipGridsBeforeWidth > 0f)
                {
                    // if required width is larger than the total width of specific columns,
                    // the remaining required width adds to the last specific column
                    this.tableColumnsWidth[edgeEnd - 1] += skipGridsBeforeWidth;
                }

                // ------
                // cells
                while (j < (cellsInRow.Count - skipGridsAfter))
                {
                    float reqCellWidth            = 0f;
                    Word.TableCellWidth cellWidth = this.styleHelper.GetAppliedElement <Word.TableCellWidth>(cellsInRow[j].cell);
                    if (cellWidth != null && cellWidth.Type != null)
                    {
                        switch (cellWidth.Type.Value)
                        {
                        case Word.TableWidthUnitValues.Auto:
                            //// TODO: calculate the items width
                            //if (cellsInRow[j].elements.Count > 0)
                            //{
                            //    iTSText.IElement element = cellsInRow[j].elements[0];
                            //}
                            break;

                        case Word.TableWidthUnitValues.Nil:
                        default:
                            break;

                        case Word.TableWidthUnitValues.Dxa:
                            if (cellWidth.Width != null)
                            {
                                reqCellWidth = Tools.ConvertToPoint(cellWidth.Width.Value, Tools.SizeEnum.TwentiethsOfPoint, -1f);
                            }
                            break;

                        case Word.TableWidthUnitValues.Pct:
                            if (cellWidth.Width != null)
                            {
                                reqCellWidth = Tools.Percentage(cellWidth.Width.Value) * totalWidth;
                            }
                            break;
                        }
                    }

                    // check row span
                    int spanCount = 1;
                    if (cellsInRow[j].cell != null)
                    {
                        Word.TableCell tmpCell = cellsInRow[j].cell;
                        if (tmpCell.TableCellProperties != null)
                        {
                            Word.GridSpan span = tmpCell.TableCellProperties.Elements <Word.GridSpan>().FirstOrDefault();
                            spanCount = (span != null && span.Val != null) ? span.Val.Value : 1;
                        }
                    }

                    edgeEnd = j + spanCount;
                    for (; j < edgeEnd; j++)
                    {
                        // deduce specific columns width from required width
                        reqCellWidth -= this.tableColumnsWidth[j];
                    }
                    if (reqCellWidth > 0f)
                    {
                        // if required width is larger than the total width of specific columns,
                        // the remaining required width adds to the last specific column
                        this.tableColumnsWidth[edgeEnd - 1] += reqCellWidth;
                    }
                }

                // ------
                // gridAfter
                edgeEnd = j + skipGridsAfter;
                for (; j < edgeEnd; j++)
                {
                    // deduce specific columns width from required width
                    skipGridsAfterWidth -= this.tableColumnsWidth[j];
                }
                if (skipGridsAfterWidth > 0f)
                {
                    // if required width is larger than the total width of specific columns,
                    // the remaining required width adds to the last specific column
                    this.tableColumnsWidth[edgeEnd - 1] += skipGridsAfterWidth;
                }

                if (!autoWidth) // fixed table width, adjust width to fit in
                {
                    scaleTableColumnsWidth(ref this.tableColumnsWidth, totalWidth);
                }
                else // auto table width
                {
                    totalWidth = this.tableColumnsWidth.Sum();
                }
            }
        }
        void ImportProjectsAndMilestones(MainDocumentPart mainPart, Word.SdtElement sdt, SPFile spreadsheetFileName)
        {
            ArrayList cellText = new ArrayList();

            // Create a Word table.
            Word.Table tbl = new Word.Table();
            Word.TableProperties tblPr = new Word.TableProperties();
            Word.TableStyle tblStyle = new Word.TableStyle();
            tblStyle.Val = "LightShading-Accent1";
            tblPr.AppendChild(tblStyle);

            Word.TableWidth tblW = new Word.TableWidth();
            tblW.Width = "5000";
            tblW.Type = Word.TableWidthUnitValues.Pct;
            tblPr.Append(tblW);
            tbl.AppendChild(tblPr);
            byte[] byteArray = spreadsheetFileName.OpenBinary();

            using (MemoryStream mem = new MemoryStream())
            {
                mem.Write(byteArray, 0, (int)byteArray.Length);

                using (SpreadsheetDocument mySpreadsheet = SpreadsheetDocument.Open(mem, true))
                {
                    WorkbookPart workbookPart = mySpreadsheet.WorkbookPart;
                    WorksheetPart worksheetPart = XLGetWorksheetPartByName(mySpreadsheet, "Sheet1");

                    Excel.SheetData sheetData =
                       worksheetPart.Worksheet.GetFirstChild<Excel.SheetData>();

                    foreach (Excel.Row r in sheetData)
                    {
                        foreach (Excel.Cell c in r)
                        {
                            cellText.Add(XLGetCellValue(c, workbookPart));
                        }
                        Word.TableRow tr = CreateRow(cellText);
                        tbl.Append(tr);
                        cellText = new ArrayList();
                    }
                }
            }
            // Swap out the content control for the SmartArt.
            OpenXmlElement parent = sdt.Parent;
            parent.InsertAfter(tbl, sdt);
            sdt.Remove();
        }
Пример #4
0
        protected word.Table GetWordTable(DataTable dataTable)
        {
            word.Table table = new word.Table();

            #region Set Table Properties
            word.TableProperties tableProperties = new word.TableProperties();
            word.TableWidth      tableWidth      = new word.TableWidth()
            {
                Type = word.TableWidthUnitValues.Pct, Width = "5000"
            };
            tableProperties.Append(tableWidth);
            UInt32Value       borderWidth  = UInt32Value.FromUInt32(5);
            word.TableBorders tableBorders = new word.TableBorders(
                new word.TopBorder
            {
                Val  = new EnumValue <word.BorderValues>(word.BorderValues.Single),
                Size = borderWidth
            },
                new word.BottomBorder
            {
                Val  = new EnumValue <word.BorderValues>(word.BorderValues.Single),
                Size = borderWidth
            },
                new word.LeftBorder
            {
                Val  = new EnumValue <word.BorderValues>(word.BorderValues.Single),
                Size = borderWidth
            },
                new word.RightBorder
            {
                Val  = new EnumValue <word.BorderValues>(word.BorderValues.Single),
                Size = borderWidth
            },
                new word.InsideHorizontalBorder
            {
                Val  = new EnumValue <word.BorderValues>(word.BorderValues.Single),
                Size = borderWidth
            },
                new word.InsideVerticalBorder
            {
                Val  = new EnumValue <word.BorderValues>(word.BorderValues.Single),
                Size = borderWidth
            });
            tableProperties.Append(tableBorders);
            table.AppendChild <word.TableProperties>(tableProperties);
            #endregion

            word.TableGrid tableGrid = new word.TableGrid();
            table.Append(tableGrid);
            if (PrintTableHeader)
            {
                word.TableRow headerRow = new word.TableRow();

                foreach (DataColumn dataColumn in dataTable.Columns)
                {
                    word.GridColumn gridColumn = new word.GridColumn();
                    word.TableCell  tableCell  = new word.TableCell();
                    tableCell.Append(GetParagraph(GetColumnName(dataColumn)));
                    headerRow.Append(tableCell);
                    tableGrid.Append(gridColumn);
                }
                table.Append(headerRow);
            }



            foreach (DataRow row in dataTable.Rows)
            {
                word.TableRow tableRow = new word.TableRow();

                foreach (object cellItem in row.ItemArray)
                {
                    word.TableCell tableCell = new word.TableCell();
                    tableCell.Append(GetParagraph(cellItem.ToString()));
                    tableRow.Append(tableCell);
                }
                table.Append(tableRow);
            }

            return(table);
        }
Пример #5
0
        private static Word.TableProperties GetTableProperties(Table table)
        {
            Word.TableWidth widthProps = new Word.TableWidth();

            switch (table.WidthUnits)
            {
                case ElementWidth.Absolute:
                    widthProps.Width = (table.Width * 20).ToString();
                    widthProps.Type = Word.TableWidthUnitValues.Dxa;
                    break;
                case ElementWidth.Percentage:
                    widthProps.Width = (table.Width * 50).ToString();
                    widthProps.Type = Word.TableWidthUnitValues.Pct;
                    break;
                default:
                    break;
            }

            Word.BorderValues border;

            switch (table.BorderType)
            {
                case TableBorders.None:
                    border = Word.BorderValues.None;
                    break;
                case TableBorders.Single:
                    border = Word.BorderValues.Single;
                    break;
                default:
                    border = Word.BorderValues.None;
                    break;
            }

            Word.TableProperties tableProps = new Word.TableProperties()
            {
                TableWidth = widthProps
                ,
                TableBorders = new Word.TableBorders()
                {

                    LeftBorder = new Word.LeftBorder()
                    {
                        Val = border
                    }
                    ,
                    RightBorder = new Word.RightBorder()
                    {
                        Val = border
                    }
                    ,
                    TopBorder = new Word.TopBorder()
                    {
                        Val = border
                    }
                    ,
                    BottomBorder = new Word.BottomBorder()
                    {
                        Val = border
                    }
                    ,
                    InsideHorizontalBorder = new Word.InsideHorizontalBorder()
                    {
                        Val = border
                    }
                    ,
                    InsideVerticalBorder = new Word.InsideVerticalBorder()
                    {
                        Val = border
                    }

                }
            };
            return tableProps;
        }
Пример #6
0
        public Wordprocessing.Table CreateTable(int columnsCount)
        {
            Wordprocessing.Table table1 = new Wordprocessing.Table();
            WorkbookPart workbookPart = _spreadsheetDocument.WorkbookPart;
            WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
            DocumentFormat.OpenXml.Spreadsheet.SheetData sheetData = worksheetPart.Worksheet.Elements<DocumentFormat.OpenXml.Spreadsheet.SheetData>().First();
            //Задание свойств таблицы
            Wordprocessing.TableProperties tableProperties1 = new Wordprocessing.TableProperties();
            Wordprocessing.TableStyle tableStyle1 = new Wordprocessing.TableStyle() { Val = "TableGrid" };
            Wordprocessing.TableWidth tableWidth1 = new Wordprocessing.TableWidth() { Width = "0", Type = Wordprocessing.TableWidthUnitValues.Auto };
            Wordprocessing.TableBorders tableBorders1 = new Wordprocessing.TableBorders();
            Wordprocessing.TopBorder topBorder1 = new Wordprocessing.TopBorder() { Val = Wordprocessing.BorderValues.Single, Color = "000000", Size = (int)4U, Space = (int)0U };
            Wordprocessing.LeftBorder leftBorder1 = new Wordprocessing.LeftBorder() { Val = Wordprocessing.BorderValues.Single, Color = "000000", Size = (int)4U, Space = (int)0U };
            Wordprocessing.BottomBorder bottomBorder1 = new Wordprocessing.BottomBorder() { Val = Wordprocessing.BorderValues.Single, Color = "000000", Size = (int)4U, Space = (int)0U };
            Wordprocessing.RightBorder rightBorder1 = new Wordprocessing.RightBorder() { Val = Wordprocessing.BorderValues.Single, Color = "000000", Size = (int)4U, Space = (int)0U };
            Wordprocessing.InsideHorizontalBorder insideHorizontalBorder1 = new Wordprocessing.InsideHorizontalBorder() { Val = Wordprocessing.BorderValues.Single, Color = "000000", Size = (int)4U, Space = (int)0U };
            Wordprocessing.InsideVerticalBorder insideVerticalBorder1 = new Wordprocessing.InsideVerticalBorder() { Val = Wordprocessing.BorderValues.Single, Color = "000000", Size = (int)4U, Space = (int)0U };
            tableBorders1.Append(topBorder1);
            tableBorders1.Append(leftBorder1);
            tableBorders1.Append(bottomBorder1);
            tableBorders1.Append(rightBorder1);
            tableBorders1.Append(insideHorizontalBorder1);
            tableBorders1.Append(insideVerticalBorder1);
            Wordprocessing.TableLook tableLook1 = new Wordprocessing.TableLook() { Val = "04A0", FirstRow = true, LastRow = false, FirstColumn = true, LastColumn = false, NoHorizontalBand = false, NoVerticalBand = true };
            tableProperties1.Append(tableStyle1);
            tableProperties1.Append(tableWidth1);
            tableProperties1.Append(tableBorders1);
            tableProperties1.Append(tableLook1);
            table1.Append(tableProperties1);

            //Создание структуры таблицы
            Wordprocessing.TableGrid tableGrid1 = new Wordprocessing.TableGrid();
            Wordprocessing.GridColumn gridColumn = new Wordprocessing.GridColumn() { Width = "9571" };
            tableGrid1.Append(gridColumn);
            table1.Append(tableGrid1);

                //Добавление информации из Excel
                int j = 0;
                foreach (Spreadsheet.Row r in sheetData.Elements<Spreadsheet.Row>())
                {
                    j = 0;
                    Wordprocessing.TableRow tableRow1 = new Wordprocessing.TableRow();
                    foreach (Spreadsheet.Cell c in r.Elements<Spreadsheet.Cell>())
                    {
                        j++;
                        string value = c.InnerText;
                        if (c.DataType!= null && c.DataType.Value == CellValues.SharedString)
                        {
                                 var stringTable = workbookPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault();
                                 if (stringTable != null) value = stringTable.SharedStringTable.ElementAt(int.Parse(value)).InnerText;
                        }

                        TableRowExtension.AddCell(tableRow1,value);
                    }
                    for (int i=j; i < columnsCount; i++) TableRowExtension.AddCell(tableRow1, "");
                    table1.Append(tableRow1);
                }

                Wordprocessing.Table table2 = doptable(table1);
                Wordprocessing.Table table3 = doptable2(table2);

             return table3;
        }