コード例 #1
0
ファイル: Md2MlCore.cs プロジェクト: NetDevArt/md2ml
        public Table CreateTable(int cols)
        {
            // TODO : Fix the bug, Applying a style to a table is not working
            Table           table           = new Table();
            TableProperties tableProperties = new TableProperties(
                new TableStyle()
            {
                Val = DocStyles.TableBlue.ToDescriptionString()
            },
                new TableWidth()
            {
                Width = "5000", Type = TableWidthUnitValues.Pct
            });

            table.AppendChild <TableProperties>(tableProperties);

            // May be useless, or for performances reasons
            TableGrid tg = new TableGrid();

            for (int i = 0; i < cols; i++)
            {
                tg.Append(new GridColumn());
            }
            table.AppendChild(tg);
            _body.Append(table);
            return(table);
        }
コード例 #2
0
ファイル: Table.cs プロジェクト: wbj2008/DocXPlus
        /// <summary>
        /// Adds a row to the table. The row will have the same number of cells as the number of columns in the table.
        /// Each cell will have an empty paragraph
        /// </summary>
        /// <returns></returns>
        public TableRow AddRow()
        {
            var tableRow = table.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableRow());

            var result = new TableRow(this, tableRow)
            {
                HeaderRow = false
            };

            if (rows == null)
            {
                rows = new List <TableRow>();
            }

            rows.Add(result);

            return(result);
        }
コード例 #3
0
 public Table(DocumentFormat.OpenXml.Wordprocessing.Table table, int row, int column)
 {
     this.table      = table;
     this.row        = row;
     this.column     = column;
     tableProperties = new TableProperties();
     table.AppendChild(tableProperties);
     CreateTable(row, column);
     AddBorder();
 }
コード例 #4
0
        static Table EditTable(WordprocessingDocument doc, List <GamesToReportViewModel> list)
        {
            Table table = doc.MainDocumentPart.Document.Body.Elements <Table>().First();
            int   i     = 1;

            foreach (var game in list)
            {
                table.AppendChild(CreateRow(i++, game));
            }

            return(table);
        }
コード例 #5
0
        public void getang()
        {
            Autodesk.AutoCAD.ApplicationServices.Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;

            string filepath = "D:\\tdoc.docx";

            using (WordprocessingDocument docX = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
            {
                try
                {
                    // Add a main document part.
                    MainDocumentPart mainPart = docX.AddMainDocumentPart();
                    StyleDefinitionsPart styleDefinitionsPart = mainPart.AddNewPart<StyleDefinitionsPart>();
                    Styles styles1 = new Styles();
                    DocDefaults docDefaults =
                        new DocDefaults(
                            new RunPropertiesDefault(new RunPropertiesBaseStyle(new RunFonts()
                            {
                                Ascii = "Times New Roman",
                                HighAnsi = "Times New Roman",
                                ComplexScript = "Times New Roman"
                            }, new FontSize() { Val = "24" },
                                new FontSizeComplexScript() { Val = "24" })),
                                new ParagraphPropertiesDefault(new SpacingBetweenLines() { After = "0", Line = "240", LineRule = LineSpacingRuleValues.Auto }));
                    styles1.AppendChild(docDefaults);
                    styleDefinitionsPart.Styles = styles1;

                    mainPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document();
                    DocumentFormat.OpenXml.Wordprocessing.Body body = mainPart.Document.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Body());
                    ParagraphProperties paragraphProperties1 = new ParagraphProperties(
                        new Justification() { Val = JustificationValues.Center },
                        new ParagraphMarkRunProperties(
                            new RunFonts()
                            {
                                Ascii = "Times New Roman",
                                HighAnsi = "Times New Roman",
                                ComplexScript = "Times New Roman"
                            },
                            new FontSize() { Val = "24" },
                            new FontSizeComplexScript() { Val = "24" }
                            ));

                    Paragraph para = body.AppendChild(new Paragraph());
                    para.AppendChild(paragraphProperties1);

                    Run run = para.AppendChild(new Run());

                    RunProperties runProperties1 = new RunProperties(
                        new Bold());

                    // String msg contains the text, "Hello, Word!"
                    run.AppendChild(runProperties1);
                    run.AppendChild(new Text("ПРИЛОЖЕНИЕ Ф"));
                    run.AppendChild(new Break());
                    run.AppendChild(new Text("Ведомость углов поворотов"));
                    run.AppendChild(new Break());

                    var table = new DocumentFormat.OpenXml.Wordprocessing.Table();
                    // Create a TableProperties object and specify its border information.
                    TableProperties tblProp = new TableProperties(
                        new TableWidth() { Width = "9782", Type = TableWidthUnitValues.Dxa },
                        new TableIndentation() { Width = -318, Type = TableWidthUnitValues.Dxa },
                        new TableBorders(
                            new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }),
                        new DocumentFormat.OpenXml.Wordprocessing.TableStyle() { Val = "TableGrid" }
                        );

                    // Append the TableProperties object to the empty table.
                    table.AppendChild<TableProperties>(tblProp);

                    // Add 3 columns to the table.
                    TableGrid tg = new TableGrid(new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(),
                        new GridColumn(), new GridColumn(), new GridColumn());
                    table.AppendChild(tg);

                    TableRow tr1 = new TableRow(
                        new TableRowProperties(new TableRowHeight() { Val = 430 }),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1709" },
                                new VerticalMerge() { Val = MergedCellValues.Restart },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()),
                                new Run(new Text("Обозначение точки")))),
                        //new TableCellProperties(new TableCellWidth() {Type = TableWidthUnitValues.Pct, Width = "500"})
                        new TableCell(
                            new TableCellProperties(
                                new GridSpan() { Val = 2 },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center },
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "3922" }),
                            new Paragraph(
                                new ParagraphProperties(new Justification() { Val = JustificationValues.Center }),
                                new Run(new Text("Координаты точки")))),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1358" },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center },
                                new VerticalMerge() { Val = MergedCellValues.Restart }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()),
                                new Run(new Text("Пикетаж")))),
                        new TableCell(
                            new TableCellProperties(
                                new GridSpan() { Val = 2 },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center },
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2368" }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()),
                                new Run(new Text("Угол")))),
                        new TableCell(new TableCellProperties(
                            new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "425" },
                            new VerticalMerge() { Val = MergedCellValues.Restart },
                            new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Прямая вставка, м"))))
                        );
                    table.AppendChild(tr1);
                    TableRow tr2 = new TableRow(
                        new TableRowProperties(new TableRowHeight() { Val = 419 }),
                        new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())),
                        new TableCell(
                            new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("Y")))),
                        new TableCell(
                            new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("X")))),
                        new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1260" },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Лево")))),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1108" },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Право")))),
                        new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())));
                    table.AppendChild(tr2);

                    TableCellProperties tcp = new TableCellProperties(new GridSpan() { Val = 7 });

                    while (true)
                    {
                        double dist = 0, paste = 0;

                        table.AppendChild(new TableRow(
                            new TableCell(
                                new TableCellProperties(
                                    new GridSpan() { Val = 7 }),
                                    new Paragraph(
                                        new ParagraphProperties(
                                            new ParagraphMarkRunProperties(new Bold()),
                                            new Justification() { Val = JustificationValues.Center }),
                                            new Run(new RunProperties(
                                                new Bold()),
                                                new Text("Трасса"))))));

                        PromptEntityOptions peo = new PromptEntityOptions("\nВыбери polyline: ");
                        peo.SetRejectMessage("Можно только polyline.");
                        peo.AddAllowedClass(typeof(Polyline), true);
                        PromptEntityResult per = ed.GetEntity(peo);
                        if (per.Status != PromptStatus.OK) { break; }

                        PromptPointResult pPtRes;
                        PromptPointOptions pPtOpts = new PromptPointOptions("");
                        // Prompt for the start point
                        pPtOpts.Message = "\nВведи начало: ";
                        pPtRes = doc.Editor.GetPoint(pPtOpts);

                        PromptDoubleOptions getpik = new PromptDoubleOptions("\nВведи пикетаж (в формате числа, а не 0+00): ");
                        PromptDoubleResult getpikRes = doc.Editor.GetDouble(getpik);
                        dist = 100 * getpikRes.Value;

                        /*
                        PromptStringOptions pStrOpts = new PromptStringOptions("\nEnter your name: ");
                        pStrOpts.AllowSpaces = true;
                        PromptResult pStrRes = doc.Editor.GetString(pStrOpts);
                        Application.ShowAlertDialog("The name entered was: " + pStrRes.StringResult);
                         */

                        Point3d curr = pPtRes.Value, next = pPtRes.Value;
                        try
                        {
                            using (Transaction tr = db.TransactionManager.StartTransaction())
                            {
                                Polyline pline = (Polyline)tr.GetObject(per.ObjectId, OpenMode.ForRead);
                                if ((pPtRes.Value == pline.GetLineSegmentAt(0).StartPoint) || (pPtRes.Value == pline.GetLineSegmentAt(0).EndPoint))
                                    for (int i = 0; i < pline.NumberOfVertices - 2; i++)
                                    {
                                        TrassaRecord temp = new TrassaRecord();
                                        temp.Name = "ВТ" + (i + 1).ToString();

                                        LineSegment3d l1 = pline.GetLineSegmentAt(i);
                                        LineSegment3d l2 = pline.GetLineSegmentAt(i + 1);
                                        double angle = GetPolylineShape(l1, l2, pline.Normal);
                                        if (angle > Math.PI)
                                        {
                                            if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint))
                                            {
                                                ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.StartPoint.X, l1.StartPoint.Y);
                                                next = l1.StartPoint;

                                                temp.CoordsX = l1.StartPoint.X.ToString("F");
                                                temp.CoordsY = l1.StartPoint.Y.ToString("F");
                                            }
                                            else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint))
                                            {
                                                ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.EndPoint.X, l1.EndPoint.Y);
                                                next = l1.EndPoint;

                                                temp.CoordsX = l1.EndPoint.X.ToString("F");
                                                temp.CoordsY = l1.EndPoint.Y.ToString("F");
                                            }
                                            angle = -(angle - Math.PI * 2.0) * 180.0 / Math.PI;
                                            ed.WriteMessage("{0},{1:0}", (int)angle / 1, (angle % 1) * 60);

                                            temp.AngleT = TrassaRecord.Angle.Right;
                                            temp.AngleVal = ((int)angle / 1).ToString("F0") + "°" + ((angle % 1) * 60).ToString("F0") + "’";
                                        }
                                        else
                                        {
                                            if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint))
                                            {
                                                ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.StartPoint.X, l1.StartPoint.Y);
                                                next = l1.StartPoint;

                                                temp.CoordsX = l1.StartPoint.X.ToString("F");
                                                temp.CoordsY = l1.StartPoint.Y.ToString("F");
                                            }
                                            else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint))
                                            {
                                                ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.EndPoint.X, l1.EndPoint.Y);
                                                next = l1.EndPoint;

                                                temp.CoordsX = l1.EndPoint.X.ToString("F");
                                                temp.CoordsY = l1.EndPoint.Y.ToString("F");
                                            }
                                            angle = angle * 180.0 / Math.PI;
                                            ed.WriteMessage("{0},{1:0}", (int)angle / 1, (angle % 1) * 60);

                                            temp.AngleT = TrassaRecord.Angle.Left;
                                            temp.AngleVal = ((int)angle / 1).ToString("F0") + "°" + ((angle % 1) * 60).ToString("F0") + "’";
                                        }

                                        paste = curr.DistanceTo(next);
                                        dist += paste;
                                        curr = next;
                                        ed.WriteMessage(" {0:0.00} {1:0.00}", dist, paste);

                                        temp.Piketaz = ((int)dist / 100).ToString("F0") + "+" + (dist % 100).ToString("F");
                                        temp.DirectInsert = paste.ToString("F");

                                        tr2 = new TableRow(
                                            new TableRowProperties(new TableRowHeight() { Val = 300 }),
                                            new TableCell(new Paragraph(new Run())),
                                            new TableCell(new Paragraph(new Run())),
                                            new TableCell(new Paragraph(new Run())),
                                            new TableCell(new Paragraph(new Run())),
                                            new TableCell(new Paragraph(new Run())),
                                            new TableCell(new Paragraph(new Run())),
                                            new TableCell(new Paragraph(new Run(new Text(temp.DirectInsert))))
                                            );
                                        table.AppendChild(tr2);
                                        tr1 = new TableRow(
                                            new TableRowProperties(new TableRowHeight() { Val = 300 }),
                                            new TableCell(new Paragraph(new Run(new Text(temp.Name)))),
                                            new TableCell(new Paragraph(new Run(new Text(temp.CoordsX)))),
                                            new TableCell(new Paragraph(new Run(new Text(temp.CoordsY)))),
                                            new TableCell(new Paragraph(new Run(new Text(temp.Piketaz)))),
                                            new TableCell(new Paragraph(new Run(new Text((temp.AngleT == TrassaRecord.Angle.Left) ? temp.AngleVal.ToString() : "")))),
                                            new TableCell(new Paragraph(new Run(new Text((temp.AngleT == TrassaRecord.Angle.Right) ? temp.AngleVal.ToString() : "")))),
                                            new TableCell(new Paragraph(new Run()))
                                            );
                                        table.AppendChild(tr1);
                                    }
                                else
                                    for (int i = pline.NumberOfVertices - 3; i >= 0; i--)
                                    {
                                        TrassaRecord temp = new TrassaRecord();
                                        temp.Name = "ВУ" + (pline.NumberOfVertices - 2 - i).ToString();

                                        LineSegment3d l1 = pline.GetLineSegmentAt(i);
                                        LineSegment3d l2 = pline.GetLineSegmentAt(i + 1);
                                        double angle = GetPolylineShape(l1, l2, pline.Normal);
                                        if (angle > Math.PI)
                                        {
                                            if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint))
                                            {
                                                ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.StartPoint.X, l1.StartPoint.Y);
                                                next = l1.StartPoint;

                                                temp.CoordsX = l1.StartPoint.X.ToString("F");
                                                temp.CoordsY = l1.StartPoint.Y.ToString("F");
                                            }
                                            else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint))
                                            {
                                                ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.EndPoint.X, l1.EndPoint.Y);
                                                next = l1.EndPoint;

                                                temp.CoordsX = l1.EndPoint.X.ToString("F");
                                                temp.CoordsY = l1.EndPoint.Y.ToString("F");
                                            }
                                            angle = -(angle - Math.PI * 2.0) * 180.0 / Math.PI;
                                            ed.WriteMessage("{0},{1:0}", (int)angle / 1, (angle % 1) * 60);

                                            temp.AngleT = TrassaRecord.Angle.Left;
                                            temp.AngleVal = ((int)angle / 1).ToString("F0") + "°" + ((angle % 1) * 60).ToString("00") + "’";
                                        }
                                        else
                                        {
                                            if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint))
                                            {
                                                ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.StartPoint.X, l1.StartPoint.Y);
                                                next = l1.StartPoint;

                                                temp.CoordsX = l1.StartPoint.X.ToString("F");
                                                temp.CoordsY = l1.StartPoint.Y.ToString("F");
                                            }
                                            else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint))
                                            {
                                                ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.EndPoint.X, l1.EndPoint.Y);
                                                next = l1.EndPoint;

                                                temp.CoordsX = l1.EndPoint.X.ToString("F");
                                                temp.CoordsY = l1.EndPoint.Y.ToString("F");
                                            }
                                            angle = angle * 180.0 / Math.PI;
                                            ed.WriteMessage("{0},{1:0}", (int)angle / 1, (angle % 1) * 60);

                                            temp.AngleT = TrassaRecord.Angle.Right;
                                            temp.AngleVal = ((int)angle / 1).ToString("F0") + "°" + ((angle % 1) * 60).ToString("00") + "’";
                                        }

                                        paste = curr.DistanceTo(next);
                                        dist += paste;
                                        curr = next;
                                        ed.WriteMessage(" {0:0.00} {1:0.00}", dist, paste);

                                        temp.Piketaz = ((int)dist / 100).ToString("F0") + "+" + (dist % 100).ToString("F");
                                        temp.DirectInsert = paste.ToString("F");

                                        tr2 = new TableRow(
                                            new TableRowProperties(new TableRowHeight() { Val = 300 }),
                                            new TableCell(new Paragraph(new Run())),
                                            new TableCell(new Paragraph(new Run())),
                                            new TableCell(new Paragraph(new Run())),
                                            new TableCell(new Paragraph(new Run())),
                                            new TableCell(new Paragraph(new Run())),
                                            new TableCell(new Paragraph(new Run())),
                                            new TableCell(new Paragraph(new Run(new Text(temp.DirectInsert))))
                                            );
                                        table.AppendChild(tr2);
                                        tr1 = new TableRow(
                                            new TableRowProperties(new TableRowHeight() { Val = 300 }),
                                            new TableCell(new Paragraph(new Run(new Text(temp.Name)))),
                                            new TableCell(new Paragraph(new Run(new Text(temp.CoordsX)))),
                                            new TableCell(new Paragraph(new Run(new Text(temp.CoordsY)))),
                                            new TableCell(new Paragraph(new Run(new Text(temp.Piketaz)))),
                                            new TableCell(new Paragraph(new Run(new Text((temp.AngleT == TrassaRecord.Angle.Left) ? temp.AngleVal.ToString() : "")))),
                                            new TableCell(new Paragraph(new Run(new Text((temp.AngleT == TrassaRecord.Angle.Right) ? temp.AngleVal.ToString() : "")))),
                                            new TableCell(new Paragraph(new Run()))
                                            );
                                        table.AppendChild(tr1);
                                    }
                            }
                        }
                        catch
                        {
                            ed.WriteMessage("\nInvalid polyline.");
                        }
                    }

                    body.AppendChild(table);
                    body.AppendChild(
                        new SectionProperties(
                            new PageMargin()
                            {
                                Top = 1134,
                                Right = (UInt32Value)850U,
                                Bottom = 1134,
                                Left = (UInt32Value)1418U,
                                Header = (UInt32Value)708U,
                                Footer = (UInt32Value)708U,
                                Gutter = (UInt32Value)0U
                            }));
                    ed.WriteMessage("\nДокумент сохранен в D:\\tdoc.docx");
                }
                catch
                {
                    ed.WriteMessage("\nError.");
                }
            }
        }
