public void CopyToFile_Test_CopiesCorrectHyperlinksToBookmarks()
        {
            Range        range        = _application.Documents.Add().Range();
            const string bookmarkName = "bookmark1";

            Interop.Paragraph paragraph1 = range.Paragraphs.Add();
            paragraph1.Range.Text = "bookmark";
            Interop.Bookmark bookmark = paragraph1.Range.Bookmarks.Add(bookmarkName);

            range.Paragraphs.Add();
            Interop.Paragraph paragraph2 = range.Paragraphs.Add();
            paragraph2.Range.Text = "link";
            range.Hyperlinks.Add(paragraph2.Range, SubAddress: bookmark);

            _tmpFile = new OpenXmlHelper().CopyToFile(range);

            using (WordprocessingDocument doc = WordprocessingDocument.Open(_tmpFile, true)) {
                OpenXml.Body body = doc.MainDocumentPart
                                    .Document
                                    .Body;

                OpenXml.BookmarkStart bookmarkStart = body.Descendants <OpenXml.BookmarkStart>().First();
                OpenXml.Hyperlink     hyperlink     = body.Descendants <OpenXml.Hyperlink>().First();

                Assert.That(bookmarkStart.Name.Value, Is.EqualTo(bookmarkName));
                Assert.That(hyperlink.Anchor.Value, Is.EqualTo(bookmarkName));
            }
        }
예제 #2
0
        public ReadWord(string filename)
        {
            try
            {
                //使用文件路径打开WordprocessingDocument进行处理
                using (WordprocessingDocument wordprocessingDocument =
                           WordprocessingDocument.Open(filename, true))
                {
                    // DocumentFormat.OpenXml.Wordprocessing.Body创建一个body对象,存储上述文档的body
                    DocumentFormat.OpenXml.Wordprocessing.Body body = wordprocessingDocument.MainDocumentPart.Document.Body;

                    //  定义一个elements,获取所有元素
                    IEnumerable <DocumentFormat.OpenXml.OpenXmlElement> elements = body.Elements <DocumentFormat.OpenXml.OpenXmlElement>();
                    //遍历元素列表,输出内容
                    foreach (DocumentFormat.OpenXml.OpenXmlElement element in elements)
                    {
                        strList += element.InnerText.ToString();
                        TextList.Add(element.InnerText);
                    }
                }
            }
            catch
            {
                Console.WriteLine("没有找到文件");
                Console.ReadKey();
            }
        }
예제 #3
0
        public void CopyToFileTextOnly_Test_DoesNotKeepHyperlinksAndBookmarks()
        {
            Range        range        = _application.Documents.Add().Range();
            const string bookmarkName = "bookmark1";

            Interop.Paragraph paragraph1 = range.Paragraphs.Add();
            paragraph1.Range.Text = "bookmark";
            Interop.Bookmark bookmark = paragraph1.Range.Bookmarks.Add(bookmarkName);

            range.Paragraphs.Add();
            Interop.Paragraph paragraph2 = range.Paragraphs.Add();
            paragraph2.Range.Text = "link";
            range.Hyperlinks.Add(paragraph2.Range, SubAddress: bookmark);

            _tmpFile = new OpenXmlHelper().CopyToFileTextOnly(range);

            using (WordprocessingDocument doc = WordprocessingDocument.Open(_tmpFile, true)) {
                OpenXml.Body body = doc.MainDocumentPart
                                    .Document
                                    .Body;

                CollectionAssert.IsEmpty(body.Descendants <OpenXml.BookmarkStart>());
                CollectionAssert.IsEmpty(body.Descendants <OpenXml.Hyperlink>());
            }
        }
예제 #4
0
        public object Convert()
        {
            FlowDocument flowdoc = new FlowDocument();

            //For Each p As OpenXmlPart In OpenXMLFile.MainDocumentPart.
            //Next
            flowdoc.PageWidth  = 816;
            flowdoc.PageHeight = 1056;
            DocumentFormat.OpenXml.Wordprocessing.Body body = OpenXMLFile.MainDocumentPart.Document.Body;
            foreach (DocumentFormat.OpenXml.OpenXmlElement oxmlobject in body.ChildElements)
            {
                DocumentFormat.OpenXml.Wordprocessing.Paragraph par = oxmlobject as DocumentFormat.OpenXml.Wordprocessing.Paragraph;
                if (par != null)
                {
                    System.Windows.Documents.Paragraph p = new System.Windows.Documents.Paragraph();
                    flowdoc.Blocks.Add(p);
                    foreach (DocumentFormat.OpenXml.OpenXmlElement paroxmlobject in par.ChildElements)
                    {
                        DocumentFormat.OpenXml.Wordprocessing.Run ru = paroxmlobject as DocumentFormat.OpenXml.Wordprocessing.Run;
                        if (ru != null)
                        {
                            System.Windows.Documents.Run r = new System.Windows.Documents.Run();
                            r.Text = ru.InnerText;
                            p.Inlines.Add(r);
                        }
                    }
                    //flowdoc.ContentStart.InsertTextInRun(par.InnerText)
                }
            }
            return(flowdoc);
        }
예제 #5
0
        public Document(String fileName)
        {
            this.FileName = fileName;
            docFileName = fileName + ".docx";

            packager = DocumentPackager.GetInstance();
            docxFile = packager.CreateDocument(docFileName);
            body = packager.GetBody();
        }
예제 #6
0
        private string[] readDocx(string path)
        {
            string totalText = "";

            using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(path, true))
            {
                DocumentFormat.OpenXml.Wordprocessing.Body body = wordDoc.MainDocumentPart.Document.Body;
                totalText = body.InnerText;
            }
            string[] ret = formatOddFileLayout(totalText);
            return(ret);
        }
예제 #7
0
        private static IEnumerable <Section> SplitToSectionsCore(
            this Word.Body body,
            Pack.MainDocumentPart mainDocumentPart,
            IStyleFactory styleFactory)
        {
            var sections = new List <Section>();

            var sectionElements           = new List <OpenXml.OpenXmlCompositeElement>();
            var headerFooterConfiguration = HeaderFooterConfiguration.Empty;

            Word.SectionProperties wordSectionProperties;

            foreach (var e in body.RenderableChildren())
            {
                sectionElements.Add(e);
                if (!(e is Word.Paragraph paragraph))
                {
                    continue;
                }

                wordSectionProperties = paragraph.GetSectionProperties();
                if (wordSectionProperties == null)
                {
                    continue;
                }

                var section = sectionElements.CreateSection(wordSectionProperties, mainDocumentPart, headerFooterConfiguration, sections.Count == 0, styleFactory);
                headerFooterConfiguration = section.HeaderFooterConfiguration;
                sections.Add(section);
                sectionElements.Clear();
            }

            wordSectionProperties = body
                                    .ChildsOfType <Word.SectionProperties>()
                                    .Single();

            var lastSection = sectionElements.CreateSection(wordSectionProperties, mainDocumentPart, headerFooterConfiguration, sections.Count == 0, styleFactory);

            sections.Add(lastSection);
            return(sections);
        }
        public void InitWFile(string theFilepath)
        {
            // XmlDocument theDocument = null;

            var fileInfo = new FileInfo(theFilepath);

            string tempFile = Path.GetTempPath();

            Task T = Task.Run(() => { System.IO.File.Copy(fileInfo.FullName, tempFile + ".docx"); });


            Task T2 = Task.Run(() => { WordprocessingDocument theDocument = WordprocessingDocument.Open(fileInfo.FullName, false);
                                       W.Body body = theDocument.MainDocumentPart.Document.Body;
                                       foreach (W.Paragraph theParagraph in body.Elements <W.Paragraph>())
                                       {
                                           // using theParagraph.innerText for each line
                                       }
                               });
            //using (WordprocessingDocument theDocument = WordprocessingDocument.Open(fileInfo.FullName, false))

            //OK
        }