コード例 #6
0
        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();
        }
コード例 #7
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Inserts a table with 300 rows using Open Xml
            object bookmarkName = "bkflatOpc";

            if (!this.Bookmarks.Exists("bkflatOpc"))
            {
                MessageBox.Show("Please create a bookmark with name bkflatOpc");
                return;
            }
            Word.Bookmark tblBookmark = this.Bookmarks.get_Item(ref bookmarkName);
            if (tblBookmark.Range.Tables.Count > 0)
            {
                MessageBox.Show("Table already exists.Please delete this table.");
                return;
            }
            this.Application.ScreenUpdating = false;
            string openxml     = string.Empty;
            int    incrementor = 1;

            //Get existing content control id , if there is any
            if (this.ContentControls.Count > 0)
            {
                object index           = this.ContentControls.Count;
                Word.ContentControl cc = this.ContentControls.get_Item(ref index);
                contentControlSeedId = Int32.Parse(cc.ID);
                contentControlSeedId = contentControlSeedId + 1;
            }
            //Get stream for the range. This is the System.IO.Packaging.Package stream
            Stream packageStream = this.Paragraphs[1].Range.GetPackageStreamFromRange();

            //Use Open Xml SDK to process it.
            using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(packageStream, true))
            {
                //Insert image to Image Part
                ImagePart imgPart =
                    wordDoc.MainDocumentPart.AddImagePart(ImagePartType.Jpeg, "RImage");
                System.Drawing.Image img =
                    (System.Drawing.Image)Resources.ResourceManager.GetObject("RImage");
                img.Save(imgPart.GetStream(), System.Drawing.Imaging.ImageFormat.Jpeg);
                //Remove all children
                wordDoc.MainDocumentPart.Document.Body.RemoveAllChildren();
                //Generate table markup.
                DocumentFormat.OpenXml.Wordprocessing.Table table =
                    new DocumentFormat.OpenXml.Wordprocessing.Table();
                TableProperties properties =
                    new TableProperties(
                        new DocumentFormat.OpenXml.Wordprocessing.TableStyle()
                {
                    Val = "TableGrid"
                },
                        new TableWidth()
                {
                    Width = 0, Type = TableWidthUnitValues.Auto
                },
                        new TableLook()
                {
                    Val = "04A0"
                });
                table.AppendChild <TableProperties>(properties);
                for (int i = 0; i < 301; i++)
                {
                    TableRow row = new TableRow();
                    for (int j = 0; j < 3; j++)
                    {
                        incrementor++;
                        SdtCell contentControl =
                            GenerateSdtCell("Sample Text", incrementor + contentControlSeedId);
                        UInt32 value = (UInt32)(incrementor + contentControlSeedId);
                        contentControl
                        .Descendants <Run>()
                        .First()
                        .AppendChild <Drawing>
                            (GenerateDrawing("RImage", value, "RImage.jpg", 321933L, 288000L,
                                             19050L, 17957L, 0L, 0L));
                        row.AppendChild <SdtCell>(contentControl);
                    }
                    table.AppendChild <TableRow>(row);
                }
                int bookmarkCount = this.Bookmarks.Count;
                table.
                PrependChild <BookmarkStart>(new BookmarkStart()
                {
                    Name = "bkflatOpc",
                    Id   = bookmarkCount.ToString()
                }
                                             );
                table.
                AppendChild <BookmarkEnd>
                    (new BookmarkEnd()
                {
                    Id = bookmarkCount.ToString()
                });
                wordDoc.MainDocumentPart.Document
                .Body
                .AppendChild <DocumentFormat.OpenXml.Wordprocessing.Table>(table);
                wordDoc.MainDocumentPart.Document.Save();
                //Flush the contents of the package
                wordDoc.Package.Flush();
                //Convert back to flat opc using this in-memory package
                XDocument xDoc = OpcHelper.OpcToFlatOpc(wordDoc.Package);
                openxml = xDoc.ToString();
            }
            this.Application.ScreenUpdating = false;
            Word.Range range = FindRange("bkflatOpc");
            //Insert this flat opc Xml
            range.InsertXML(openxml, ref missing);
            this.Application.ScreenUpdating = true;
        }
コード例 #8
0
        protected void CreateDocumentLink_Click(object sender, EventArgs e)
        {
            FileStream fs = null;
            try
            {

                // When the user has selected a library, they will be allowed to click the button
                // The first thing we'll do is get the target library and its root folder.
                targetLibrary = hostingWeb.Lists.GetByTitle(OutputLibrary.SelectedItem.Text);
                Microsoft.SharePoint.Client.Folder destintationFolder = targetLibrary.RootFolder;
                clientContext.Load(destintationFolder);
                clientContext.ExecuteQuery();

                // Then we'll build a Word Document by using OOXML
                // Note that we'll first create it in a folder in this Web app.
                using (WordprocessingDocument wordDocument =
                    WordprocessingDocument.Create(Server.MapPath("~/SampleOOXML/LocalOOXMLDocument.docx"),
                    WordprocessingDocumentType.Document))
                {

                    // Add a main document part.
                    MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();

                    // Create the document structure.
                    mainPart.Document = new Document();
                    Body body = mainPart.Document.AppendChild(new Body());

                    // Create a paragraph.
                    Paragraph para = body.AppendChild(new Paragraph());
                    Run run = para.AppendChild(new Run());
                    run.AppendChild(new Text("Here's some text in a paragraph"));

                    // Create a table.
                    DocumentFormat.OpenXml.Wordprocessing.Table table
                        = new DocumentFormat.OpenXml.Wordprocessing.Table();

                    // Create some table border settings.
                    TableProperties borderProperties = new TableProperties(
                        new TableBorders(
                        new TopBorder
                        {
                            Val = new EnumValue<BorderValues>(BorderValues.DashDotStroked),
                            Size = 12
                        },
                        new BottomBorder
                        {
                            Val = new EnumValue<BorderValues>(BorderValues.DashDotStroked),
                            Size = 12
                        },
                        new LeftBorder
                        {
                            Val = new EnumValue<BorderValues>(BorderValues.DashDotStroked),
                            Size = 12
                        },
                        new RightBorder
                        {
                            Val = new EnumValue<BorderValues>(BorderValues.DashDotStroked),
                            Size = 12
                        },
                        new InsideHorizontalBorder
                        {
                            Val = new EnumValue<BorderValues>(BorderValues.Single),
                            Size = 12
                        },
                        new InsideVerticalBorder
                        {
                            Val = new EnumValue<BorderValues>(BorderValues.Single),
                            Size = 12
                        }));

                    // Add the table border settings to the table.
                    table.AppendChild<TableProperties>(borderProperties);

                    // Create a table row and add two cells with some text
                    var tr = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
                    var tc1 = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
                    tc1.Append(new Paragraph(new Run(new Text("Here's some text in table cell #1"))));
                    var tc2 = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
                    tc2.Append(new Paragraph(new Run(new Text("Here's some text in table cell #2"))));
                    tr.Append(tc1);
                    tr.Append(tc2);

                    // Add the row to the table, and the table to the body of the document.
                    table.Append(tr);
                    body.Append(table);
                }

                // At this stage, the local file has been created in the folder of this Web project
                // so we'll now read it and create a new file in SharePoint, based on this local file.
                byte[] documentBytes;
                fs = File.OpenRead(Server.MapPath("~/SampleOOXML/LocalOOXMLDocument.docx"));
                documentBytes = new byte[fs.Length];
                fs.Read(documentBytes, 0, Convert.ToInt32(fs.Length));

                // At this stage, the file contents of the OOXML document has been read into the byte array
                // so we can use that as the content of a new file in SharePoint.
                Microsoft.SharePoint.Client.FileCreationInformation ooxmlFile
                    = new Microsoft.SharePoint.Client.FileCreationInformation();
                ooxmlFile.Overwrite = true;
                ooxmlFile.Url = hostingWeb.Url
                    + destintationFolder.ServerRelativeUrl
                    + "/SharePointOOXMLDocument.docx";
                ooxmlFile.Content = documentBytes;
                Microsoft.SharePoint.Client.File newFile = targetLibrary.RootFolder.Files.Add(ooxmlFile);
                clientContext.Load(newFile);
                clientContext.ExecuteQuery();

                // Let the user navigate to the document library where the file has been created
                string targetUrl = hostingWeb.Url + destintationFolder.ServerRelativeUrl;
                DocumentLink.Text = "Document has been created in SharePoint! Click here to view the library";
                DocumentLink.Visible = true;
                DocumentLink.NavigateUrl = targetUrl;
            }
            catch (Exception ex)
            {
                // Tell the user what went wrong
                DocumentLink.Text = "An error has occurred: " + ex.Message;
                DocumentLink.Visible = true;
                DocumentLink.NavigateUrl = "";
            }
            finally
            {
                // Clean up our filestream object
                fs.Close();
            }
        }
コード例 #9
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);
        }
コード例 #10
0
        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();
            }
        }
コード例 #11
0
        private void AddSecondPageTable(Body body)
        {
            Table           personalInfoTable = new Table();
            TableProperties tableProps        = new TableProperties();

            AddTableBorders(tableProps);
            TableStyle tableStyle = new TableStyle()
            {
                Val = "TableGrid"
            };
            TableWidth tableWidth = new TableWidth()
            {
                Width = "5000", Type = TableWidthUnitValues.Pct
            };

            tableProps.Append(tableStyle, tableWidth);
            TableGrid tableGrid = new TableGrid();

            personalInfoTable.AppendChild(tableProps);
            for (int x = 0; x < 6; x++)
            {
                tableGrid.AppendChild(new GridColumn());
            }
            personalInfoTable.AppendChild(tableGrid);
            for (int x = 0; x < 7; x++)
            {
                TableRow         pesonalTableRow = new TableRow();
                List <TableCell> cells           = new List <TableCell>();
                for (int i = 0; i < 6; i++)
                {
                    TableCell           cell = new TableCell();
                    TableCellProperties tableCellProperties = new TableCellProperties();
                    tableCellProperties.TableCellVerticalAlignment     = new TableCellVerticalAlignment();
                    tableCellProperties.TableCellVerticalAlignment.Val = TableVerticalAlignmentValues.Center;
                    VerticalMerge   verticalMerge   = new VerticalMerge();
                    HorizontalMerge horizontalMerge = new HorizontalMerge();
                    if (x == 0)
                    {
                        horizontalMerge.Val = i == 0 ? MergedCellValues.Restart : MergedCellValues.Continue;
                        tableCellProperties.AppendChild(horizontalMerge);
                        if (i == 0)
                        {
                            SetCellText(cell, "Time Table", true);
                        }
                        else
                        {
                            SetCellText(cell, "", false);
                        }
                    }
                    else if (i == 0)
                    {
                        verticalMerge.Val = x == 1 ? MergedCellValues.Restart : MergedCellValues.Continue;
                        tableCellProperties.AppendChild(verticalMerge);
                        if (x == 1)
                        {
                            SetCellText(cell, "Hours", true);
                        }
                        else
                        {
                            SetCellText(cell, "", false);
                        }
                    }
                    else if (x == 1)
                    {
                        switch (i)
                        {
                        case 1:
                            SetCellText(cell, "Mon", true);
                            break;

                        case 2:
                            SetCellText(cell, "Tue", true);
                            break;

                        case 3:
                            SetCellText(cell, "Wed", true);
                            break;

                        case 4:
                            SetCellText(cell, "Thu", true);
                            break;

                        case 5:
                            SetCellText(cell, "Fri", true);
                            break;
                        }
                    }
                    else if (x == 4)
                    {
                        horizontalMerge.Val = i == 1 ? MergedCellValues.Restart : MergedCellValues.Continue;
                        tableCellProperties.AppendChild(horizontalMerge);
                        if (i == 1)
                        {
                            SetCellText(cell, "Lunch", true);
                        }
                        else
                        {
                            SetCellText(cell, "", false);
                        }
                    }
                    else if (x == 2 || x == 5)
                    {
                        switch (i)
                        {
                        case 1:
                        case 3:
                            SetCellText(cell, "Science", false);
                            break;

                        case 2:
                        case 4:
                            SetCellText(cell, "Maths", false);
                            break;
                        }
                    }
                    else if (x == 3 || x == 6)
                    {
                        switch (i)
                        {
                        case 1:
                        case 4:
                            SetCellText(cell, "Social", false);
                            break;

                        case 2:
                            SetCellText(cell, "History", false);
                            break;

                        case 3:
                            SetCellText(cell, "English", false);
                            break;
                        }
                    }
                    if (x == 2 && i == 5)
                    {
                        SetCellText(cell, "Arts", false);
                    }
                    else if (x == 3 && i == 5)
                    {
                        SetCellText(cell, "Sports", false);
                    }
                    else if (i == 5 && (x == 5 || x == 6))
                    {
                        if (x == 5)
                        {
                            verticalMerge.Val = MergedCellValues.Restart;
                            SetCellText(cell, "Project", false);
                        }
                        else
                        {
                            verticalMerge.Val = MergedCellValues.Continue;
                            SetCellText(cell, "", false);
                        }
                        tableCellProperties.AppendChild(verticalMerge);
                    }
                    cell.AppendChild(tableCellProperties);
                    cells.Add(cell);
                }
                pesonalTableRow.Append(cells);
                personalInfoTable.AppendChild(pesonalTableRow);
            }
            body.AppendChild(personalInfoTable);
        }
コード例 #12
0
        // Insert a table into a word processing document.
        public static void CreateTable(string fileName)
        {
            // Use the file name and path passed in as an argument
            // to open an existing Word 2007 document.

            using (WordprocessingDocument doc
                       = WordprocessingDocument.Open(fileName, true))
            {
                // Create an empty table.
                DocumentFormat.OpenXml.Wordprocessing.Table table = new DocumentFormat.OpenXml.Wordprocessing.Table();

                // Create a TableProperties object and specify its border information.
                DocumentFormat.OpenXml.Wordprocessing.TableProperties tblProp = new DocumentFormat.OpenXml.Wordprocessing.TableProperties(
                    new TableBorders(
                        new DocumentFormat.OpenXml.Wordprocessing.TopBorder()
                {
                    Val =
                        new EnumValue <BorderValues>(BorderValues.Dashed),
                    Size = 24
                },
                        new DocumentFormat.OpenXml.Wordprocessing.BottomBorder()
                {
                    Val =
                        new EnumValue <BorderValues>(BorderValues.Dashed),
                    Size = 24
                },
                        new DocumentFormat.OpenXml.Wordprocessing.LeftBorder()
                {
                    Val =
                        new EnumValue <BorderValues>(BorderValues.Dashed),
                    Size = 24
                },
                        new DocumentFormat.OpenXml.Wordprocessing.RightBorder()
                {
                    Val =
                        new EnumValue <BorderValues>(BorderValues.Dashed),
                    Size = 24
                },
                        new DocumentFormat.OpenXml.Wordprocessing.InsideHorizontalBorder()
                {
                    Val =
                        new EnumValue <BorderValues>(BorderValues.Dashed),
                    Size = 24
                },
                        new DocumentFormat.OpenXml.Wordprocessing.InsideVerticalBorder()
                {
                    Val =
                        new EnumValue <BorderValues>(BorderValues.Dashed),
                    Size = 24
                }
                        )
                    );

                // Append the TableProperties object to the empty table.
                table.AppendChild <DocumentFormat.OpenXml.Wordprocessing.TableProperties>(tblProp);

                // Create a row.
                DocumentFormat.OpenXml.Wordprocessing.TableRow tr = new  DocumentFormat.OpenXml.Wordprocessing.TableRow();

                // Create a cell.
                DocumentFormat.OpenXml.Wordprocessing.TableCell tc1 = new DocumentFormat.OpenXml.Wordprocessing.TableCell();

                // Specify the width property of the table cell.
                tc1.Append(new DocumentFormat.OpenXml.Wordprocessing.TableCellProperties(
                               new TableCellWidth()
                {
                    Type = TableWidthUnitValues.Dxa, Width = "2400"
                }));

                // Specify the table cell content.
                tc1.Append(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text("some text"))));

                // Append the table cell to the table row.
                tr.Append(tc1);

                // Create a second table cell by copying the OuterXml value of the first table cell.
                DocumentFormat.OpenXml.Wordprocessing.TableCell tc2 = new DocumentFormat.OpenXml.Wordprocessing.TableCell(tc1.OuterXml);

                // Append the table cell to the table row.
                tr.Append(tc2);

                // Append the table row to the table.
                table.Append(tr);

                // Append the table to the document.
                doc.MainDocumentPart.Document.Body.Append(table);
            }
        }
コード例 #13
0
ファイル: DocSaver.cs プロジェクト: ardier16/nure-marks
        public static void CreateWordDoc(string filepath, List <StudentData> data, string header, string info = "")
        {
            using (WordprocessingDocument document = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
            {
                MainDocumentPart mainPart = document.AddMainDocumentPart();
                mainPart.Document = new Document();
                Body body = mainPart.Document.AppendChild(new Body());

                var doc = document.MainDocumentPart.Document;
                doc.Body.Append(GenerateParagraph(header, true, "000000"));
                doc.Body.Append(GenerateParagraph(info, false, "000000"));
                doc.Body.Append(GenerateParagraph("", false, "000000"));

                DocumentFormat.OpenXml.Wordprocessing.Table table = new DocumentFormat.OpenXml.Wordprocessing.Table();

                TableProperties props = new TableProperties(
                    new TableBorders(
                        new DocumentFormat.OpenXml.Wordprocessing.TopBorder
                {
                    Val  = new EnumValue <BorderValues>(BorderValues.Single),
                    Size = 8
                },
                        new DocumentFormat.OpenXml.Wordprocessing.BottomBorder
                {
                    Val  = new EnumValue <BorderValues>(BorderValues.Single),
                    Size = 8
                },
                        new DocumentFormat.OpenXml.Wordprocessing.LeftBorder
                {
                    Val  = new EnumValue <BorderValues>(BorderValues.Single),
                    Size = 8
                },
                        new DocumentFormat.OpenXml.Wordprocessing.RightBorder
                {
                    Val  = new EnumValue <BorderValues>(BorderValues.Single),
                    Size = 8
                },
                        new DocumentFormat.OpenXml.Wordprocessing.InsideHorizontalBorder
                {
                    Val  = new EnumValue <BorderValues>(BorderValues.Single),
                    Size = 8
                },
                        new DocumentFormat.OpenXml.Wordprocessing.InsideVerticalBorder
                {
                    Val  = new EnumValue <BorderValues>(BorderValues.Single),
                    Size = 8
                }));

                table.AppendChild <TableProperties>(props);
                Justification justification1 = new Justification()
                {
                    Val = JustificationValues.Center
                };

                var th = new TableRow();

                var thc1 = new TableCell();

                thc1.Append(GenerateParagraph("№", true, "000000"));
                thc1.Append(new TableCellProperties(
                                new TableCellWidth {
                    Type = TableWidthUnitValues.Pct, Width = "5"
                }));
                th.Append(thc1);

                var thc2 = new TableCell();
                thc2.Append(GenerateParagraph("П.I.Б. студента", true, "000000"));
                thc2.Append(new TableCellProperties(
                                new TableCellWidth {
                    Type = TableWidthUnitValues.Pct, Width = "50"
                }));
                th.Append(thc2);

                var thc3 = new TableCell();
                thc3.Append(GenerateParagraph("Група", true, "000000"));
                thc3.Append(new TableCellProperties(
                                new TableCellWidth {
                    Type = TableWidthUnitValues.Pct, Width = "15"
                }));
                th.Append(thc3);

                var thc4 = new TableCell();
                thc4.Append(GenerateParagraph("Рейтинг", true, "000000"));
                thc4.Append(new TableCellProperties(
                                new TableCellWidth {
                    Type = TableWidthUnitValues.Pct, Width = "10"
                }));
                th.Append(thc4);

                var thc5 = new TableCell();
                thc5.Append(GenerateParagraph("Дод. iнформацiя", true, "000000"));
                thc5.Append(new TableCellProperties(
                                new TableCellWidth {
                    Type = TableWidthUnitValues.Pct, Width = "20"
                }));
                th.Append(thc5);

                table.Append(th);

                for (var i = 0; i < data.Count; i++)
                {
                    var tr  = new TableRow();
                    var tc1 = new TableCell();

                    tc1.Append(GenerateParagraph((i + 1).ToString(), false, "000000"));
                    tc1.Append(new TableCellProperties(
                                   new TableCellWidth {
                        Type = TableWidthUnitValues.Pct, Width = "5"
                    },
                                   new TableCellVerticalAlignment {
                        Val = TableVerticalAlignmentValues.Center
                    }));
                    tr.Append(tc1);

                    var tc2 = new TableCell();
                    tc2.Append(new Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(data[i].Name))));
                    tc2.Append(new TableCellProperties(
                                   new TableCellWidth {
                        Type = TableWidthUnitValues.Pct, Width = "50"
                    },
                                   new TableCellVerticalAlignment {
                        Val = TableVerticalAlignmentValues.Center
                    }));
                    tr.Append(tc2);

                    var tc3 = new TableCell();
                    tc3.Append(GenerateParagraph(data[i].Group, false, "000000"));
                    tc3.Append(new TableCellProperties(
                                   new TableCellWidth {
                        Type = TableWidthUnitValues.Pct, Width = "15"
                    },
                                   new TableCellVerticalAlignment {
                        Val = TableVerticalAlignmentValues.Center
                    }));
                    tr.Append(tc3);

                    var tc4 = new TableCell();
                    tc4.Append(GenerateParagraph(data[i].Rating.ToString(), true, "FFFFFF"));
                    tc4.Append(new TableCellProperties(
                                   new TableCellWidth {
                        Type = TableWidthUnitValues.Pct, Width = "10"
                    },
                                   new Shading()
                    {
                        Fill = GetRatingColor(data[i].Rating)
                    },
                                   new TableCellVerticalAlignment {
                        Val = TableVerticalAlignmentValues.Center
                    }));
                    tr.Append(tc4);

                    var tc5 = new TableCell();
                    tc5.Append(GenerateParagraph(data[i].Info, false, "000000"));
                    tc5.Append(new TableCellProperties(
                                   new TableCellWidth {
                        Type = TableWidthUnitValues.Pct, Width = "20"
                    },
                                   new TableCellVerticalAlignment {
                        Val = TableVerticalAlignmentValues.Center
                    }));
                    tr.Append(tc5);

                    table.Append(tr);
                }
                doc.Body.Append(table);
                doc.Save();
            }
        }