예제 #9
0
        public void GenerarArchivoDocxDesdeTextosHtml(string[] textosHtml, System.IO.Stream archivo)
        {
            using (DocumentFormat.OpenXml.Packaging.WordprocessingDocument objPaquete = DocumentFormat.OpenXml.Packaging.WordprocessingDocument.Create(archivo, DocumentFormat.OpenXml.WordprocessingDocumentType.Document))
            {
                DocumentFormat.OpenXml.Packaging.MainDocumentPart objDocumentoPrincipal = objPaquete.MainDocumentPart;
                if (objDocumentoPrincipal == null)
                {
                    objDocumentoPrincipal = objPaquete.AddMainDocumentPart();
                    new DocumentFormat.OpenXml.Wordprocessing.Document(new DocumentFormat.OpenXml.Wordprocessing.Body()).Save(objDocumentoPrincipal);
                }

                NotesFor.HtmlToOpenXml.HtmlConverter       objConversorHtml = new NotesFor.HtmlToOpenXml.HtmlConverter(objDocumentoPrincipal);
                DocumentFormat.OpenXml.Wordprocessing.Body objCuerpo        = objDocumentoPrincipal.Document.Body;
                objConversorHtml.ImageProcessing = NotesFor.HtmlToOpenXml.ImageProcessing.ManualProvisioning;
                objConversorHtml.ProvisionImage += eventoHtmlDoc_ProveerImagenes;

                for (int intIndiceHtml = 0; intIndiceHtml < textosHtml.Length; intIndiceHtml++)
                {
                    if (intIndiceHtml > 0)
                    {
                        Paragraph PageBreakParagraph = new Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Break()
                        {
                            Type = BreakValues.Page
                        }));
                        objCuerpo.Append(PageBreakParagraph);
                    }

                    var arrParrafos = objConversorHtml.Parse(textosHtml[intIndiceHtml]);
                    foreach (var objParrafo in arrParrafos)
                    {
                        objCuerpo.Append(objParrafo);
                    }
                }

                objDocumentoPrincipal.Document.Save();
            }
        }
예제 #10
0
        public static List <DocumentContentControl> GetContentControls(string fileName)
        {
            #region WordprocessingDocument

            List <DocumentContentControl> documentContentControls = new List <DocumentContentControl>();

            using (WordprocessingDocument myDocument = WordprocessingDocument.Open(fileName, true))
            {
                #region List<DocumentContentControl>
                // Create a Body object.
                DocumentFormat.OpenXml.Wordprocessing.Body body = myDocument.MainDocumentPart.Document.Body;

                foreach (var item in body.ChildElements)
                {
                    if (item is Paragraph)                                  //если поле
                    {
                        foreach (var item1 in item.Where(n => n is SdtRun)) //n => n.GetType() == typeof(SdtRun)
                        {
                            documentContentControls.Add(new FieldContentControl(item1.Elements <SdtProperties>().FirstOrDefault().Elements <Tag>().FirstOrDefault().Val));
                        }
                    }

                    if (item is SdtBlock)//если список или таблица
                    {
                        ListContentControl documentList = new ListContentControl(item.ChildElements.First <SdtProperties>().Elements <Tag>().FirstOrDefault().Val);;

                        foreach (var item1 in item.ChildElements.First <SdtContentBlock>().ChildElements)
                        {
                            if (item1 is SdtBlock)                                                                                  //если простой список или список с таблицей
                            {
                                if (item1.ChildElements.First <SdtContentBlock>().Where(n => n is Table).FirstOrDefault() is Table) //если список с таблицей
                                {
                                    foreach (var item2 in item1.ChildElements.First <SdtContentBlock>().ChildElements.FirstOrDefault().Where(n => n is TableRow))
                                    {
                                        TableContentControl documentTable = new TableContentControl(item1.ChildElements.First <SdtProperties>().Elements <Tag>().FirstOrDefault().Val);
                                        foreach (var item3 in item2.Where(n => n is TableCell))
                                        {
                                            foreach (var item4 in item3.ChildElements)
                                            {
                                                if (item4 is Paragraph)//если поле, вложенное в параграф
                                                {
                                                    foreach (var item5 in item4.Where(n => n is SdtRun))
                                                    {
                                                        documentTable.Fields.Add(new FieldContentControl(item5.Elements <SdtProperties>().FirstOrDefault().Elements <Tag>().FirstOrDefault().Val));
                                                    }
                                                }

                                                if (item4 is SdtBlock)//если поле
                                                {
                                                    documentTable.Fields.Add(new FieldContentControl(item4.Elements <SdtProperties>().FirstOrDefault().Elements <Tag>().FirstOrDefault().Val));
                                                }
                                            }
                                        }

                                        if (documentTable.Fields.Count != 0)
                                        {
                                            documentList.Tables.Add(documentTable);
                                        }
                                    }
                                }
                                else//если простой список
                                {
                                    documentList.Fields.Add(new FieldContentControl(item1.Elements <SdtProperties>().FirstOrDefault().Elements <Tag>().FirstOrDefault().Val));
                                }
                            }

                            if (item1 is Paragraph)//если список с полями
                            {
                                foreach (var item2 in item1.Where(n => n is SdtRun))
                                {
                                    documentList.Fields.Add(new FieldContentControl(item2.Elements <SdtProperties>().FirstOrDefault().Elements <Tag>().FirstOrDefault().Val));
                                }
                            }

                            if (item1 is Table)//если таблица
                            {
                                foreach (var item2 in item1.Where(n => n is TableRow))
                                {
                                    TableContentControl documentTable = new TableContentControl(item.ChildElements.First <SdtProperties>().Elements <Tag>().FirstOrDefault().Val);

                                    foreach (var item3 in item2.Where(n => n is TableCell))
                                    {
                                        foreach (var item4 in item3.ChildElements)
                                        {
                                            if (item4 is Paragraph)//если поле, вложенное в параграф
                                            {
                                                foreach (var item5 in item4.Where(n => n is SdtRun))
                                                {
                                                    documentTable.Fields.Add(new FieldContentControl(item5.Elements <SdtProperties>().FirstOrDefault().Elements <Tag>().FirstOrDefault().Val));
                                                }
                                            }

                                            if (item4 is SdtBlock)//если поле
                                            {
                                                documentTable.Fields.Add(new FieldContentControl(item4.Elements <SdtProperties>().FirstOrDefault().Elements <Tag>().FirstOrDefault().Val));
                                            }
                                        }
                                    }

                                    if (documentTable.Fields.Count != 0)
                                    {
                                        documentContentControls.Add(documentTable);
                                    }
                                }
                            }
                        }

                        if (documentList.Fields.Count != 0)
                        {
                            documentContentControls.Add(documentList);
                        }
                    }
                }
                #endregion
            }

            return(documentContentControls);

            #endregion
        }