コード例 #14
0
        protected void btnIspisi_Click(object sender, EventArgs e)
        {
            Body      body;
            Paragraph par;
            Run       run;

            DocumentFormat.OpenXml.Wordprocessing.TableRow  tr;
            DocumentFormat.OpenXml.Wordprocessing.TableCell tc;
            TableCellProperties tcp;
            RunProperties       rp;

            WordprocessingDocument package = WordprocessingDocument.Create(HttpRuntime.AppDomainAppPath + "\\poste.docx", WordprocessingDocumentType.Document);

            package.AddMainDocumentPart();

            Document document = new Document();

            package.MainDocumentPart.Document = document;
            body = document.AppendChild(new Body());
            SectionProperties sectionProps = body.AppendChild(new SectionProperties());

            sectionProps.Append(new PageMargin()
            {
                Top = 720, Right = 720, Bottom = 720, Left = 720, Header = 0, Footer = 0, Gutter = 0
            });                                                                                                                             // 1440 = 1", 720 = 0.5";

            par = body.AppendChild(new Paragraph());
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            rp.AppendChild(new Bold()
            {
                Val = OnOffValue.FromBoolean(true)
            });
            rp.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.FontSize()
            {
                Val = "32"
            });
            run.AppendChild(new Text("Države"));

            DocumentFormat.OpenXml.Wordprocessing.Table table = new DocumentFormat.OpenXml.Wordprocessing.Table();
            TableProperties props = new TableProperties
                                    (
                new TableBorders
                (
                    new TableWidth {
                Width = "5000", Type = TableWidthUnitValues.Pct
            },                                                                                  // 100%
                    new TopBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.None),
                Size = 6
            },
                    new BottomBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.Single),
                Size = 6
            },
                    new LeftBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.None),
                Size = 6
            },
                    new RightBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.None),
                Size = 6
            },
                    new InsideHorizontalBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.Single),
                Size = 6
            },
                    new InsideVerticalBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.None),
                Size = 6
            }
                )
                                    );

            table.AppendChild <TableProperties>(props);

            // red
            tr = table.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableRow());
            // ćelija
            tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
            tcp = tc.AppendChild(new TableCellProperties());
            tcp.Append(new Shading()
            {
                Val = ShadingPatternValues.Clear, Color = "auto", Fill = "black"
            });
            par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
            {
                Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
            })));
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            rp.Append(new Color()
            {
                Val = "ffffff"
            });
            rp.Append(new Bold()
            {
                Val = OnOffValue.FromBoolean(true)
            });
            run.Append(new Text("Broj"));
            // ćelija
            tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
            tcp = tc.AppendChild(new TableCellProperties());
            tcp.Append(new Shading()
            {
                Val = ShadingPatternValues.Clear, Color = "auto", Fill = "black"
            });
            par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
            {
                Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
            })));
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            rp.Append(new Color()
            {
                Val = "ffffff"
            });
            rp.Append(new Bold()
            {
                Val = OnOffValue.FromBoolean(true)
            });
            run.Append(new Text("Naziv"));

            string          query = "select broj, naziv from poste where 1 = 1 " + ViewState["filter"] + " order by broj, naziv";
            OleDbConnection con   = new OleDbConnection(ConfigurationManager.ConnectionStrings["connstr"].ConnectionString);
            OleDbCommand    cmd   = new OleDbCommand();

            cmd.CommandText = query;
            cmd.CommandType = CommandType.Text;
            cmd.Connection  = con;
            con.Open();
            OleDbDataReader dr = cmd.ExecuteReader();

            while (dr.Read())
            {
                tr  = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
                tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
                tcp = tc.AppendChild(new TableCellProperties());
                par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
                {
                    Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
                })));
                run = par.AppendChild(new Run());
                rp  = run.AppendChild(new RunProperties());
                run.Append(new Text(dr[0] as string));

                tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
                tcp = tc.AppendChild(new TableCellProperties());
                par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
                {
                    Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
                })));
                run = par.AppendChild(new Run());
                rp  = run.AppendChild(new RunProperties());
                run.Append(new Text(dr[1] as string));

                table.Append(tr);
            }
            document.Body.Append(table);
            document.Save();
            package.Close();

            con.Close();

            Response.ContentType = "Application/docx";
            Response.AppendHeader("Content-Disposition", "attachment; filename=poste.docx");
            Response.TransmitFile(HttpRuntime.AppDomainAppPath + "\\poste.docx");
            Response.End();
        }
コード例 #15
0
        public void GetIntersectionsRiver()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Transaction tr = db.TransactionManager.StartTransaction();

            #region For Word
            string filepath = "D:\\intersections_rivers.docx";

            using (WordprocessingDocument docX = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
            {
                try
                {
                    // Add a main document part.
                    MainDocumentPart mainPart = docX.AddMainDocumentPart();
                    StyleDefinitionsPart styleDefinitionsPart = mainPart.AddNewPart<StyleDefinitionsPart>();
                    Styles styles1 = new Styles();
                    DocDefaults docDefaults =
                        new DocDefaults(
                            new RunPropertiesDefault(new RunPropertiesBaseStyle(new RunFonts()
                            {
                                Ascii = "Times New Roman",
                                HighAnsi = "Times New Roman",
                                ComplexScript = "Times New Roman"
                            }, new FontSize() { Val = "24" },
                                new FontSizeComplexScript() { Val = "24" })),
                                new ParagraphPropertiesDefault(new SpacingBetweenLines() { After = "0", Line = "240", LineRule = LineSpacingRuleValues.Auto }));
                    styles1.AppendChild(docDefaults);
                    styleDefinitionsPart.Styles = styles1;

                    mainPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document();
                    DocumentFormat.OpenXml.Wordprocessing.Body body = mainPart.Document.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Body());
                    ParagraphProperties paragraphProperties1 = new ParagraphProperties(
                        new Justification() { Val = JustificationValues.Center },
                        new ParagraphMarkRunProperties(
                            new RunFonts()
                            {
                                Ascii = "Times New Roman",
                                HighAnsi = "Times New Roman",
                                ComplexScript = "Times New Roman"
                            },
                            new FontSize() { Val = "24" },
                            new FontSizeComplexScript() { Val = "24" }
                            ));

                    Paragraph para = body.AppendChild(new Paragraph());
                    para.AppendChild(paragraphProperties1);

                    Run run = para.AppendChild(new Run());

                    RunProperties runProperties1 = new RunProperties(
                        new Bold());

                    // String msg contains the text, "Hello, Word!"
                    run.AppendChild(runProperties1);
                    run.AppendChild(new Text("ПРИЛОЖЕНИЕ"));
                    run.AppendChild(new Break());
                    run.AppendChild(new Text("Ведомость пересечений"));
                    run.AppendChild(new Break());

                    var table = new DocumentFormat.OpenXml.Wordprocessing.Table();
                    // Create a TableProperties object and specify its border information.
                    TableProperties tblProp = new TableProperties(
                        new TableWidth() { Width = "9782", Type = TableWidthUnitValues.Dxa },
                        new TableIndentation() { Width = -318, Type = TableWidthUnitValues.Dxa },
                        new TableBorders(
                            new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }),
                        new DocumentFormat.OpenXml.Wordprocessing.TableStyle() { Val = "TableGrid" }
                        );

                    // Append the TableProperties object to the empty table.
                    table.AppendChild<TableProperties>(tblProp);

                    // Add 3 columns to the table.
                    TableGrid tg = new TableGrid(new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(),
                         new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn());
                    table.AppendChild(tg);

                    TableRow tr1 = new TableRow(
                        new TableRowProperties(new TableRowHeight() { Val = 430 }),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1709" },
                                new VerticalMerge() { Val = MergedCellValues.Restart },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()),
                                new Run(new Text("Наимен. водотока")))),
                        //new TableCellProperties(new TableCellWidth() {Type = TableWidthUnitValues.Pct, Width = "500"})
                        new TableCell(
                            new TableCellProperties(
                                new GridSpan() { Val = 2 },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center },
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "3922" }),
                            new Paragraph(
                                new ParagraphProperties(new Justification() { Val = JustificationValues.Center }),
                                new Run(new Text("Пикетное положение пересечения")))),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(
                                new ParagraphProperties(new Justification() { Val = JustificationValues.Center }),
                                new Run(new Text("Ширина водотока в межень")))),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1358" },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center },
                                new VerticalMerge() { Val = MergedCellValues.Restart }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()),
                                new Run(new Text("Глуб. водотока")))),
                        new TableCell(
                            new TableCellProperties(
                                new GridSpan() { Val = 3 },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center },
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2368" }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()),
                                new Run(new Text("Горизонт воды")))),
                        new TableCell(new TableCellProperties(
                            new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "425" },
                            new VerticalMerge() { Val = MergedCellValues.Restart },
                            new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Прим."))))
                        );
                    table.AppendChild(tr1);
                    TableRow tr2 = new TableRow(
                        new TableRowProperties(new TableRowHeight() { Val = 419 }),
                        new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())),
                        new TableCell(
                            new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("От")))),
                        new TableCell(
                            new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("До")))),
                        new TableCell(
                            new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("половодье")))),
                        new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1260" },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Дата съемки")))),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1108" },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("На день съемки")))),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1108" },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Макс.")))),
                        new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())));
                    table.AppendChild(tr2);

                    TableCellProperties tcp = new TableCellProperties(new GridSpan() { Val = 9 });
            #endregion

                    while (true)
                    {

                        //using (tr)
                        //{
                        try
                        {
                            #region Поиск пересечений
                            BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                            PromptEntityOptions peo = new PromptEntityOptions("\nВыбери polyline  >>");
                            peo.SetRejectMessage("\nМожно только polyline >>");
                            peo.AddAllowedClass(typeof(Polyline), false);
                            PromptEntityResult res;
                            res = ed.GetEntity(peo);
                            if (res.Status != PromptStatus.OK)
                            {
                                break;
                            }
                            DBObject ent = (DBObject)tr.GetObject(res.ObjectId, OpenMode.ForRead);
                            if (ent == null) return;

                            PromptPointResult pPtRes;
                            PromptPointOptions pPtOpts = new PromptPointOptions("");
                            // Prompt for the start point
                            pPtOpts.Message = "\nВведи начало: ";
                            pPtRes = doc.Editor.GetPoint(pPtOpts);

                            PromptDoubleOptions getpik = new PromptDoubleOptions("\nВведи пикетаж (в формате числа, а не 0+00): ");
                            PromptDoubleResult getpikRes = doc.Editor.GetDouble(getpik);

                            //zoom
                            /*PromptEntityResult per = ed.GetEntity(peo);

                            if (per.Status != PromptStatus.OK)
                                return;*/

                            // Extract its extents

                            Extents3d ext;

                            Transaction trans = db.TransactionManager.StartTransaction();
                            using (trans)
                            {
                                Entity enti = (Entity)trans.GetObject(res.ObjectId, OpenMode.ForRead);
                                ext = enti.GeometricExtents;
                                trans.Commit();
                            }

                            ext.TransformBy(ed.CurrentUserCoordinateSystem.Inverse());

                            ZoomWin(ed, ext.MinPoint, ext.MaxPoint);
                            //

                            //Polyline poly = (Polyline)ent as Polyline;
                            Curve curv = ent as Curve;

                            DBObjectCollection pcurves = new DBObjectCollection();

                            curv.Explode(pcurves);
                            TypedValue[] values = new TypedValue[]
                     {
                        new TypedValue(0, "lwpolyline")
                        //might be added layer name to select curve:
                        //, new TypedValue(8, "mylayer")
                     };
                            SelectionFilter filter = new SelectionFilter(values);

                            Point3dCollection fence = new Point3dCollection();

                            double leng = curv.GetDistanceAtParameter(curv.EndParam) - curv.GetDistanceAtParameter(curv.StartParam);
                            // number of divisions along polyline to create fence selection
                            double step = leng / 256;// set number of steps to your suit

                            int num = Convert.ToInt32(leng / step);

                            for (int i = 0; i < num; i++)
                            {
                                Point3d pp = curv.GetPointAtDist(step * i);

                                fence.Add(curv.GetClosestPointTo(pp, false));
                            }

                            PromptSelectionResult selres = ed.SelectFence(fence, filter);

                            if (selres.Status != PromptStatus.OK) return;
                            Point3dCollection intpts = new Point3dCollection();

                            DBObjectCollection qcurves = new DBObjectCollection();
                            //ed.WriteMessage("\nCheck");
                            foreach (SelectedObject selobj in selres.Value)
                            {
                                DBObject obj = tr.GetObject(selobj.ObjectId, OpenMode.ForRead, false) as DBObject;
                                if (selobj.ObjectId != curv.ObjectId)
                                {
                                    DBObjectCollection icurves = new DBObjectCollection();
                                    Curve icurv = obj as Curve;
                                    icurv.Explode(icurves);
                                    foreach (DBObject dbo in icurves)
                                    {
                                        if (!qcurves.Contains(dbo))
                                            qcurves.Add(dbo);
                                    }
                                }

                            }
                            //ed.WriteMessage("\n{0}", qcurves.Count);

                            int j = 0;
                            Point3dCollection polypts = new Point3dCollection();

                            for (int i = 0; i < pcurves.Count; ++i)
                            {
                                for (j = 0; j < qcurves.Count; ++j)
                                {
                                    Curve curve1 = pcurves[i] as Curve;

                                    Curve curve2 = qcurves[j] as Curve;

                                    Point3dCollection pts = new Point3dCollection();

                                    curve1.IntersectWith(curve2, Intersect.OnBothOperands, pts, IntPtr.Zero, IntPtr.Zero);

                                    foreach (Point3d pt in pts)
                                    {
                                        if (!polypts.Contains(pt))
                                            polypts.Add(pt);
                                    }
                                }
                            }
                            #endregion

                            try
                            {
                                using (Transaction tran = db.TransactionManager.StartTransaction())
                                {
                                    Polyline pline = (Polyline)tran.GetObject(res.ObjectId, OpenMode.ForRead);
                                    table.AppendChild(new TableRow(
                                        new TableCell(
                                            new TableCellProperties(
                                                new GridSpan() { Val = 9 }),
                                                new Paragraph(
                                                    new ParagraphProperties(
                                                        new ParagraphMarkRunProperties(new Bold()),
                                                        new Justification() { Val = JustificationValues.Center }),
                                                        new Run(new RunProperties(
                                                            new Bold()),
                                                            new Text("ПК" + ((int)(getpikRes.Value)).ToString("F0") + "-ПК" +
                                                                ((int)(100 * getpikRes.Value + pline.Length) / 100).ToString("F0") + "+" +
                                                                ((100 * getpikRes.Value + pline.Length) % 100).ToString("F")))))));
                                }
                            }
                            catch { ed.WriteMessage("\nError."); }

                            Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("osmode", 0);// optional
                            // for debug only
                            Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(string.Format("\nНайдено пересечений: {0}", polypts.Count));

                            if (polypts.Count == 0)
                            {
                                try
                                {
                                    using (Transaction tran = db.TransactionManager.StartTransaction())
                                    {
                                        Polyline pline = (Polyline)tran.GetObject(res.ObjectId, OpenMode.ForRead);
                                        table.AppendChild(new TableRow(
                                            new TableCell(
                                                new TableCellProperties(
                                                    new GridSpan() { Val = 9 }),
                                                    new Paragraph(
                                                        new ParagraphProperties(
                                                            new Justification() { Val = JustificationValues.Center }),
                                                            new Run(new Text("На данном участке трассы пересечения отсутствуют"))))));
                                    }
                                }
                                catch { ed.WriteMessage("\nError."); }
                            }
                            else
                            {
                                //List<double> pik = new List<double>(polypts.Count);
                                double[] pik = new double[polypts.Count];
                                int numInter = 0;

                                foreach (Point3d inspt in polypts)
                                {
                                    double dist = 0;
                                    dist = 100 * getpikRes.Value;

                                    // test for visulization only
                                    /*Circle circ = new Circle(inspt, Vector3d.ZAxis, 10 * db.Dimtxt);
                                    circ.ColorIndex = 1;
                                    btr.AppendEntity(circ);
                                    tr.AddNewlyCreatedDBObject(circ, true);*/

                                    Point3d curr = pPtRes.Value, next = pPtRes.Value;
                                    try
                                    {
                                        using (Transaction tran = db.TransactionManager.StartTransaction())
                                        {
                                            Polyline pline = (Polyline)tran.GetObject(res.ObjectId, OpenMode.ForRead);
                                            if ((pPtRes.Value == pline.GetLineSegmentAt(0).StartPoint) || (pPtRes.Value == pline.GetLineSegmentAt(0).EndPoint))
                                                for (int i = 0; i < pline.NumberOfVertices - 2; i++)
                                                {
                                                    LineSegment3d l1 = pline.GetLineSegmentAt(i);
                                                    LineSegment3d l2 = pline.GetLineSegmentAt(i + 1);
                                                    double angle = GetPolylineShape(l1, l2, pline.Normal);
                                                    if (angle > Math.PI)
                                                    {
                                                        if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint))
                                                            next = l1.StartPoint;
                                                        else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint))
                                                            next = l1.EndPoint;
                                                    }
                                                    else
                                                    {
                                                        if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint))
                                                            next = l1.StartPoint;
                                                        else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint))
                                                            next = l1.EndPoint;
                                                    }

                                                    if (Math.Abs(inspt.DistanceTo(curr) + inspt.DistanceTo(next) - curr.DistanceTo(next)) < 1)
                                                    {
                                                        dist += inspt.DistanceTo(curr);
                                                        ed.WriteMessage(((int)dist / 100).ToString("F0") + "+" + (dist % 100).ToString("F") + "\n");
                                                        break;
                                                    }
                                                    else
                                                        dist += curr.DistanceTo(next);

                                                    curr = next;
                                                }
                                            else
                                                for (int i = pline.NumberOfVertices - 3; i >= 0; i--)
                                                {
                                                    LineSegment3d l1 = pline.GetLineSegmentAt(i);
                                                    LineSegment3d l2 = pline.GetLineSegmentAt(i + 1);
                                                    double angle = GetPolylineShape(l1, l2, pline.Normal);
                                                    if (angle > Math.PI)
                                                    {
                                                        if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint))
                                                            next = l1.StartPoint;
                                                        else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint))
                                                            next = l1.EndPoint;
                                                    }
                                                    else
                                                    {
                                                        if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint))
                                                            next = l1.StartPoint;
                                                        else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint))
                                                            next = l1.EndPoint;
                                                    }

                                                    if (Math.Abs(inspt.DistanceTo(curr) + inspt.DistanceTo(next) - curr.DistanceTo(next)) < 1)
                                                    {
                                                        dist += inspt.DistanceTo(curr);
                                                        ed.WriteMessage(((int)dist / 100).ToString("F0") + "+" + (dist % 100).ToString("F") + "\n");
                                                        break;
                                                    }
                                                    else
                                                        dist += curr.DistanceTo(next);

                                                    curr = next;
                                                }
                                        }
                                    }
                                    catch
                                    {
                                        ed.WriteMessage("\nInvalid polyline.");
                                    }
                                    pik[numInter] = dist;
                                    numInter++;
                                    //ed.WriteMessage(" {0:0.00}\n", dist);
                                }

                                //pik.Sort();

                                Array.Sort(pik);

                                for (int i = 0; i < polypts.Count; i++)
                                {
                                    tr1 = new TableRow(
                                        new TableRowProperties(new TableRowHeight() { Val = 300 }),
                                        new TableCell(new Paragraph(new Run())),
                                        new TableCell(
                                                new TableCellProperties(
                                                    new GridSpan() { Val = 2 }),
                                                    new Paragraph(
                                                        new ParagraphProperties(
                                                            new Justification() { Val = JustificationValues.Center }),
                                                            new Run(new Text(((int)pik[i] / 100).ToString("F0") + "+" + (pik[i] % 100).ToString("F"))))),
                                        new TableCell(new Paragraph(new Run())),
                                        new TableCell(new Paragraph(new Run())),
                                        new TableCell(new Paragraph(new Run())),
                                        new TableCell(new Paragraph(new Run())),
                                        new TableCell(new Paragraph(new Run())),
                                        new TableCell(new Paragraph(new Run()))
                                        );
                                    table.AppendChild(tr1);
                                }
                            }

                        }
                        catch
                        {
                            ed.WriteMessage("\nError");
                        }
                        //}
                    }

                    tr.Commit();

                    body.AppendChild(table);
                    body.AppendChild(
                        new SectionProperties(
                            new PageMargin()
                            {
                                Top = 1134,
                                Right = (UInt32Value)850U,
                                Bottom = 1134,
                                Left = (UInt32Value)1418U,
                                Header = (UInt32Value)708U,
                                Footer = (UInt32Value)708U,
                                Gutter = (UInt32Value)0U
                            }));
                    ed.WriteMessage("\nДокумент сохранен в D:\\intersections_rivers.docx");
                }
                catch
                {
                    ed.WriteMessage("\nError.");
                }
            }
        }
コード例 #16
0
        public void InsertForcesTable(IForcesModel forces)
        {
            Paragraph     para          = _body.AppendChild(new Paragraph());
            Run           run           = para.AppendChild(new Run());
            RunProperties runProperties = getHeading2(run);

            run.AppendChild(new Text(++_diagmarCounter + ". Decision Forces Viewpoint: " + forces.Name));
            //_body.AppendChild(new Paragraph(new Run(new Text(++_diagmarCounter + ". Decision Forces Viewpoint"))));
            _body.AppendChild(new Paragraph(new Run(new Text())));

            var table = new Table();

            var props = new TableProperties(
                new TableBorders(
                    new TopBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.Single),
                Size = 11
            },
                    new BottomBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.Single),
                Size = 11
            },
                    new LeftBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.Single),
                Size = 11
            },
                    new RightBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.Single),
                Size = 11
            },
                    new InsideHorizontalBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.Single),
                Size = 11
            },
                    new InsideVerticalBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.Single),
                Size = 11
            }));

            table.AppendChild(props);

            var emptyCell = new TableCell();

            // insert an empty cell in tol left of forces table
            var decRow = new TableRow();

            decRow.AppendChild(emptyCell);
            emptyCell.AppendChild(new Paragraph(new Run(new Text(""))));

            // insert the concern header and the decisions names
            var concCellHeader = new TableCell(new Paragraph(new Run(new Text("Concerns"))));

            decRow.AppendChild(concCellHeader);
            foreach (
                TableCell decCell in
                forces.GetDecisions()
                .Select(decision => new TableCell(new Paragraph(new Run(new Text(decision.Name))))))
            {
                decRow.AppendChild(decCell);
            }
            table.AppendChild(decRow);


            foreach (var concernsPerForces in forces.GetConcernsPerForce())
            {
                IEAElement        force    = concernsPerForces.Key;
                List <IEAElement> concerns = concernsPerForces.Value;

                foreach (IEAElement concern in concerns)
                {
                    var forceRow  = new TableRow();
                    var forceCell = new TableCell(new Paragraph(new Run(new Text(force.Name))));
                    forceRow.AppendChild(forceCell);
                    var concCell = new TableCell();
                    concCell.AppendChild(new Paragraph(new Run(new Text(concern.Name))));
                    forceRow.AppendChild(concCell);

                    // insert ratings
                    foreach (Rating rating in forces.GetRatings())
                    {
                        if (rating.ForceGUID != force.GUID || rating.ConcernGUID != concern.GUID)
                        {
                            continue;
                        }
                        if (forces.GetDecisions().Any(decision => rating.DecisionGUID == decision.GUID))
                        {
                            var ratCell = new TableCell();
                            ratCell.AppendChild(new Paragraph(new Run(new Text(rating.Value))));
                            forceRow.AppendChild(ratCell);
                        }
                    }
                    table.AppendChild(forceRow);
                }
            }


            _body.AppendChild(table);
            _body.AppendChild(new Paragraph());
        }
コード例 #17
0
        public void InsertDecisionTable(IDecision decision)
        {
            var dataDict = new Dictionary <String, IList <String> >();

            dataDict.Add("Name", new List <string>());
            dataDict.Add("State", new List <string>());
            dataDict.Add("Problem", new List <string>());
            dataDict.Add("Decision", new List <string>());
            dataDict.Add("Argumentation", new List <string>());
            dataDict.Add("Alternatives", new List <string>());
            dataDict.Add("Related Decisions", new List <string>());
            dataDict.Add("Forces", new List <string>());
            dataDict.Add("Traces", new List <string>());
            dataDict.Add("Stakeholder Involvement", new List <string>());
            dataDict.Add("History", new List <string>());


            dataDict["Name"].Add(decision.Name);
            dataDict["State"].Add(decision.State);
            //dataDict["Problem"].Add(decision.Problem);
            //dataDict["Decision"].Add(decision.Solution);
            //dataDict["Argumentation"].Add(decision.Argumentation);

            _decisionCounter++;
            //_body.AppendChild(new Paragraph(new Run(new Text("Decision " +_decisionCounter.ToString() +": " + decision.Name))));

            var table = new Table();

            var props = new TableProperties(
                new TableBorders(
                    new TopBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.Single),
                Size = 11
            },
                    new BottomBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.Single),
                Size = 11
            },
                    new LeftBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.Single),
                Size = 11
            },
                    new RightBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.Single),
                Size = 11
            },
                    new InsideHorizontalBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.Single),
                Size = 11
            },
                    new InsideVerticalBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.Single),
                Size = 11
            },
                    new TableWidth
            {
                Width = "5000",
                Type  = TableWidthUnitValues.Pct
            }
                    ),
                new TableCaption
            {
                Val = new StringValue("My Caption Val")         // Does not work..
            });

            table.AppendChild(props);

            foreach (IDecisionRelation relation in decision.RelatedDecisions)
            {
                dataDict["Related Decisions"].Add(relation.Decision.GUID.Equals(decision.GUID)
                                                      ? "<<this>> " + decision.Name + " - " + relation.Type +
                                                  " - " +
                                                  relation.RelatedDecision.Name
                                                      : relation.Decision.Name + " - " + relation.Type +
                                                  " - <<this>> " + decision.Name + "\r\n");
            }

            foreach (IDecisionRelation alternative in decision.Alternatives)
            {
                dataDict["Alternatives"].Add(alternative.Decision.GUID.Equals(decision.GUID)
                                                 ? "<<this>> " + decision.Name + " - " + alternative.Type +
                                             " - " + alternative.RelatedDecision.Name
                                                 : alternative.Decision.Name + " - " + alternative.Type +
                                             " - <<this>> " + decision.Name + "\r\n");
            }


            foreach (IForceEvaluation rating in decision.Forces)
            {
                IEAElement force = EAMain.Repository.GetElementByGUID(rating.Force.ForceGUID);
                dataDict["Forces"].Add(rating.Force.Name + " - " + force.Notes);
            }


            foreach (ITraceLink trace in decision.Traces)
            {
                dataDict["Traces"].Add(trace.TracedElementName);
            }


            foreach (IHistoryEntry entry in decision.History)
            {
                dataDict["History"].Add(entry.State + " " + entry.Modified.ToShortDateString());
            }

            foreach (IStakeholderAction stakeholderInvolvment in decision.Stakeholders)
            {
                string line = string.Format(Messages.ReportingStakeholderInvolvmentLine,
                                            stakeholderInvolvment.Stakeholder.Role,
                                            stakeholderInvolvment.Stakeholder.Name,
                                            stakeholderInvolvment.Action);
                dataDict["Stakeholder Involvement"].Add(line);
            }


            foreach (var entry in dataDict)
            {
                if (entry.Value.Count == 0)
                {
                    continue;
                }
                if ("".Equals(entry.Value[0]))
                {
                    continue;
                }

                var tableRow = new TableRow();

                var rowHeader = new TableCell();
                rowHeader.Append(new TableCellWidth {
                    Type = TableWidthUnitValues.Dxa, Width = "1821"
                });
                rowHeader.Append(
                    new TableCellProperties(new Shading
                {
                    Val   = ShadingPatternValues.Clear,
                    Color = "auto",
                    Fill  = "##d3d4d6"
                }));
                Paragraph para = rowHeader.AppendChild(new Paragraph());
                Run       run  = para.AppendChild(new Run());
                getBold(run);
                run.AppendChild(new Text(entry.Key));

                var       rowValue     = new TableCell();
                Paragraph rowValuePara = rowValue.AppendChild(new Paragraph());
                Run       rowValueRun  = rowValuePara.AppendChild(new Run());
                int       lineCount    = 0;
                foreach (string line in entry.Value)
                {
                    rowValueRun.AppendChild(new Text(line));
                    if (++lineCount != entry.Value.Count)
                    {
                        rowValueRun.AppendChild(new Break());
                    }
                }

                tableRow.AppendChild(rowHeader);
                tableRow.AppendChild(rowValue);
                table.AppendChild(tableRow);
            }

            /*  for (int i = 0; i <= data.GetUpperBound(0); i++)
             * {
             *  var tr = new TableRow();
             *  for (int j = 0; j <= data.GetUpperBound(1); j++)
             *  {
             *      var tc = new TableCell();
             *      if (j == 0)
             *      {
             *          //Apply the same width at column 1 (0)
             *          tc.Append(new TableCellWidth {Type = TableWidthUnitValues.Dxa, Width = "1821"});
             *          tc.Append(new TableCellProperties(new Shading{Val = ShadingPatternValues.Clear,Color = "auto",Fill = "##d3d4d6"}));
             *          Paragraph para = tc.AppendChild(new Paragraph());
             *          Run run = para.AppendChild(new Run());
             *          RunProperties runProperties = getBold(run);
             *          run.AppendChild(new Text(dataDict.));
             *      }
             *      else
             *      {
             *          tc.AppendChild(new Paragraph(new Run(new Text(data[i, j]))));
             *      }
             *
             *      tr.AppendChild(tc);
             *  }
             *  if (data[i, 1] != "")
             *      table.AppendChild(tr);
             * }*/

            _body.AppendChild(table);
            _body.AppendChild(new Paragraph());
        }