예제 #11
0
        public override void Write()
        {
            ExportFileName = PopulatedName(ExportFileName);
            if (!String.IsNullOrWhiteSpace(ExportFileName))
            {
                DocProperties["FileName"]   = ExportFileName;
                DocProperties["TableCount"] = _dataSet.Tables.Count.ToString();
                if (PopulatePropertiesOnly)
                {
                    if (_dataSet != null)
                    {
                        foreach (DataTable dTable in _dataSet.Tables)
                        {
                            if (dTable.Rows.Count > 0)
                            {
                                foreach (DataColumn dColumn in dTable.Columns)
                                {
                                    DocProperties[dColumn.ColumnName] = dTable.Rows[0][dColumn].ToString();
                                }
                            }
                        }
                    }
                }
                switch (DestinationType)
                {
                case OfficeFileType.WordDocument:
                    WordprocessingDocument doc;
                    if (File.Exists(TemplateFileName))
                    {
                        doc = WordprocessingDocument.CreateFromTemplate(TemplateFileName);
                        doc = (WordprocessingDocument)doc.SaveAs(ExportFileName);
                    }
                    else
                    {
                        doc = WordprocessingDocument.Create(ExportFileName, WordprocessingDocumentType.Document);
                    }
                    CustomFilePropertiesPart customProp = doc.CustomFilePropertiesPart;
                    if (customProp == null)
                    {
                        customProp = doc.AddCustomFilePropertiesPart();
                    }
                    SetFileProperties(customProp);

                    MainDocumentPart mainDoc = doc.MainDocumentPart;
                    if (mainDoc == null)
                    {
                        mainDoc = doc.AddMainDocumentPart();
                    }

                    DocumentSettingsPart settingsPart = mainDoc.GetPartsOfType <DocumentSettingsPart>().First();
                    UpdateFieldsOnOpen   updateFields = new UpdateFieldsOnOpen
                    {
                        Val = new OnOffValue(true)
                    };
                    settingsPart.Settings.PrependChild <UpdateFieldsOnOpen>(updateFields);
                    settingsPart.Settings.Save();

                    if (!PopulatePropertiesOnly)
                    {
                        if (mainDoc.Document == null)
                        {
                            mainDoc.Document = new word.Document();
                        }
                        word.Body body       = new word.Body();
                        bool      firstTable = true;
                        foreach (DataTable dt in _dataSet.Tables)
                        {
                            if (!firstTable)
                            {
                                body.Append(GetPageBreak());
                            }
                            else
                            {
                                firstTable = false;
                            }
                            body.Append(GetParagraph(dt.TableName));
                            body.Append(GetWordTable(dt));
                        }
                        mainDoc.Document.Append(body);
                    }
                    mainDoc.Document.Save();
                    doc.Dispose();
                    break;

                case OfficeFileType.ExcelWorkbook:
                    SpreadsheetDocument spreadSheet;
                    if (File.Exists(TemplateFileName))
                    {
                        spreadSheet = SpreadsheetDocument.CreateFromTemplate(TemplateFileName);
                        spreadSheet = (SpreadsheetDocument)spreadSheet.SaveAs(ExportFileName);
                    }
                    else
                    {
                        spreadSheet = SpreadsheetDocument.Create(ExportFileName, SpreadsheetDocumentType.Workbook);
                        spreadSheet.Save();
                    }
                    using (SpreadsheetDocument workbook = spreadSheet)
                    {
                        CustomFilePropertiesPart excelCustomProp = workbook.AddCustomFilePropertiesPart();
                        SetFileProperties(excelCustomProp);

                        if (workbook.WorkbookPart == null)
                        {
                            workbook.AddWorkbookPart();
                        }
                        if (workbook.WorkbookPart.Workbook == null)
                        {
                            workbook.WorkbookPart.Workbook = new excel.Workbook();
                        }
                        if (workbook.WorkbookPart.Workbook.Sheets == null)
                        {
                            workbook.WorkbookPart.Workbook.Sheets = new excel.Sheets();
                        }
                        excel.Sheets sheets = workbook.WorkbookPart.Workbook.Sheets;
                        foreach (DataTable table in _dataSet.Tables)
                        {
                            excel.SheetData sheetData = null;
                            WorksheetPart   sheetPart = null;
                            excel.Sheet     sheet     = null;
                            foreach (OpenXmlElement element in sheets.Elements())
                            {
                                if (element is Sheet)
                                {
                                    sheet = (Sheet)element;
                                    if (sheet.Name.Value.Equals(table.TableName, StringComparison.CurrentCultureIgnoreCase))
                                    {
                                        //Assign the sheetPart
                                        sheetPart = (WorksheetPart)workbook.WorkbookPart.GetPartById(sheet.Id.Value);
                                        sheetData = sheetPart.Worksheet.GetFirstChild <SheetData>();
                                        break;
                                    }
                                }
                                sheet = null;
                            }

                            if (sheet == null)
                            {
                                sheetPart           = workbook.WorkbookPart.AddNewPart <WorksheetPart>(); //Create a new WorksheetPart
                                sheetData           = new excel.SheetData();                              //create a new SheetData
                                sheetPart.Worksheet = new excel.Worksheet(sheetData);                     /// Create a new Worksheet with the sheetData and link it to the sheetPart...

                                string relationshipId = workbook.WorkbookPart.GetIdOfPart(sheetPart);     //get the ID of the sheetPart.
                                sheet = new excel.Sheet()
                                {
                                    Id = relationshipId, SheetId = 1, Name = table.TableName
                                };                        //create a new sheet
                                sheets.Append(sheet);     //append the sheet to the sheets.
                            }

                            List <String> columns = new List <string>();
                            foreach (System.Data.DataColumn column in table.Columns)
                            {
                                columns.Add(column.ColumnName);
                            }
                            if (PrintTableHeader)
                            {
                                excel.Row headerRow = new excel.Row();

                                foreach (string column in columns)
                                {
                                    excel.Cell cell = new excel.Cell
                                    {
                                        DataType  = excel.CellValues.String,
                                        CellValue = new excel.CellValue(GetColumnName(table.Columns[column]))
                                    };
                                    headerRow.AppendChild(cell);
                                }


                                sheetData.AppendChild(headerRow);
                            }

                            foreach (DataRow dsrow in table.Rows)
                            {
                                excel.Row newRow = new excel.Row();
                                foreach (String col in columns)
                                {
                                    excel.Cell cell = new excel.Cell
                                    {
                                        DataType  = excel.CellValues.String,
                                        CellValue = new excel.CellValue(dsrow[col].ToString())     //
                                    };
                                    newRow.AppendChild(cell);
                                }

                                sheetData.AppendChild(newRow);
                            }
                            sheetPart.Worksheet.Save();
                        }
                        workbook.WorkbookPart.Workbook.Save();
                        workbook.Save();
                        workbook.Close();
                    }

                    break;
                }
            }
        }