コード例 #18
0
        protected void CreateDocumentLink_Click(object sender, EventArgs e)
        {
            FileStream fs = null;

            try
            {
                // When the user has selected a library, they will be allowed to click the button
                // The first thing we'll do is get the target library and its root folder.
                targetLibrary = hostingWeb.Lists.GetByTitle(OutputLibrary.SelectedItem.Text);
                Microsoft.SharePoint.Client.Folder destintationFolder = targetLibrary.RootFolder;
                clientContext.Load(destintationFolder);
                clientContext.ExecuteQuery();

                // Then we'll build a Word Document by using OOXML
                // Note that we'll first create it in a folder in this Web app.
                using (WordprocessingDocument wordDocument =
                           WordprocessingDocument.Create(Server.MapPath("~/SampleOOXML/LocalOOXMLDocument.docx"),
                                                         WordprocessingDocumentType.Document))
                {
                    // Add a main document part.
                    MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();

                    // Create the document structure.
                    mainPart.Document = new Document();
                    Body body = mainPart.Document.AppendChild(new Body());

                    // Create a paragraph.
                    Paragraph para = body.AppendChild(new Paragraph());
                    Run       run  = para.AppendChild(new Run());
                    run.AppendChild(new Text("Here's some text in a paragraph"));

                    // Create a table.
                    DocumentFormat.OpenXml.Wordprocessing.Table table
                        = new DocumentFormat.OpenXml.Wordprocessing.Table();

                    // Create some table border settings.
                    TableProperties borderProperties = new TableProperties(
                        new TableBorders(
                            new TopBorder
                    {
                        Val  = new EnumValue <BorderValues>(BorderValues.DashDotStroked),
                        Size = 12
                    },
                            new BottomBorder
                    {
                        Val  = new EnumValue <BorderValues>(BorderValues.DashDotStroked),
                        Size = 12
                    },
                            new LeftBorder
                    {
                        Val  = new EnumValue <BorderValues>(BorderValues.DashDotStroked),
                        Size = 12
                    },
                            new RightBorder
                    {
                        Val  = new EnumValue <BorderValues>(BorderValues.DashDotStroked),
                        Size = 12
                    },
                            new InsideHorizontalBorder
                    {
                        Val  = new EnumValue <BorderValues>(BorderValues.Single),
                        Size = 12
                    },
                            new InsideVerticalBorder
                    {
                        Val  = new EnumValue <BorderValues>(BorderValues.Single),
                        Size = 12
                    }));

                    // Add the table border settings to the table.
                    table.AppendChild <TableProperties>(borderProperties);

                    // Create a table row and add two cells with some text
                    var tr  = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
                    var tc1 = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
                    tc1.Append(new Paragraph(new Run(new Text("Here's some text in table cell #1"))));
                    var tc2 = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
                    tc2.Append(new Paragraph(new Run(new Text("Here's some text in table cell #2"))));
                    tr.Append(tc1);
                    tr.Append(tc2);

                    // Add the row to the table, and the table to the body of the document.
                    table.Append(tr);
                    body.Append(table);
                }

                // At this stage, the local file has been created in the folder of this Web project
                // so we'll now read it and create a new file in SharePoint, based on this local file.
                byte[] documentBytes;
                fs            = File.OpenRead(Server.MapPath("~/SampleOOXML/LocalOOXMLDocument.docx"));
                documentBytes = new byte[fs.Length];
                fs.Read(documentBytes, 0, Convert.ToInt32(fs.Length));


                // At this stage, the file contents of the OOXML document has been read into the byte array
                // so we can use that as the content of a new file in SharePoint.
                Microsoft.SharePoint.Client.FileCreationInformation ooxmlFile
                    = new Microsoft.SharePoint.Client.FileCreationInformation();
                ooxmlFile.Overwrite = true;
                ooxmlFile.Url       = hostingWeb.Url
                                      + destintationFolder.ServerRelativeUrl
                                      + "/SharePointOOXMLDocument.docx";
                ooxmlFile.Content = documentBytes;
                Microsoft.SharePoint.Client.File newFile = targetLibrary.RootFolder.Files.Add(ooxmlFile);
                clientContext.Load(newFile);
                clientContext.ExecuteQuery();

                // Let the user navigate to the document library where the file has been created
                string targetUrl = hostingWeb.Url + destintationFolder.ServerRelativeUrl;
                DocumentLink.Text        = "Document has been created in SharePoint! Click here to view the library";
                DocumentLink.Visible     = true;
                DocumentLink.NavigateUrl = targetUrl;
            }
            catch (Exception ex)
            {
                // Tell the user what went wrong
                DocumentLink.Text        = "An error has occurred: " + ex.Message;
                DocumentLink.Visible     = true;
                DocumentLink.NavigateUrl = "";
            }
            finally
            {
                // Clean up our filestream object
                fs.Close();
            }
        }
コード例 #19
0
        public void CreateWordDoc(DataTable data, decimal t, string user)
        {
            string pathUser     = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            string pathDownload = Path.Combine(pathUser, "Downloads");
            //string pathDownload = Server.MapPath("~/Content/");
            decimal total = t;

            try
            {
                //Set the current directory.
                Directory.SetCurrentDirectory(pathDownload);
            }
            catch (DirectoryNotFoundException e)
            {
                Console.WriteLine("The specified directory does not exist. {0}", e);
            }

            WordprocessingDocument doc         = WordprocessingDocument.Create("ExpenseReport.docx", WordprocessingDocumentType.Document);
            MainDocumentPart       mainDocPart = doc.AddMainDocumentPart();

            mainDocPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document();
            DocumentFormat.OpenXml.Wordprocessing.Body body = new DocumentFormat.OpenXml.Wordprocessing.Body();
            mainDocPart.Document.Append(body);
            DocumentFormat.OpenXml.Wordprocessing.Table table = new DocumentFormat.OpenXml.Wordprocessing.Table();

            //border
            TableProperties tblProp = new TableProperties(
                new TableBorders(
                    new InsideHorizontalBorder()
            {
                Val = new EnumValue <BorderValues>(BorderValues.BasicThinLines), Size = 10
            })
                );

            // Append the TableProperties object to the empty table.
            table.AppendChild <TableProperties>(tblProp);

            //setting header
            DocumentFormat.OpenXml.Wordprocessing.TableRow      tr = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
            DocumentFormat.OpenXml.Wordprocessing.RunProperties rp = new DocumentFormat.OpenXml.Wordprocessing.RunProperties();
            rp.Append(new DocumentFormat.OpenXml.Wordprocessing.Color()
            {
                Val = "#FF0000"
            });
            RunFonts rFont1 = new RunFonts();

            rFont1.Ascii = "Arial";
            rp.Append(rFont1);
            rp.Append(new Bold());
            rp.Append(new DocumentFormat.OpenXml.Wordprocessing.FontSize()
            {
                Val = "28"
            });

            DocumentFormat.OpenXml.Wordprocessing.Run run = new DocumentFormat.OpenXml.Wordprocessing.Run();
            run.RunProperties = rp;
            run.Append(new Text("Expense Report for " + user));
            DocumentFormat.OpenXml.Wordprocessing.Paragraph           para = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(run);
            DocumentFormat.OpenXml.Wordprocessing.TableCellProperties tcpp = new DocumentFormat.OpenXml.Wordprocessing.TableCellProperties();
            tcpp.Append(new DocumentFormat.OpenXml.Wordprocessing.TableCellWidth {
                Type = DocumentFormat.OpenXml.Wordprocessing.TableWidthUnitValues.Dxa, Width = "2200"
            });
            GridSpan gs = new GridSpan();

            gs.Val = 5;
            tcpp.Append(gs);
            DocumentFormat.OpenXml.Wordprocessing.TableCell tc = new DocumentFormat.OpenXml.Wordprocessing.TableCell(tcpp, para);
            tr.Append(tc);
            table.Append(tr);

            DocumentFormat.OpenXml.Wordprocessing.TableRow row_header = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
            foreach (DataColumn column in data.Columns)
            {
                DocumentFormat.OpenXml.Wordprocessing.TableCell cell = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
                cell.Append(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(
                                new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(column.ToString()))));
                cell.Append(new DocumentFormat.OpenXml.Wordprocessing.TableCellProperties(new DocumentFormat.OpenXml.Wordprocessing.TableCellWidth {
                    Type = DocumentFormat.OpenXml.Wordprocessing.TableWidthUnitValues.Dxa, Width = "2200"
                }));
                row_header.Append(cell);
            }

            table.Append(row_header);

            for (int i = 0; i < data.Rows.Count; ++i)
            {
                DocumentFormat.OpenXml.Wordprocessing.TableRow row = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
                for (int j = 0; j < data.Columns.Count; j++)
                {
                    DocumentFormat.OpenXml.Wordprocessing.TableCell cell = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
                    cell.Append(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(data.Rows[i][j].ToString()))));
                    cell.Append(new DocumentFormat.OpenXml.Wordprocessing.TableCellProperties(new DocumentFormat.OpenXml.Wordprocessing.TableCellWidth {
                        Type = DocumentFormat.OpenXml.Wordprocessing.TableWidthUnitValues.Dxa, Width = "2200"
                    }));
                    row.Append(cell);
                }
                table.Append(row);
            }
            body.Append(table);

            Run       run1  = new Run();
            Paragraph para1 = new Paragraph(run1);

            run1.AppendChild(new Text("The total Expenditure is " + total));
            body.Append(para1);
            doc.MainDocumentPart.Document.Save();
            doc.Dispose();
        }
コード例 #20
0
ファイル: sintetika.aspx.cs プロジェクト: sasajuric/spvv
        protected void btnIspisi_Click(object sender, EventArgs e)
        {
            /*DateTime dt;
             * string d1 = "";
             * string d2 = "";
             * try {
             *  dt = Convert.ToDateTime(txtOdDatuma.Text);
             *  d1 = "#" + dt.Month + "/" + dt.Day + "/" + dt.Year + "#";
             * }
             * catch {
             * }
             * try {
             *  dt = Convert.ToDateTime(txtDoDatuma.Text);
             *  d2 = "#" + dt.Month + "/" + dt.Day + "/" + dt.Year + "#";
             * }
             * catch {
             * }*/

            Body      body;
            Paragraph par;
            Run       run;

            DocumentFormat.OpenXml.Wordprocessing.TableRow  tr;
            DocumentFormat.OpenXml.Wordprocessing.TableCell tc;
            TableCellProperties tcp;
            RunProperties       rp;

            WordprocessingDocument package = WordprocessingDocument.Create(HttpRuntime.AppDomainAppPath + "\\sintetika.docx", WordprocessingDocumentType.Document);

            package.AddMainDocumentPart();

            Document document = new Document();

            package.MainDocumentPart.Document = document;
            body = document.AppendChild(new Body());
            SectionProperties sectionProps = body.AppendChild(new SectionProperties());

            sectionProps.Append(new PageMargin()
            {
                Top = 720, Right = 720, Bottom = 720, Left = 720, Header = 0, Footer = 0, Gutter = 0
            });                                                                                                                             // 1440 = 1", 720 = 0.5";

            par = body.AppendChild(new Paragraph());
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            rp.AppendChild(new Bold()
            {
                Val = OnOffValue.FromBoolean(true)
            });
            rp.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.FontSize()
            {
                Val = "32"
            });
            run.AppendChild(new Text("Sintetika"));

            DocumentFormat.OpenXml.Wordprocessing.Table table = new DocumentFormat.OpenXml.Wordprocessing.Table();
            TableProperties props = new TableProperties
                                    (
                new TableBorders
                (
                    new TableWidth {
                Width = "5000", Type = TableWidthUnitValues.Pct
            },                                                                                  // 100%
                    new TopBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.None),
                Size = 6
            },
                    new BottomBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.Single),
                Size = 6
            },
                    new LeftBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.None),
                Size = 6
            },
                    new RightBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.None),
                Size = 6
            },
                    new InsideHorizontalBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.Single),
                Size = 6
            },
                    new InsideVerticalBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.None),
                Size = 6
            }
                )
                                    );

            table.AppendChild <TableProperties>(props);

            tr  = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
            tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
            tcp = tc.AppendChild(new TableCellProperties());
            tcp.Append(new GridSpan()
            {
                Val = 2
            });
            par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
            {
                Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
            })));
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            rp.Append(new Bold()
            {
                Val = OnOffValue.FromBoolean(true)
            });
            rp.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.FontSize()
            {
                Val = "28"
            });
            run.Append(new Text("PRIPRAVNICI"));
            table.Append(tr);

            tr = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
            // ćelija
            tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
            tcp = tc.AppendChild(new TableCellProperties());
            tcp.Append(new Shading()
            {
                Val = ShadingPatternValues.Clear, Color = "auto", Fill = "black"
            });
            par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
            {
                Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
            })));
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            rp.Append(new Color()
            {
                Val = "ffffff"
            });
            rp.Append(new Bold()
            {
                Val = OnOffValue.FromBoolean(true)
            });
            run.Append(new Text("Standard"));

            // ćelija
            tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
            tcp = tc.AppendChild(new TableCellProperties());
            tcp.Append(new Shading()
            {
                Val = ShadingPatternValues.Clear, Color = "auto", Fill = "black"
            });
            par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
            {
                Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
            })));
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            rp.Append(new Color()
            {
                Val = "ffffff"
            });
            rp.Append(new Bold()
            {
                Val = OnOffValue.FromBoolean(true)
            });
            run.Append(new Text("Broj"));

            table.Append(tr);

            string          query = query = "select qvodicitecajevi.standard, count(*) as broj from vodici inner join qvodicitecajevi on vodici.id = qvodicitecajevi.vod_id where vodici.clanarina like '%" + txtGodina.Text + "%' group by qvodicitecajevi.standard order by qvodicitecajevi.standard";
            OleDbConnection con   = new OleDbConnection(ConfigurationManager.ConnectionStrings["connstr"].ConnectionString);
            OleDbCommand    cmd   = new OleDbCommand();

            cmd.CommandText = query;
            cmd.CommandType = CommandType.Text;
            cmd.Connection  = con;
            con.Open();
            OleDbDataReader dr = cmd.ExecuteReader();

            while (dr.Read())
            {
                tr  = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
                tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
                tcp = tc.AppendChild(new TableCellProperties());
                par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
                {
                    Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
                })));
                run = par.AppendChild(new Run());
                rp  = run.AppendChild(new RunProperties());
                run.Append(new Text(dr["standard"].ToString()));

                tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
                tcp = tc.AppendChild(new TableCellProperties());
                par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
                {
                    Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
                })));
                run = par.AppendChild(new Run());
                rp  = run.AppendChild(new RunProperties());
                run.Append(new Text(dr["broj"].ToString()));

                table.Append(tr);
            }


            tr = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
            // ćelija
            tc = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
            //tcp = tc.AppendChild(new TableCellProperties());
            //tcp.Append(new Shading() { Val = ShadingPatternValues.Clear, Color = "auto", Fill = "black" });
            par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
            {
                Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
            })));
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            //rp.Append(new Color() { Val = "ffffff" });
            //rp.Append(new Bold() { Val = OnOffValue.FromBoolean(true) });
            run.Append(new Text(""));
            table.Append(tr);


            tr  = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
            tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
            tcp = tc.AppendChild(new TableCellProperties());
            tcp.Append(new GridSpan()
            {
                Val = 2
            });
            par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
            {
                Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
            })));
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            rp.Append(new Bold()
            {
                Val = OnOffValue.FromBoolean(true)
            });
            rp.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.FontSize()
            {
                Val = "28"
            });
            run.Append(new Text("VODIČI"));
            table.Append(tr);

            tr = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
            // ćelija
            tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
            tcp = tc.AppendChild(new TableCellProperties());
            tcp.Append(new Shading()
            {
                Val = ShadingPatternValues.Clear, Color = "auto", Fill = "black"
            });
            par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
            {
                Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
            })));
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            rp.Append(new Color()
            {
                Val = "ffffff"
            });
            rp.Append(new Bold()
            {
                Val = OnOffValue.FromBoolean(true)
            });
            run.Append(new Text("Standard"));

            // ćelija
            tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
            tcp = tc.AppendChild(new TableCellProperties());
            tcp.Append(new Shading()
            {
                Val = ShadingPatternValues.Clear, Color = "auto", Fill = "black"
            });
            par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
            {
                Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
            })));
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            rp.Append(new Color()
            {
                Val = "ffffff"
            });
            rp.Append(new Bold()
            {
                Val = OnOffValue.FromBoolean(true)
            });
            run.Append(new Text("Broj"));

            table.Append(tr);

            query           = "select qvodiciispiti.standard, count(*) as broj from vodici inner join qvodiciispiti on vodici.id = qvodiciispiti.vod_id where vodici.clanarina like '%" + txtGodina.Text + "%' group by qvodiciispiti.standard order by qvodiciispiti.standard";
            cmd.CommandText = query;
            dr.Close();
            dr = cmd.ExecuteReader();

            while (dr.Read())
            {
                tr  = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
                tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
                tcp = tc.AppendChild(new TableCellProperties());
                par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
                {
                    Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
                })));
                run = par.AppendChild(new Run());
                rp  = run.AppendChild(new RunProperties());
                run.Append(new Text(dr["standard"].ToString()));

                tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
                tcp = tc.AppendChild(new TableCellProperties());
                par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
                {
                    Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
                })));
                run = par.AppendChild(new Run());
                rp  = run.AppendChild(new RunProperties());
                run.Append(new Text(dr["broj"].ToString()));

                table.Append(tr);
            }

            document.Body.Append(table);
            document.Save();
            package.Close();

            con.Close();

            Response.ContentType = "Application/docx";
            Response.AppendHeader("Content-Disposition", "attachment; filename=sintetika.docx");
            Response.TransmitFile(HttpRuntime.AppDomainAppPath + "\\sintetika.docx");
            Response.End();
        }
コード例 #21
0
        // Insert a table into a word processing document.
        public static void CreateTable(string fileName)
        {
            // Use the file name and path passed in as an argument 
            // to open an existing Word 2007 document.

            using (WordprocessingDocument doc
                = WordprocessingDocument.Open(fileName, true))
            {
                // Create an empty table.
                DocumentFormat.OpenXml.Wordprocessing.Table table = new DocumentFormat.OpenXml.Wordprocessing.Table();

                // Create a TableProperties object and specify its border information.
                DocumentFormat.OpenXml.Wordprocessing.TableProperties tblProp = new DocumentFormat.OpenXml.Wordprocessing.TableProperties(
                    new TableBorders(
                        new DocumentFormat.OpenXml.Wordprocessing.TopBorder()
                        {
                            Val =
                                new EnumValue<BorderValues>(BorderValues.Dashed),
                            Size = 24
                        },
                        new DocumentFormat.OpenXml.Wordprocessing.BottomBorder()
                        {
                            Val =
                                new EnumValue<BorderValues>(BorderValues.Dashed),
                            Size = 24
                        },
                        new DocumentFormat.OpenXml.Wordprocessing.LeftBorder()
                        {
                            Val =
                                new EnumValue<BorderValues>(BorderValues.Dashed),
                            Size = 24
                        },
                        new DocumentFormat.OpenXml.Wordprocessing.RightBorder()
                        {
                            Val =
                                new EnumValue<BorderValues>(BorderValues.Dashed),
                            Size = 24
                        },
                        new DocumentFormat.OpenXml.Wordprocessing.InsideHorizontalBorder()
                        {
                            Val =
                                new EnumValue<BorderValues>(BorderValues.Dashed),
                            Size = 24
                        },
                        new DocumentFormat.OpenXml.Wordprocessing.InsideVerticalBorder()
                        {
                            Val =
                                new EnumValue<BorderValues>(BorderValues.Dashed),
                            Size = 24
                        }
                    )
                );

                // Append the TableProperties object to the empty table.
                table.AppendChild<DocumentFormat.OpenXml.Wordprocessing.TableProperties>(tblProp);

                // Create a row.
                DocumentFormat.OpenXml.Wordprocessing.TableRow tr = new  DocumentFormat.OpenXml.Wordprocessing.TableRow();

                // Create a cell.
                DocumentFormat.OpenXml.Wordprocessing.TableCell tc1 = new DocumentFormat.OpenXml.Wordprocessing.TableCell();

                // Specify the width property of the table cell.
                tc1.Append(new DocumentFormat.OpenXml.Wordprocessing.TableCellProperties(
                    new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));

                // Specify the table cell content.
                tc1.Append(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text("some text"))));

                // Append the table cell to the table row.
                tr.Append(tc1);

                // Create a second table cell by copying the OuterXml value of the first table cell.
                DocumentFormat.OpenXml.Wordprocessing.TableCell tc2 = new DocumentFormat.OpenXml.Wordprocessing.TableCell(tc1.OuterXml);

                // Append the table cell to the table row.
                tr.Append(tc2);

                // Append the table row to the table.
                table.Append(tr);

                // Append the table to the document.
                doc.MainDocumentPart.Document.Body.Append(table);
            }
        }
コード例 #22
0
        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)));
        }
コード例 #23
0
        protected void btnIspisi_Click(object sender, EventArgs e)
        {
            Body      body;
            Paragraph par;
            Run       run;

            DocumentFormat.OpenXml.Wordprocessing.TableRow  tr;
            DocumentFormat.OpenXml.Wordprocessing.TableCell tc;
            TableCellProperties tcp;
            RunProperties       rp;

            WordprocessingDocument package = WordprocessingDocument.Create(HttpRuntime.AppDomainAppPath + "\\izleti.docx", WordprocessingDocumentType.Document);

            package.AddMainDocumentPart();

            Document document = new Document();

            package.MainDocumentPart.Document = document;
            body = document.AppendChild(new Body());
            SectionProperties sectionProps = body.AppendChild(new SectionProperties());

            sectionProps.Append(new PageMargin()
            {
                Top = 720, Right = 720, Bottom = 720, Left = 720, Header = 0, Footer = 0, Gutter = 0
            });                                                                                                                             // 1440 = 1", 720 = 0.5";

            par = body.AppendChild(new Paragraph());
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            rp.AppendChild(new Bold()
            {
                Val = OnOffValue.FromBoolean(true)
            });
            rp.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.FontSize()
            {
                Val = "32"
            });
            run.AppendChild(new Text("Izleti"));

            DocumentFormat.OpenXml.Wordprocessing.Table table = new DocumentFormat.OpenXml.Wordprocessing.Table();
            TableProperties props = new TableProperties
                                    (
                new TableBorders
                (
                    new TableWidth {
                Width = "5000", Type = TableWidthUnitValues.Pct
            },                                                                                  // 100%
                    new TopBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.None),
                Size = 6
            },
                    new BottomBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.Single),
                Size = 6
            },
                    new LeftBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.None),
                Size = 6
            },
                    new RightBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.None),
                Size = 6
            },
                    new InsideHorizontalBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.Single),
                Size = 6
            },
                    new InsideVerticalBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.None),
                Size = 6
            }
                )
                                    );

            table.AppendChild <TableProperties>(props);

            // red
            tr = table.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableRow());
            // ćelija
            tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
            tcp = tc.AppendChild(new TableCellProperties());
            tcp.Append(new Shading()
            {
                Val = ShadingPatternValues.Clear, Color = "auto", Fill = "black"
            });
            par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
            {
                Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
            })));
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            rp.Append(new Color()
            {
                Val = "ffffff"
            });
            rp.Append(new Bold()
            {
                Val = OnOffValue.FromBoolean(true)
            });
            run.Append(new Text("Datum"));
            // ćelija
            tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
            tcp = tc.AppendChild(new TableCellProperties());
            tcp.Append(new Shading()
            {
                Val = ShadingPatternValues.Clear, Color = "auto", Fill = "black"
            });
            par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
            {
                Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
            })));
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            rp.Append(new Color()
            {
                Val = "ffffff"
            });
            rp.Append(new Bold()
            {
                Val = OnOffValue.FromBoolean(true)
            });
            run.Append(new Text("Naziv"));
            // ćelija
            tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
            tcp = tc.AppendChild(new TableCellProperties());
            tcp.Append(new Shading()
            {
                Val = ShadingPatternValues.Clear, Color = "auto", Fill = "black"
            });
            par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
            {
                Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
            })));
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            rp.Append(new Color()
            {
                Val = "ffffff"
            });
            rp.Append(new Bold()
            {
                Val = OnOffValue.FromBoolean(true)
            });
            run.Append(new Text("Glavni vodič"));
            // ćelija
            tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
            tcp = tc.AppendChild(new TableCellProperties());
            tcp.Append(new Shading()
            {
                Val = ShadingPatternValues.Clear, Color = "auto", Fill = "black"
            });
            par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
            {
                Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
            })));
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            rp.Append(new Color()
            {
                Val = "ffffff"
            });
            rp.Append(new Bold()
            {
                Val = OnOffValue.FromBoolean(true)
            });
            run.Append(new Text("Pomoćni vodič"));
            // ćelija
            tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
            tcp = tc.AppendChild(new TableCellProperties());
            tcp.Append(new Shading()
            {
                Val = ShadingPatternValues.Clear, Color = "auto", Fill = "black"
            });
            par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
            {
                Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
            })));
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            rp.Append(new Color()
            {
                Val = "ffffff"
            });
            rp.Append(new Bold()
            {
                Val = OnOffValue.FromBoolean(true)
            });
            run.Append(new Text("Udruga"));
            // ćelija
            tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
            tcp = tc.AppendChild(new TableCellProperties());
            tcp.Append(new Shading()
            {
                Val = ShadingPatternValues.Clear, Color = "auto", Fill = "black"
            });
            par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
            {
                Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
            })));
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            rp.Append(new Color()
            {
                Val = "ffffff"
            });
            rp.Append(new Bold()
            {
                Val = OnOffValue.FromBoolean(true)
            });
            run.Append(new Text("Odredište"));
            // ćelija
            tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
            tcp = tc.AppendChild(new TableCellProperties());
            tcp.Append(new Shading()
            {
                Val = ShadingPatternValues.Clear, Color = "auto", Fill = "black"
            });
            par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
            {
                Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
            })));
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            rp.Append(new Color()
            {
                Val = "ffffff"
            });
            rp.Append(new Bold()
            {
                Val = OnOffValue.FromBoolean(true)
            });
            run.Append(new Text("Trajanje"));
            // ćelija
            tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
            tcp = tc.AppendChild(new TableCellProperties());
            tcp.Append(new Shading()
            {
                Val = ShadingPatternValues.Clear, Color = "auto", Fill = "black"
            });
            par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
            {
                Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
            })));
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            rp.Append(new Color()
            {
                Val = "ffffff"
            });
            rp.Append(new Bold()
            {
                Val = OnOffValue.FromBoolean(true)
            });
            run.Append(new Text("Broj sudionika"));

            string          query = "select izleti.datum, izleti.naziv, vodicig.prezime + ', ' + vodicig.ime as glavnivodic, vodicip.prezime + ', ' + vodicip.ime as pomocnivodic, udruge.naziv as udruga, izleti.odrediste, izleti.trajanje, izleti.brojsudionika from ((izleti left join vodici as vodicig on izleti.glavni_vod_id = vodicig.id) left join vodici as vodicip on izleti.pomocni_vod_id = vodicip.id) left join udruge on izleti.udr_id = udruge.id where 1 = 1 " + ViewState["filter"] + " order by datum desc";
            OleDbConnection con   = new OleDbConnection(ConfigurationManager.ConnectionStrings["connstr"].ConnectionString);
            OleDbCommand    cmd   = new OleDbCommand();

            cmd.CommandText = query;
            cmd.CommandType = CommandType.Text;
            cmd.Connection  = con;
            con.Open();
            OleDbDataReader dr = cmd.ExecuteReader();

            while (dr.Read())
            {
                tr  = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
                tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
                tcp = tc.AppendChild(new TableCellProperties());
                par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
                {
                    Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
                })));
                run = par.AppendChild(new Run());
                rp  = run.AppendChild(new RunProperties());
                run.Append(new Text(Convert.ToDateTime(dr["datum"]).ToString("dd.MM.yyyy.")));

                tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
                tcp = tc.AppendChild(new TableCellProperties());
                par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
                {
                    Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
                })));
                run = par.AppendChild(new Run());
                rp  = run.AppendChild(new RunProperties());
                run.Append(new Text(dr["naziv"] as string));

                tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
                tcp = tc.AppendChild(new TableCellProperties());
                par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
                {
                    Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
                })));
                run = par.AppendChild(new Run());
                rp  = run.AppendChild(new RunProperties());
                run.Append(new Text(dr["glavnivodic"] as string));

                tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
                tcp = tc.AppendChild(new TableCellProperties());
                par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
                {
                    Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
                })));
                run = par.AppendChild(new Run());
                rp  = run.AppendChild(new RunProperties());
                run.Append(new Text(dr["pomocnivodic"] as string));

                tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
                tcp = tc.AppendChild(new TableCellProperties());
                par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
                {
                    Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
                })));
                run = par.AppendChild(new Run());
                rp  = run.AppendChild(new RunProperties());
                run.Append(new Text(dr["udruga"] as string));

                tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
                tcp = tc.AppendChild(new TableCellProperties());
                par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
                {
                    Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
                })));
                run = par.AppendChild(new Run());
                rp  = run.AppendChild(new RunProperties());
                run.Append(new Text(dr["odrediste"] as string));

                tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
                tcp = tc.AppendChild(new TableCellProperties());
                par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
                {
                    Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
                })));
                run = par.AppendChild(new Run());
                rp  = run.AppendChild(new RunProperties());
                run.Append(new Text(dr["trajanje"].ToString()));

                tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
                tcp = tc.AppendChild(new TableCellProperties());
                par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
                {
                    Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
                })));
                run = par.AppendChild(new Run());
                rp  = run.AppendChild(new RunProperties());
                run.Append(new Text(dr["brojsudionika"].ToString()));

                table.Append(tr);
            }
            document.Body.Append(table);
            document.Save();
            package.Close();

            con.Close();

            Response.ContentType = "Application/docx";
            Response.AppendHeader("Content-Disposition", "attachment; filename=izleti.docx");
            Response.TransmitFile(HttpRuntime.AppDomainAppPath + "\\izleti.docx");
            Response.End();
        }