예제 #12
0
 public void TableToWord(Wordprocessing.Table table, WordprocessingDocument document)
 {
     Wordprocessing.Body body = new Wordprocessing.Body();
     Wordprocessing.Paragraph paragraph = new Wordprocessing.Paragraph();
     body.Append(table);
     body.Append(paragraph);
     document.MainDocumentPart.Document.AppendChild(body);
     document.MainDocumentPart.Document.Save();
     document.Close();
 }
예제 #13
0
        public Wordprocessing.Body insertinform()
        {
            Wordprocessing.Body body = new Wordprocessing.Body();
            //Параграф1
            Wordprocessing.Paragraph paragraph1 = new Wordprocessing.Paragraph();
            Wordprocessing.ParagraphProperties paragraphProperties1 = new Wordprocessing.ParagraphProperties();
            Wordprocessing.SpacingBetweenLines spacingBetweenLines1 = new Wordprocessing.SpacingBetweenLines() { After = "0" };
            Wordprocessing.Justification justification1 = new Wordprocessing.Justification() { Val = Wordprocessing.JustificationValues.Center };
            paragraphProperties1.Append(spacingBetweenLines1);
            paragraphProperties1.Append(justification1);
            Wordprocessing.Run run1 = new Wordprocessing.Run();
            Wordprocessing.RunProperties runProperties1 = new Wordprocessing.RunProperties();
            Wordprocessing.RunFonts runFonts2 = new Wordprocessing.RunFonts() { Ascii = "Times New Roman", HighAnsi = "Times New Roman", ComplexScript = "Times New Roman" };
            Wordprocessing.Bold bold2 = new Wordprocessing.Bold();
            Wordprocessing.FontSize fontSize2 = new Wordprocessing.FontSize() { Val = "24" };
            runProperties1.Append(runFonts2);
            runProperties1.Append(bold2);
            runProperties1.Append(fontSize2);
            Wordprocessing.Text text1 = new Wordprocessing.Text();
            text1.Text = "ФГБОУВПО \"ПЕРМСКИЙ ГОСУДАРСТВЕННЫЙ НАЦИОНАЛЬНЫЙ ИССЛЕДОВАТЕЛЬСКИЙ УНИВЕРСИТЕТ\"";
            run1.Append(runProperties1);
            run1.Append(text1);
            paragraph1.Append(paragraphProperties1);
            paragraph1.Append(run1);

            //Параграф2
            Wordprocessing.Paragraph paragraph2 = new Wordprocessing.Paragraph();

            Wordprocessing.ParagraphProperties paragraphProperties2 = new Wordprocessing.ParagraphProperties();
            Wordprocessing.SpacingBetweenLines spacingBetweenLines2 = new Wordprocessing.SpacingBetweenLines() { After = "0" };
            Wordprocessing.Justification justification2 = new Wordprocessing.Justification() { Val = Wordprocessing.JustificationValues.Center };
            paragraphProperties2.Append(spacingBetweenLines2);
            paragraphProperties2.Append(justification2);
            Wordprocessing.Run run2 = new Wordprocessing.Run();

            Wordprocessing.RunProperties runProperties2 = new Wordprocessing.RunProperties();
            Wordprocessing.RunFonts runFonts4 = new Wordprocessing.RunFonts() { Ascii = "Times New Roman", HighAnsi = "Times New Roman", ComplexScript = "Times New Roman" };
            Wordprocessing.FontSize fontSize4 = new Wordprocessing.FontSize() { Val = "24" };

            runProperties2.Append(runFonts4);
            runProperties2.Append(fontSize4);
            Wordprocessing.Text text2 = new Wordprocessing.Text();
            text2.Text = "Механико-математический факультет ";

            run2.Append(runProperties2);
            run2.Append(text2);

            Wordprocessing.Run run3 = new Wordprocessing.Run();

            Wordprocessing.RunProperties runProperties3 = new Wordprocessing.RunProperties();
            Wordprocessing.RunFonts runFonts5 = new Wordprocessing.RunFonts() { Ascii = "Times New Roman", HighAnsi = "Times New Roman", ComplexScript = "Times New Roman" };
            Wordprocessing.FontSize fontSize5 = new Wordprocessing.FontSize() { Val = "24" };
            runProperties3.Append(runFonts5);
            runProperties3.Append(fontSize5);
            Wordprocessing.Break break1 = new Wordprocessing.Break();
            Wordprocessing.Text text3 = new Wordprocessing.Text();
            text3.Text = "очная форма обучения";

            run3.Append(runProperties3);
            run3.Append(break1);
            run3.Append(text3);

            paragraph2.Append(paragraphProperties2);
            paragraph2.Append(run2);
            paragraph2.Append(run3);

            //Параграф2
            Wordprocessing.Paragraph paragraph3 = new Wordprocessing.Paragraph() { RsidParagraphAddition = "004D49E1", RsidParagraphProperties = "004D49E1", RsidRunAdditionDefault = "004D49E1" };

            Wordprocessing.ParagraphProperties paragraphProperties3 = new Wordprocessing.ParagraphProperties();
            Wordprocessing.SpacingBetweenLines spacingBetweenLines3 = new Wordprocessing.SpacingBetweenLines() { After = "0" };
            Wordprocessing.Justification justification3 = new Wordprocessing.Justification() { Val = Wordprocessing.JustificationValues.Center };
            paragraphProperties3.Append(spacingBetweenLines3);
            paragraphProperties3.Append(justification3);
            Wordprocessing.Run run4 = new Wordprocessing.Run();

            Wordprocessing.RunProperties runProperties4 = new Wordprocessing.RunProperties();
            Wordprocessing.RunFonts runFonts7 = new Wordprocessing.RunFonts() { Ascii = "Times New Roman", HighAnsi = "Times New Roman", ComplexScript = "Times New Roman" };
            Wordprocessing.Bold bold4 = new Wordprocessing.Bold();

            runProperties4.Append(runFonts7);
            runProperties4.Append(bold4);
            Wordprocessing.Text text4 = new Wordprocessing.Text();
            text4.Text = "ЭКЗАМЕНАЦИОННАЯ ВЕДОМОСТЬ";
            run4.Append(runProperties4);
            run4.Append(text4);

            Wordprocessing.Run run5 = new Wordprocessing.Run();
            Wordprocessing.Break break2 = new Wordprocessing.Break();
            run5.Append(break2);

            paragraph3.Append(paragraphProperties3);
            paragraph3.Append(run4);
            paragraph3.Append(run5);

            body.Append(paragraph1);
            body.Append(paragraph2);
            body.Append(paragraph3);
            return body;
        }