コード例 #24
0
        /// <summary>
        /// Create new Word document with a two column table from a fixed array.
        /// </summary>
        /// <returns>Is valid document</returns>
        public bool CreateDocumentWithTableFromArray(string pFileName)
        {
            mHasException = false;

            var names = new[, ]
            {
                { "Karen", "Payne" },
                { "Bill", "Smith" },
                { "Jane", "Lebow" },
                { "Jess", "Gallagher" }
            };

            var fileName = Path.Combine(DocumentFolder, pFileName);

            if (File.Exists(fileName))
            {
                File.Delete(fileName);
            }

            using (var document = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document))
            {
                MainDocumentPart mainPart = document.AddMainDocumentPart();
                mainPart.Document = new Document();
                mainPart.Document.AppendChild(new Body());

                var table = new Table();

                // set borders
                TableProperties props = Helpers.CreateTableProperties();
                table.AppendChild(props);

                // make table full width of page
                var tableWidth = new TableWidth()
                {
                    Width = "5000", Type = TableWidthUnitValues.Pct
                };
                table.AppendChild(tableWidth);

                for (var outerIndex = 0; outerIndex <= names.GetUpperBound(0); outerIndex++)
                {
                    var tableRow = new TableRow();
                    for (var innerIndex = 0; innerIndex <= names.GetUpperBound(1); innerIndex++)
                    {
                        var tableColumn = new TableCell();

                        tableColumn.Append(new Paragraph(new Run(new Text(names[outerIndex, innerIndex]))));

                        // Assume you want columns that are automatically sized.
                        tableColumn.Append(new TableCellProperties(new TableCellWidth {
                            Type = TableWidthUnitValues.Auto
                        }));
                        tableRow.Append(tableColumn);
                    }
                    table.Append(tableRow);
                }

                mainPart.Document.Body.Append(table);
                mainPart.Document.Save();
            }

            return(true);
        }
コード例 #25
0
        public static void WDAddTable(string fileName, string[] data1, string[] data2, string[] data3, string[] data4)
        {
            using (var document = WordprocessingDocument.Open(fileName, true))
            {
                var doc = document.MainDocumentPart.Document;

                //DocumentFormat.OpenXml.Wordprocessing.Table table = doc.Body.Elements<DocumentFormat.OpenXml.Wordprocessing.Table>().Where<>.
                DocumentFormat.OpenXml.Wordprocessing.Table table = doc.Body.Elements <DocumentFormat.OpenXml.Wordprocessing.Table>().ElementAtOrDefault(2);

                //    new DocumentFormat.OpenXml.Wordprocessing.Table().First() ;

                //Table table =
                //  doc.MainDocumentPart.Document.Body.Elements<Table>().First();

                TableProperties props = new TableProperties(
                    new TableBorders(
                        new DocumentFormat.OpenXml.Wordprocessing.TopBorder
                {
                    Val  = new EnumValue <BorderValues>(BorderValues.None),
                    Size = 9
                },
                        new DocumentFormat.OpenXml.Wordprocessing.BottomBorder
                {
                    Val  = new EnumValue <BorderValues>(BorderValues.None),
                    Size = 9
                },
                        new DocumentFormat.OpenXml.Wordprocessing.LeftBorder
                {
                    Val  = new EnumValue <BorderValues>(BorderValues.None),
                    Size = 9
                },
                        new DocumentFormat.OpenXml.Wordprocessing.RightBorder
                {
                    Val  = new EnumValue <BorderValues>(BorderValues.None),
                    Size = 9
                },
                        new InsideHorizontalBorder
                {
                    Val  = new EnumValue <BorderValues>(BorderValues.None),
                    Size = 9
                },
                        new InsideVerticalBorder
                {
                    Val  = new EnumValue <BorderValues>(BorderValues.None),
                    Size = 9
                }));
                table.AppendChild <TableProperties>(props);

                for (var i = 0; i <= data1.GetUpperBound(0); i++)
                {
                    var tr = new TableRow(new TableWidth {
                        Type = TableWidthUnitValues.Auto
                    });
                    var tc2 = new TableCell();
                    var tc3 = new TableCell();
                    var tc4 = new TableCell();
                    //for (var j = 0; j <= data.GetUpperBound(1); j++)
                    //{
                    var tc = new TableCell();
                    // Assume you want columns that are automatically sized.
                    if (i == 0)
                    {
                        tc.Append(new TableCellProperties(
                                      new TableCellWidth {
                            Type = TableWidthUnitValues.Auto
                        },
                                      new DocumentFormat.OpenXml.Wordprocessing.Bold(),
                                      new DocumentFormat.OpenXml.Wordprocessing.RunFonts()
                        {
                            Ascii = "Arial"
                        },
                                      new DocumentFormat.OpenXml.Wordprocessing.FontSize()
                        {
                            Val = "9"
                        },
                                      new Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(data1[i])),
                                                    new DocumentFormat.OpenXml.Wordprocessing.RunFonts()
                        {
                            Ascii = "Arial"
                        })
                                      ));

                        tr.Append(tc);



                        tc2.Append(new TableCellProperties(
                                       new TableCellWidth {
                            Type = TableWidthUnitValues.Dxa, Width = "350"
                        },
                                       new DocumentFormat.OpenXml.Wordprocessing.Bold(),
                                       new DocumentFormat.OpenXml.Wordprocessing.FontSize()
                        {
                            Val = "9"
                        }
                                       ));

                        tc3.Append(new TableCellProperties(
                                       new TableCellWidth {
                            Type = TableWidthUnitValues.Dxa, Width = "600"
                        },
                                       new DocumentFormat.OpenXml.Wordprocessing.Bold(),
                                       new DocumentFormat.OpenXml.Wordprocessing.FontSize()
                        {
                            Val = "9"
                        }
                                       ));
                    }
                    else
                    {
                        tc.Append(new TableCellProperties(
                                      new TableCellWidth {
                            Type = TableWidthUnitValues.Auto
                        },
                                      new DocumentFormat.OpenXml.Wordprocessing.RunFonts()
                        {
                            Ascii = "Arial"
                        },
                                      new DocumentFormat.OpenXml.Wordprocessing.FontSize()
                        {
                            Val = "9"
                        },
                                      new Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(data1[i])),
                                                    new DocumentFormat.OpenXml.Wordprocessing.RunFonts()
                        {
                            Ascii = "Arial"
                        })
                                      ));

                        tr.Append(tc);



                        tc2.Append(new TableCellProperties(
                                       new TableCellWidth {
                            Type = TableWidthUnitValues.Dxa, Width = "350"
                        },
                                       new DocumentFormat.OpenXml.Wordprocessing.FontSize()
                        {
                            Val = "9"
                        }
                                       ));

                        tc3.Append(new TableCellProperties(
                                       new TableCellWidth {
                            Type = TableWidthUnitValues.Dxa, Width = "600"
                        },
                                       new DocumentFormat.OpenXml.Wordprocessing.FontSize()
                        {
                            Val = "9"
                        }
                                       ));
                    }
                    //tc.Append(new Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(data1[i]))),
                    //    new TableCellProperties(
                    //                              new TableCellWidth { Type = TableWidthUnitValues.Dxa, Width = "500" },
                    //                               new DocumentFormat.OpenXml.Wordprocessing.FontSize() { Val = "9" }
                    //                               )
                    //    );
                    //tr.Append(tc);


                    tc2.Append(new Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(data2[i]))));
                    // Assume you want columns that are automatically sized.
                    tr.Append(tc2);


                    tc3.Append(new Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(data3[i]))));
                    // Assume you want columns that are automatically sized.

                    tr.Append(tc3);

                    tc4.Append(new TableCellProperties(
                                   new TableCellWidth {
                        Type = TableWidthUnitValues.Auto
                    },
                                   new DocumentFormat.OpenXml.Wordprocessing.Bold(),
                                   new DocumentFormat.OpenXml.Wordprocessing.RunFonts()
                    {
                        Ascii = "Arial"
                    },
                                   new DocumentFormat.OpenXml.Wordprocessing.FontSize()
                    {
                        Val = "9"
                    },
                                   new Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(data4[i])))
                                   ));

                    tr.Append(tc4);
                    // }
                    table.Append(tr);
                }
                //  doc.Body.Append(table);
                doc.Save();
            }
        }
コード例 #26
0
        public void Write(Marker marker, Table table)
        {
            if (table == null)
            {
                return;
            }

            var markerParagraph = marker.Container;
            var parent          = markerParagraph.Parent;

            var cellWriter = new TableCellWriter();

            var tableElement = new W.Table();

            var tableProp = new TableProperties();

            if (!string.IsNullOrEmpty(table.Width))
            {
                var tableStyle = new TableStyle()
                {
                    Val = "Table"
                };

                // Make the table width 100% of the page width.
                var tableWidth = new TableWidth()
                {
                    Width = table.Width, Type = TableWidthUnitValues.Pct
                };

                // Apply
                tableProp.Append(tableStyle, tableWidth);
                tableElement.AppendChild(tableProp);
            }

            AppendMargins(tableProp, table.TopMargin, table.LeftMargin, table.BottomMargin, table.RightMargin);

            foreach (var row in table.Rows)
            {
                var rowElement = new W.TableRow();

                if (row.Height > 0)
                {
                    rowElement.Append(
                        new TableRowProperties(
                            new TableRowHeight()
                    {
                        Val = (UInt32Value)(row.Height * 1U)
                    }
                            )
                        );
                }

                foreach (var cell in row.Cells)
                {
                    cellWriter.WriteTo(rowElement, cell);
                }

                tableElement.AppendChild(rowElement);
            }

            if (table.PageBreak == PageBreak.Before)
            {
                insertPageBreak(parent, markerParagraph);
            }

            parent.InsertAfter(tableElement, markerParagraph);
        }