예제 #14
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();
        }
예제 #15
0
        private void opMaachenToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult thedlgOpenRes;

            dlgOpen.FileName = "";
            dlgOpen.Filter   = "documents (*.docx)|*.docx";

            thedlgOpenRes = dlgOpen.ShowDialog();
            if (thedlgOpenRes == DialogResult.OK)
            {
                //File Open
                using (WordprocessingDocument theDocument = WordprocessingDocument.Open(dlgOpen.FileName, false))
                {
                    W.Body body    = theDocument.MainDocumentPart.Document.Body;
                    int    counter = 0;

                    DataGridView dataGrid = new DataGridView();
                    dataGrid.Name = "dataGrid";
                    dataGrid.AllowUserToAddRows      = false;
                    dataGrid.AllowUserToOrderColumns = false;
                    splitContainer1.Panel1.Controls.Add(dataGrid);
                    dataGrid.MouseDown += new System.Windows.Forms.MouseEventHandler(this.dataGrid_MouseDown);

                    dataGrid.Dock       = DockStyle.Fill;
                    dataGrid.DataSource = null;

                    dataGrid.ColumnCount         = 3;
                    dataGrid.Columns[0].ReadOnly = true;
                    dataGrid.Columns[1].ReadOnly = true;
                    dataGrid.Columns[2].ReadOnly = true;
                    dataGrid.Columns[0].Name     = "ID";
                    dataGrid.Columns[1].Name     = "Source";
                    dataGrid.Columns[2].Name     = "Target";
                    dataGrid.AutoSizeRowsMode    = DataGridViewAutoSizeRowsMode.AllCells;
                    dataGrid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
                    dataGrid.Columns[1].DefaultCellStyle.WrapMode = DataGridViewTriState.True;
                    dataGrid.Columns[2].DefaultCellStyle.WrapMode = DataGridViewTriState.True;

                    foreach (W.Paragraph theParagraph in body.Elements <W.Paragraph>())
                    {
                        if (theParagraph.InnerText.Length >= 1)
                        // check if it's not an empty line
                        {
                            counter++;
                            //if (counter > 0) { reEditor.AppendText("\r\n"); }

                            dataGrid.Rows.Add(counter, theParagraph.InnerText, " ");

                            // data
                            // dataGrid.Rows[counter].Cells[0].Value = counter;
                            // dataGrid.Rows[counter].Cells[1].Value = theParagraph.InnerText;

                            /*
                             * //Edito
                             * reEditor.ForeColor = Color.Gray;
                             * reEditor.AppendText("None");
                             * reEditor.AppendText("\r\n");
                             *
                             * //BaseText
                             * reEditor.SelectionBackColor = Color.LightGreen;
                             * reEditor.AppendText(theParagraph.InnerText);
                             * reEditor.AppendText("\r\n");
                             *
                             * //Translation
                             * reEditor.SelectionBackColor = System.Drawing.Color.Yellow;
                             * reEditor.AppendText("The empty translation");
                             * reEditor.AppendText("\r\n");
                             */
                        }
                    }
                }
            }
        }
        public ActionResult ExportWord()
        {
            ExportRetailModel model = Session["@ExportWord@"] as ExportRetailModel;
            //render view
            const string viewName = "ViewForWord";
            String       html     = RenderStringView(viewName, model);

            try
            {
                const string filename    = "StreamTest.docx";
                const string contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                using (MemoryStream generatedDocument = new MemoryStream())
                {
                    using (WordprocessingDocument package = WordprocessingDocument.Create(generatedDocument, WordprocessingDocumentType.Document))
                    {
                        MainDocumentPart mainPart = package.MainDocumentPart;
                        if (mainPart == null)
                        {
                            mainPart = package.AddMainDocumentPart();
                            new HtmlDocument.Document(new HtmlDocument.Body()).Save(mainPart);
                        }
                        if (Request.Url != null)
                        {
                            HtmlXml.HtmlConverter converter = new HtmlXml.HtmlConverter(mainPart)
                            {
                                BaseImageUrl = new Uri(Request.Url.Scheme + "://" + Request.Url.Authority)
                            };
                            HtmlDocument.Body body = mainPart.Document.Body;
                            var paragraphs         = converter.Parse(html);
                            foreach (OpenXmlCompositeElement t in paragraphs)
                            {
                                body.Append(t);
                            }
                        }
                        mainPart.Document.Save();
                    }
                    byte[] bytesInStream = generatedDocument.ToArray(); // simpler way of converting to array
                    generatedDocument.Close();
                    Response.Clear();
                    Response.ContentType = contentType;
                    Response.AddHeader("content-disposition", "attachment;filename=" + filename);
                    //this will generate problems
                    Response.BinaryWrite(bytesInStream);
                    try
                    {
                        Response.End();
                    }
                    catch (Exception ex)
                    {
                        return(new EmptyResult());
                        //Response.End(); generates an exception. if you don't use it, you get some errors when Word opens the file...
                    }
                    Session.Remove("@ExportWord@");
                    return(new EmptyResult());
                }
            }
            catch (Exception ex)
            {
                return(new EmptyResult());
            }
        }