/// <summary> /// Выполняет поиск стандартных элементов, представляющих флажки в документе, /// по значению параметра <paramref name="name"/> и заполняет их значением параметра <paramref name="value"/>. /// Если элементы не найдены, действие не выполняется. /// </summary> /// <param name="name">Имя целевого(ых) стандартных элементов.</param> /// <param name="value">Значение для вставки в стандартные элементы.</param> /// <exception cref="InvalidSdtElementException"> /// Возникает если дерево дочерних элементов <see cref="SdtElement"/> содержит недопустимые элементы /// или отсутствует обязательный дочерний элемент. /// </exception> protected void FillSdtElement(string name, bool value) { name.ThrowIfNullOrWhiteSpace(nameof(name)); try { foreach (SdtElement element in _elemetns.Where(element => element.SdtProperties.GetFirstChild <SdtAlias>()?.Val == name)) { if (element.SdtProperties.GetFirstChild <W14.SdtContentCheckBox>() is W14.SdtContentCheckBox contentCheckBox) { contentCheckBox.Checked = new W14.Checked() { Val = value ? W14.OnOffValues.One : W14.OnOffValues.Zero }; var sdtContentBlock = new SdtContentBlock(); Run run = sdtContentBlock.AppendChild(new Run()); if (element.SdtProperties.GetFirstChild <RunProperties>() is RunProperties properties) { run.AppendChild(properties.CloneNode(true)); } element.SdtProperties.RemoveAllChildren <SdtPlaceholder>(); run.AppendChild(new Text(contentCheckBox.Checked.Val == W14.OnOffValues.One ? "☒" : "☐")); element.ReplaceChild(sdtContentBlock, element.LastChild); } } } catch (InvalidOperationException) { throw new InvalidSdtElementException(name); } }
/// <summary> /// Выполняет поиск стандартных элементов в документе по значению <paramref name="name"/> /// и заполняет их значением <c><paramref name="value"/>.ToString()</c>. /// Если элементы не найдены, действие не выполняется. /// </summary> /// <param name="name">Имя целевого(ых) стандартных элементов.</param> /// <param name="value">Ссылка на объект, строковое представление которого необходимо поместить в элемент.</param> /// <exception cref="InvalidSdtElementException"> /// Возникает если дерево дочерних элементов <see cref="SdtElement"/> содержит недопустимые элементы /// или отсутствует обязательный дочерний элемент. /// </exception> protected void FillSdtElement(string name, object value) { name.ThrowIfNullOrWhiteSpace(nameof(name)); value.ThrowIfNull(nameof(value)); try { foreach (SdtElement element in _elemetns.Where(element => element.SdtProperties.GetFirstChild <SdtAlias>()?.Val == name)) { var newContentBlock = new SdtContentRun(); Run run = newContentBlock.AppendChild(new Run()); if (element.SdtProperties.GetFirstChild <RunProperties>() is RunProperties properties) { run.AppendChild(properties.CloneNode(true)); } element.SdtProperties.RemoveAllChildren <SdtPlaceholder>(); run.AppendChild(new Text(value.ToString())); element.ReplaceChild(newContentBlock, element.LastChild); } } catch (InvalidOperationException) { throw new InvalidSdtElementException(name); } }
public static void InsertText(String text, String styleXml, OpenXmlElement parentNode) { // Разделить строку на подстроки //String[] runs = macroVarValue.Split(new char[] { '\r', '\n' }); //String[] runs = Regex.Split(macroVarValue, "\r\n|\r|\n"); String[] runs = Regex.Split(text, "\r\n"); // Вставить текст foreach (String run in runs) { // Создать новый Paragraph Paragraph newParagraph = parentNode.AppendChild(new Paragraph()); // Вернуть старый стиль в Paragraph ParagraphProperties newParagraphProperties = newParagraph.AppendChild(new ParagraphProperties()); newParagraphProperties.InnerXml = styleXml; // Создать новый Run Run newRun = newParagraph.AppendChild(new Run()); // Вернуть старый стиль в Run RunProperties newRunProperties = newRun.AppendChild(new RunProperties()); newRunProperties.InnerXml = styleXml; // Вставить в него текст newRun.AppendChild(new Text(run)); } }
private void AddPersonalRow(Body body, OpenXmlElement after, string firstName, string lastName, string city) { Paragraph par = new Paragraph(); var run = new Run(); run.RunProperties = new RunProperties(); run.RunProperties.FontSize = new FontSize(); run.RunProperties.FontSize.Val = new StringValue("28"); run.AppendChild(new Break()); run.AppendChild(new TabChar()); run.AppendChild(new Text($"{firstName} {lastName}, {city}")); par.AppendChild(run); body.InsertAfter(par, after); }
/**public void getFooterWithPageNumber() * { * foreach (Section wordSection in this.adoc.Sections) * { * Range footerRange = wordSection.Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; * footerRange.InlineShapes.AddHorizontalLineStandard(); * footerRange.Font.ColorIndex = WdColorIndex.wdDarkRed; * footerRange.Font.Size = 10; * footerRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; * adoc.Sections[1].Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].PageNumbers.Add(); * } * }**/ public void generateCoverPage(string data) { body.Append(new Paragraph(new Run(new Break()))); body.Append(new Paragraph(new Run(new Break()))); body.Append(new Paragraph(new Run(new Break()))); body.Append(new Paragraph(new Run(new Break()))); //heading Paragraph heading = new Paragraph(); ParagraphProperties hp = new ParagraphProperties(); hp.Justification = new Justification() { Val = JustificationValues.Center }; heading.Append(hp); Run r = new Run(); RunProperties runProperties = r.AppendChild(new RunProperties()); Bold bold = new Bold(); bold.Val = OnOffValue.FromBoolean(true); FontSize size = new FontSize(); size.Val = "60"; runProperties.AppendChild(bold); runProperties.AppendChild(size); Text t = new Text(data); r.Append(t); heading.Append(r); body.Append(heading); //subheading Paragraph subheading = new Paragraph(); ParagraphProperties shp = new ParagraphProperties(); shp.Justification = new Justification() { Val = JustificationValues.Center }; subheading.Append(shp); Run rs = new Run(); RunProperties rhProperties = rs.AppendChild(new RunProperties()); Bold bs = new Bold(); bs.Val = OnOffValue.FromBoolean(true); FontSize sh = new FontSize(); sh.Val = "40"; rhProperties.AppendChild(bs); rhProperties.AppendChild(sh); Text subhead = new Text("BUSINESS PLAN"); rs.Append(subhead); subheading.Append(rs); body.Append(subheading); addPageBreak(); }
private static Run CreateParagraphRun(RunProperties runProperties, string paragraphText) { var run = new Run(); run.AppendChild(runProperties.CloneNode(true)); ParseTextForOpenXml(run, paragraphText); return(run); }
// Add the bold style at a Run object used by a Paragraph in order to insert text in a Document. public RunProperties getBold(Run run) { RunProperties runProperties = run.AppendChild(new RunProperties()); var bold = new Bold(); bold.Val = OnOffValue.FromBoolean(true); runProperties.AppendChild(bold); return(runProperties); }
public static void CreateWordprocessingDocument(string filepath, List <Student> st) { String fileName = Constants.Locations.ImagesFolder + "/" + Constants.Locations.ImageFile; using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document)) { // Add a main document part. MainDocumentPart mainPart = wordDocument.AddMainDocumentPart(); // Create the document structure and add some text. mainPart.Document = new Document(); Body body = mainPart.Document.AppendChild(new Body()); foreach (var stu in st) { Paragraph para = body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); run.AppendChild(new Text("Hello , my name is " + stu.FirstName + " " + stu.LastName + "\n\n")); string imageFilePath = stu.FullPathUrl + "/" + Constants.Locations.ImageFile; var ImageBytes = FTP.DownloadFileBytes(imageFilePath); SaveBytesToFile(fileName, ImageBytes); ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg); using (FileStream stream = new FileStream(fileName, FileMode.Open)) { imagePart.FeedData(stream); } AddImageToBody(wordDocument, mainPart.GetIdOfPart(imagePart)); Paragraph PageBreakParagraph = new Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Break() { Type = BreakValues.Page })); body.Append(PageBreakParagraph); } // var styles = ExtractStylesPart(filepath, true); } }
public void InsertDecisionDetailViewMessage() { Paragraph para = _body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); RunProperties runProperties = getHeading2(run); run.AppendChild(new Text(++_diagmarCounter + ". Decision Detail View")); // _body.AppendChild(new Paragraph(new Run(new Text(++_diagmarCounter + ". Decision Detail View")))); _body.AppendChild(new Paragraph()); }
public void InsertDecisionWithoutTopicMessage() { Paragraph para = _body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); RunProperties runProperties = getHeading2(run); run.AppendChild(new Text(++_diagmarCounter + ". Decisions without topic")); //_body.AppendChild(new Paragraph(new Run(new Text("Decisions not included in a topic:")))); _body.AppendChild(new Paragraph()); }
public static WP.Paragraph GenerateParagraphWithText(string content) { var p = new WP.Paragraph(); var r = new WP.Run(); var text = new WP.Text(content); r.AppendChild(text); p.AppendChild(r); return(p); }
/// <summary> /// Create a new document, append a single paragraph, set font and color. /// </summary> /// <returns>Is valid document</returns> public bool CreateDocumentWithSimpleParagraph(string pFileName) { mHasException = false; 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(); var body = mainPart.Document.AppendChild(new Body()); var para = body.AppendChild(new Paragraph()); Run runPara = para.AppendChild(new Run()); // Set the font to Arial to the first Run. var runProperties = new RunProperties( new RunFonts() { Ascii = "Arial" }); var color = new Color { Val = Helpers.ColorConverter(System.Drawing.Color.SandyBrown) }; runProperties.Append(color); Run run = document.MainDocumentPart.Document.Descendants <Run>().First(); run.PrependChild <RunProperties>(runProperties); var paragraphText = "The most basic unit of block-level content within a Word processing document, paragraphs are " + "stored using the <p> element. A paragraph defines a distinct division of content that begins on " + "a new line. A paragraph can contain three pieces of information: optional paragraph properties, " + "inline content (typically runs), and a set of optional revision IDs used to compare the content " + "of two documents."; runPara.AppendChild(new Text(paragraphText)); mainPart.Document.Save(); } return(Helpers.ValidateWordDocument(fileName) == 0); }
public static void InsertHeader(string header, WordprocessingDocument wordDoc, string currentHeader) { if (header != currentHeader) { //if currentHeader is not equal to new header, insert new header. currentHeader = header; Body body = wordDoc.MainDocumentPart.Document.Body; Paragraph para = body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); run.AppendChild(new Text(currentHeader)); } }
public static void CreateWordprocessingDocument(string filepath) { // Create a document by supplying the filepath. using (var wordprocessingDocument = WordprocessingDocument.Create(filepath, DocumentFormat.OpenXml.WordprocessingDocumentType.Document)) { MainDocumentPart mainPart = wordprocessingDocument.AddMainDocumentPart(); mainPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document(); Body body = mainPart.Document.AppendChild(new Body()); DocumentFormat.OpenXml.Wordprocessing.Paragraph para = body.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph()); DocumentFormat.OpenXml.Wordprocessing.Run run = para.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Run()); run.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Text("siddiq")); wordprocessingDocument.MainDocumentPart.Document.Save(); } }
public void InsertTopicTable(ITopic topic) { Paragraph para = _body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); RunProperties runProperties = getHeading3(run); run.AppendChild(new Text(_diagmarCounter + "." + (++_topicCounter) + ". " + topic.Name)); //_body.AppendChild(new Paragraph(new Run(new Text(_diagmarCounter + "." + (++_topicCounter) + ". " + topic.Name)))); //Topic Name if (topic.Description != "") { _body.AppendChild(new Paragraph(new Run(new Text(topic.Description)))); //Topic Desc } _body.AppendChild(new Paragraph()); }
public void InsertDiagramImage(IEADiagram diagram) { if (diagram.IsRelationshipView()) { Paragraph para = _body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); RunProperties runProperties = getHeading2(run); run.AppendChild(new Text(++_diagmarCounter + ". Relationship View: " + diagram.Name)); //_body.AppendChild(new Paragraph(new Run(new Text(++_diagmarCounter + ". Relationship Viewpoint")))); } else if (diagram.IsStakeholderInvolvementView()) { Paragraph para = _body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); RunProperties runProperties = getHeading2(run); run.AppendChild( new Text(++_diagmarCounter + ". Decision Stakeholder Involvement View: " + diagram.Name)); //_body.AppendChild(new Paragraph(new Run(new Text(++_diagmarCounter + ". Decision Stakeholder Involvement Viewpoint")))); } else if (diagram.IsChronologicalView()) { Paragraph para = _body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); RunProperties runProperties = getHeading2(run); run.AppendChild(new Text(++_diagmarCounter + ". Decision Chronological View: " + diagram.Name)); //_body.AppendChild(new Paragraph(new Run(new Text(++_diagmarCounter + ". Decision Chronological Viewpoint")))); } else { return; } _body.AppendChild(new Paragraph(new Run(new Text()))); ImagePart imagePart = _mainPart.AddImagePart(ImagePartType.Emf); FileStream fs = diagram.DiagramToStream(); imagePart.FeedData(fs); Image image = Image.FromFile(fs.Name); AddImageToBody(_mainPart.GetIdOfPart(imagePart), Utils.GetImageSize(image)); //cleanup: fs.Close(); image.Dispose(); File.Delete(fs.Name); }
private void NextLevel_1(string pFileName) { 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(); var body = mainPart.Document.AppendChild(new Body()); var para = body.AppendChild(new Paragraph()); Run runPara = para.AppendChild(new Run()); // Set the font to Arial to the first Run. var runProperties = new RunProperties( new RunFonts() { Ascii = "Arial" }); var color = new Color { Val = Helpers.ColorConverter(System.Drawing.Color.SandyBrown) }; runProperties.Append(color); Run run = document.MainDocumentPart.Document.Descendants <Run>().First(); run.PrependChild <RunProperties>(runProperties); var paragraphText = "Styling paragraph with font color"; runPara.AppendChild(new Text(paragraphText)); mainPart.Document.Save(); } Console.WriteLine(Helpers.ValidateWordDocument(fileName)); }
public static void createDocument(string filepath) { // Create a document by supplying the filepath. using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(filepath, DocumentFormat.OpenXml.WordprocessingDocumentType.Document)) { // Add a main document part. MainDocumentPart mainPart = wordDocument.AddMainDocumentPart(); // Create the document structure and add some text. mainPart.Document = new Document(); Body body = mainPart.Document.AppendChild(new Body()); DocumentFormat.OpenXml.Wordprocessing.Paragraph para = body.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph()); DocumentFormat.OpenXml.Wordprocessing.Run run = para.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Run()); run.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Text("HQ - QUANTUM 2012")); } }
// Add properties with a stykle similar to Heading 3 style at a Run object used by a Paragraph in order to insert text in a Document. public RunProperties getHeading3(Run run) { RunProperties runProperties = run.AppendChild(new RunProperties()); var bold = new Bold(); bold.Val = OnOffValue.FromBoolean(true); var color = new Color { Val = "365F91", ThemeColor = ThemeColorValues.Accent1, ThemeShade = "BF" }; var size = new FontSize { Val = new StringValue("25") }; runProperties.AppendChild(bold); runProperties.AppendChild(color); runProperties.AppendChild(size); return(runProperties); }
private List <string> ExtractImages(Body content, MainDocumentPart wDoc, string imageFolderPath) { List <string> imageList = new List <string>(); foreach (DocumentFormat.OpenXml.Wordprocessing.Paragraph par in content.Descendants <DocumentFormat.OpenXml.Wordprocessing.Paragraph>()) { ParagraphProperties paragraphProperties = par.ParagraphProperties; for (int i = 0; i < par.Descendants <Run>().Count(); i++) { Run run = par.Descendants <Run>().ElementAt(i); Drawing image = run.Descendants <Drawing>().FirstOrDefault(); if (image != null) { var imageFirst = image.Inline.Graphic.GraphicData.Descendants <DocumentFormat.OpenXml.Drawing.Pictures.Picture>().FirstOrDefault(); var blip = imageFirst.BlipFill.Blip.Embed.Value; ImagePart img = (ImagePart)wDoc.Document.MainDocumentPart.GetPartById(blip); string imageFileName = string.Empty; string imageFilePath = string.Empty; using (Image toSaveImage = Bitmap.FromStream(img.GetStream())) { imageFileName = "Img_" + imageCount; imageFilePath = imageFolderPath + "\\" + imageFileName + ".png"; try { toSaveImage.Save(imageFilePath, ImageFormat.Png); } catch (Exception ex) { } } imageList.Add(imageFilePath); Run run2 = par.Descendants <Run>().ElementAt(i - 1); run2.AppendChild(new Text(" Images/" + imageFileName + ".png")); image.Remove(); imageCount++; } } } return(imageList); }
public WordDocument(string filename) { _filename = filename; using ( WordprocessingDocument wordDoc = WordprocessingDocument.Create(_filename, WordprocessingDocumentType.Document)) { _mainPart = wordDoc.AddMainDocumentPart(); _mainPart.Document = new Document(); _body = _mainPart.Document.AppendChild(new Body()); DateTime saveNow = DateTime.Now; Paragraph para = _body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); RunProperties runProperties = getHeading1(run); run.AppendChild(new Text("Decision Report [" + saveNow + "]")); //_body.Append(new Paragraph(new Run(new Text("Decision Report [" + saveNow + "]")))); _body.AppendChild(new Paragraph()); } }
/// <summary> /// Add the text paragraph. /// </summary> /// <param name="txt">The text.</param> /// <param name="boldStyle">if set to <c>true</c> [bold style].</param> public void AddTextParagraph( string txt, bool boldStyle) { // Assign a reference to the existing document body. Body body = _wordProcessingDocument.MainDocumentPart.Document.Body; // Add new text. Paragraph para = body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); run.AppendChild(new Text(txt)); //create RunProperties and append styles RunProperties runProperties = new RunProperties(); if (boldStyle) { runProperties.Append(new Bold()); } // Set the RunProperties to the RunProperties containing the styles run.RunProperties = runProperties; }
public static void CreateWordprocessingDocument(string filepath, string myimage, List <Student> students) { // Create a document by supplying the filepath. using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document)) { // Add a main document part. MainDocumentPart mainPart = wordDocument.AddMainDocumentPart(); ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg); // Create the document structure and add some text. mainPart.Document = new Document(); Body body = mainPart.Document.AppendChild(new Body()); Paragraph para = body.AppendChild(new Paragraph()); Run run1 = para.AppendChild(new Run()); run1.AppendChild(new Text("Here is a list of students from the ftp directory, with each student getting their own page: ")); foreach (var student in students) { Paragraph para2 = body.AppendChild(new Paragraph()); Run run2 = para2.AppendChild(new Run( new Break() { Type = BreakValues.Page })); run2.AppendChild(new Text(student.FirstName + " " + student.LastName)); if (student.MyRecord == true) { using (FileStream stream = new FileStream(Constants.Locations.imgpath, FileMode.Open)) { imagePart.FeedData(stream); } AddImageToBody(wordDocument, mainPart.GetIdOfPart(imagePart)); } } } }
public static void Insert(string fullPathToDocument, string fullPathToImageFile) { List <KeyValuePair <string, string> > keyValuePairs = new List <KeyValuePair <string, string> >(); keyValuePairs.Add(new KeyValuePair <string, string>("Deponi", "Picture 1")); keyValuePairs.Add(new KeyValuePair <string, string>("Deponi", "Picture 2")); keyValuePairs.Add(new KeyValuePair <string, string>("Deponi", "Picture 3")); keyValuePairs.Add(new KeyValuePair <string, string>("Have", "Picture 4")); keyValuePairs.Add(new KeyValuePair <string, string>("Metal", "Picture 5")); keyValuePairs.Add(new KeyValuePair <string, string>("Metal", "Picture 6")); using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(fullPathToDocument, true)) { string currentHeader = ""; foreach (var keyValuePair in keyValuePairs) { if (currentHeader != keyValuePair.Key) { if (!string.IsNullOrEmpty(currentHeader)) { // insert pakebreak Body body = wordDoc.MainDocumentPart.Document.Body; Paragraph para = body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); Break pageBreak = run.AppendChild(new Break()); pageBreak.Type = BreakValues.Page; } InsertHeader(keyValuePair.Key, wordDoc, currentHeader); currentHeader = keyValuePair.Key; } InsertPicture(keyValuePair.Value, wordDoc); } } }
/// <summary> /// Creates an image paragraph. /// </summary> /// <param name="relationshipId">The relationship id.</param> /// <param name="name">The name.</param> /// <param name="description">The description.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <returns>The <see cref="Paragraph" /> containing the image.</returns> private DocumentFormat.OpenXml.Wordprocessing.Paragraph CreateImageParagraph( string relationshipId, string name, string description, double width, double height) { // http://msdn.microsoft.com/en-us/library/documentformat.openxml.drawing.extents.aspx // http://polymathprogrammer.com/2009/10/22/english-metric-units-and-open-xml/ // cx (Extent Length) // Specifies the length of the extents rectangle in EMUs. This rectangle shall dictate the size of the object as displayed (the result of any scaling to the original object). // Example: Consider a DrawingML object specified as follows: // <… cx="1828800" cy="200000"/> // The cx attributes specifies that this object has a height of 1828800 EMUs (English Metric Units). end example] // The possible values for this attribute are defined by the ST_PositiveCoordinate simple type (§20.1.10.42). // cy (Extent Width) // Specifies the width of the extents rectangle in EMUs. This rectangle shall dictate the size of the object as displayed (the result of any scaling to the original object). // Example: Consider a DrawingML object specified as follows: // < … cx="1828800" cy="200000"/> // The cy attribute specifies that this object has a width of 200000 EMUs (English Metric Units). end example] // The possible values for this attribute are defined by the ST_PositiveCoordinate simple type (§20.1.10.42). var paragraph1 = new DocumentFormat.OpenXml.Wordprocessing.Paragraph { RsidParagraphAddition = "00D91137", RsidRunAdditionDefault = "00AC08EB" }; var run1 = new Run(); var runProperties1 = new RunProperties(); var noProof1 = new NoProof(); runProperties1.AppendChild(noProof1); var drawing1 = new Drawing(); var inline1 = new Inline { DistanceFromTop = 0U, DistanceFromBottom = 0U, DistanceFromLeft = 0U, DistanceFromRight = 0U }; var extent1 = new Extent { Cx = 5753100L, Cy = 3600450L }; extent1.Cx = (long)(width * 914400); extent1.Cy = (long)(height * 914400); var effectExtent1 = new EffectExtent { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L }; var docProperties1 = new DocProperties { Id = 1U, Name = name, Description = description }; var nonVisualGraphicFrameDrawingProperties1 = new NonVisualGraphicFrameDrawingProperties(); var graphicFrameLocks1 = new GraphicFrameLocks { NoChangeAspect = true }; graphicFrameLocks1.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main"); nonVisualGraphicFrameDrawingProperties1.AppendChild(graphicFrameLocks1); var graphic1 = new Graphic(); graphic1.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main"); var graphicData1 = new GraphicData { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" }; var picture1 = new Picture(); picture1.AddNamespaceDeclaration("pic", "http://schemas.openxmlformats.org/drawingml/2006/picture"); var nonVisualPictureProperties1 = new NonVisualPictureProperties(); var nonVisualDrawingProperties1 = new NonVisualDrawingProperties { Id = 0U, Name = name, Description = description }; var nonVisualPictureDrawingProperties1 = new NonVisualPictureDrawingProperties(); var pictureLocks1 = new PictureLocks { NoChangeAspect = true, NoChangeArrowheads = true }; nonVisualPictureDrawingProperties1.AppendChild(pictureLocks1); nonVisualPictureProperties1.AppendChild(nonVisualDrawingProperties1); nonVisualPictureProperties1.AppendChild(nonVisualPictureDrawingProperties1); var blipFill1 = new BlipFill(); var blip1 = new Blip { Embed = relationshipId }; var blipExtensionList1 = new BlipExtensionList(); var blipExtension1 = new BlipExtension { Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}" }; var useLocalDpi1 = new UseLocalDpi { Val = false }; useLocalDpi1.AddNamespaceDeclaration("a14", "http://schemas.microsoft.com/office/drawing/2010/main"); blipExtension1.AppendChild(useLocalDpi1); blipExtensionList1.AppendChild(blipExtension1); blip1.AppendChild(blipExtensionList1); var sourceRectangle1 = new SourceRectangle(); var stretch1 = new Stretch(); var fillRectangle1 = new FillRectangle(); stretch1.AppendChild(fillRectangle1); blipFill1.AppendChild(blip1); blipFill1.AppendChild(sourceRectangle1); blipFill1.AppendChild(stretch1); var shapeProperties1 = new ShapeProperties { BlackWhiteMode = BlackWhiteModeValues.Auto }; var transform2D1 = new Transform2D(); var offset1 = new Offset { X = 0L, Y = 0L }; var extents1 = new Extents { Cx = extent1.Cx, Cy = extent1.Cy }; transform2D1.AppendChild(offset1); transform2D1.AppendChild(extents1); var presetGeometry1 = new PresetGeometry { Preset = ShapeTypeValues.Rectangle }; var adjustValueList1 = new AdjustValueList(); presetGeometry1.AppendChild(adjustValueList1); var noFill1 = new NoFill(); var outline1 = new Outline(); var noFill2 = new NoFill(); outline1.AppendChild(noFill2); shapeProperties1.AppendChild(transform2D1); shapeProperties1.AppendChild(presetGeometry1); shapeProperties1.AppendChild(noFill1); shapeProperties1.AppendChild(outline1); picture1.AppendChild(nonVisualPictureProperties1); picture1.AppendChild(blipFill1); picture1.AppendChild(shapeProperties1); graphicData1.AppendChild(picture1); graphic1.AppendChild(graphicData1); inline1.AppendChild(extent1); inline1.AppendChild(effectExtent1); inline1.AppendChild(docProperties1); inline1.AppendChild(nonVisualGraphicFrameDrawingProperties1); inline1.AppendChild(graphic1); drawing1.AppendChild(inline1); run1.AppendChild(runProperties1); run1.AppendChild(drawing1); paragraph1.AppendChild(run1); return(paragraph1); }
//replaces all relative subflow file paths with absolute subflow file path private void ProcessSubFlows(string originalDocFilePath, string duplicateDocFilePath, bool deploy) { WordprocessingDocument duplicateDoc = WordprocessingDocument.Open(duplicateDocFilePath, true); var paragraphs = duplicateDoc.MainDocumentPart.RootElement.Descendants <DocumentFormat.OpenXml.Wordprocessing.Paragraph>(); foreach (DocumentFormat.OpenXml.Wordprocessing.Paragraph paragraph in paragraphs) { string firstWord = paragraph.InnerText.ToLower().TrimStart().Split(' ')[0]; if (firstWord == "tagui") { subFlowCount++; subFlowTotal++; string subflowFilePath = ""; string[] arr = paragraph.InnerText.ToLower().TrimStart().Split(' '); for (int i = 1; i < arr.Length; i++) { subflowFilePath += arr[i] + " "; } string subflowAbsFilePath = subflowFilePath; if (!subflowFilePath.Contains(":")) { subflowAbsFilePath = GetFlowFolderPath() + subflowFilePath; } foreach (Run run in paragraph.Descendants <Run>()) { run.RemoveAllChildren <Text>(); } Run newRun = paragraph.AppendChild(new Run()); string workingFolder = GetWorkingFolderPath(deploy); newRun.AppendChild(new Text("tagui " + workingFolder + "WorkFlow" + subFlowCount + ".tag")); subFlowFilePaths.Add(subflowAbsFilePath); } if (firstWord == "write" || firstWord == "dump" || firstWord == "save" || firstWord == "table") { string[] arr = paragraph.InnerText.ToLower().TrimStart().Split(' '); string lastWord = arr[arr.Length - 1]; if (lastWord.Substring(lastWord.Length - 3).ToLower() == "csv") { for (int i = arr.Length - 1; i > 0; i--) { if (arr[i] == "to") { string csvFile = GetSavedFolderPath(); for (int j = i + 1; j < arr.Length; j++) { csvFile += arr[j]; if (j != arr.Length - 1) { csvFile += " "; } } if (!csvList.Any(x => csvList.Contains(csvFile))) { csvList.Add(csvFile); } break; } } } } } duplicateDoc.Close(); }
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()); }
public static void CreateWordprocessingDocumentFromApi(string filepath, List <StudentNewModel> st) { String fileName = "Users/kavyaarora/Downloads/CSV-2 3/Content/Images/MyImage.jpg"; using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document)) { // Add a main document part. MainDocumentPart mainPart = wordDocument.AddMainDocumentPart(); // Create the document structure and add some text. mainPart.Document = new Document(); Body body = mainPart.Document.AppendChild(new Body()); foreach (var stu in st) { Paragraph para = body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); run.AppendChild(new Text("Id: " + stu.Id)); Paragraph para0 = body.AppendChild(new Paragraph()); Run run0 = para0.AppendChild(new Run()); run0.AppendChild(new Text("Username: "******"Name: " + stu.Name)); Paragraph para2 = body.AppendChild(new Paragraph()); Run run2 = para2.AppendChild(new Run()); run2.AppendChild(new Text("Phone: " + stu.Phone)); Paragraph para3 = body.AppendChild(new Paragraph()); Run run3 = para3.AppendChild(new Run()); run3.AppendChild(new Text("Email: " + stu.Email)); Paragraph para4 = body.AppendChild(new Paragraph()); Run run4 = para4.AppendChild(new Run()); run4.AppendChild(new Text("Website: " + stu.Website)); Paragraph PageBreakParagraph = new Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Break() { Type = BreakValues.Page })); body.Append(PageBreakParagraph); } // var styles = ExtractStylesPart(filepath, true); } }
Word.TableRow CreateRow(ArrayList cellText) { Word.TableRow tr = new Word.TableRow(); // Create cells with simple text. foreach (string s in cellText) { Word.TableCell tc = new Word.TableCell(); Word.Paragraph p = new Word.Paragraph(); Word.Run r = new Word.Run(); Word.Text t = new Word.Text(s); r.AppendChild(t); p.AppendChild(r); tc.AppendChild(p); tr.AppendChild(tc); } return tr; }
/// <summary> /// Create a new document, append a single paragraph, set font and color. /// - add first paragraph with normal style, color brown /// - add second paragraph with normal style, default color /// - add a third paragraph with part bold and highlight/shade, part normal. /// </summary> /// <returns>Is valid document</returns> public bool CreateDocumentWithMultipleParagraphAndImage(string pFileName) { mHasException = false; 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(); var body = mainPart.Document.AppendChild(new Body()); var para = body.AppendChild(new Paragraph()); Run runPara = para.AppendChild(new Run()); // Set the font to Arial to the first Run. var runProperties = new RunProperties( new RunFonts() { Ascii = "Arial" }); var color = new Color { Val = Helpers.ColorConverter(System.Drawing.Color.Brown) }; runProperties.Append(color); Run run = document.MainDocumentPart.Document.Descendants <Run>().First(); run.PrependChild <RunProperties>(runProperties); var paragraphText = "The most basic unit of block-level content within a Word processing document, paragraphs are " + "stored using the <p> element. A paragraph defines a distinct division of content that begins on " + "a new line. A paragraph can contain three pieces of information: optional paragraph properties, " + "inline content (typically runs), and a set of optional revision IDs used to compare the content " + "of two documents."; runPara.AppendChild(new Text(paragraphText)); // add second paragraph para = body.AppendChild(new Paragraph()); runPara = para.AppendChild(new Run()); paragraphText = "A paragraph's properties are specified via the <pPr>element. Some examples of paragraph properties " + "are alignment, border, hyphenation override, indentation, line spacing, shading, text direction, " + "and widow/orphan control."; runPara.AppendChild(new Text(paragraphText)); // Highlight and bold some text. para = body.AppendChild(new Paragraph()); run = para.AppendChild(new Run()); runProperties = run.AppendChild(new RunProperties()); runProperties.AppendChild(new Bold { Val = OnOffValue.FromBoolean(true) }); var shading = new Shading() { Val = ShadingPatternValues.Clear, Fill = Helpers.ColorConverter(System.Drawing.Color.Yellow) }; runProperties.Append(shading); run.AppendChild(new Text("This is highlight/bold")); // back to normal text run = para.AppendChild(new Run()); run.AppendChild(new Text(", and this text is normal.")); int imageWidth = 0; int imageHeight = 0; ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg); var imageFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images", "F2.png"); using (var image = new System.Drawing.Bitmap(imageFileName)) { imageWidth = image.Width; imageHeight = image.Height; } using (var stream = new FileStream(imageFileName, FileMode.Open)) { imagePart.FeedData(stream); } Helpers.AddImageToBody(document, mainPart.GetIdOfPart(imagePart), imageWidth.PixelToEmu(), imageHeight.PixelToEmu()); para = body.AppendChild(new Paragraph()); run = para.AppendChild(new Run()); run.AppendChild(new Text("We just inserted an image.")); mainPart.Document.Save(); } return(Helpers.ValidateWordDocument(fileName) == 0); }
/// <summary> /// Creates an image paragraph. /// </summary> /// <param name="relationshipId">The relationship id.</param> /// <param name="name">The name.</param> /// <param name="description">The description.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <returns>The <see cref="Paragraph" /> containing the image.</returns> private DocumentFormat.OpenXml.Wordprocessing.Paragraph CreateImageParagraph( string relationshipId, string name, string description, double width, double height) { // http://msdn.microsoft.com/en-us/library/documentformat.openxml.drawing.extents.aspx // http://polymathprogrammer.com/2009/10/22/english-metric-units-and-open-xml/ // cx (Extent Length) // Specifies the length of the extents rectangle in EMUs. This rectangle shall dictate the size of the object as displayed (the result of any scaling to the original object). // Example: Consider a DrawingML object specified as follows: // <… cx="1828800" cy="200000"/> // The cx attributes specifies that this object has a height of 1828800 EMUs (English Metric Units). end example] // The possible values for this attribute are defined by the ST_PositiveCoordinate simple type (§20.1.10.42). // cy (Extent Width) // Specifies the width of the extents rectangle in EMUs. This rectangle shall dictate the size of the object as displayed (the result of any scaling to the original object). // Example: Consider a DrawingML object specified as follows: // < … cx="1828800" cy="200000"/> // The cy attribute specifies that this object has a width of 200000 EMUs (English Metric Units). end example] // The possible values for this attribute are defined by the ST_PositiveCoordinate simple type (§20.1.10.42). var paragraph1 = new DocumentFormat.OpenXml.Wordprocessing.Paragraph { RsidParagraphAddition = "00D91137", RsidRunAdditionDefault = "00AC08EB" }; var run1 = new Run(); var runProperties1 = new RunProperties(); var noProof1 = new NoProof(); runProperties1.AppendChild(noProof1); var drawing1 = new Drawing(); var inline1 = new Inline { DistanceFromTop = 0U, DistanceFromBottom = 0U, DistanceFromLeft = 0U, DistanceFromRight = 0U }; var extent1 = new Extent { Cx = 5753100L, Cy = 3600450L }; extent1.Cx = (long)(width * 914400); extent1.Cy = (long)(height * 914400); var effectExtent1 = new EffectExtent { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L }; var docProperties1 = new DocProperties { Id = 1U, Name = name, Description = description }; var nonVisualGraphicFrameDrawingProperties1 = new NonVisualGraphicFrameDrawingProperties(); var graphicFrameLocks1 = new GraphicFrameLocks { NoChangeAspect = true }; graphicFrameLocks1.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main"); nonVisualGraphicFrameDrawingProperties1.AppendChild(graphicFrameLocks1); var graphic1 = new Graphic(); graphic1.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main"); var graphicData1 = new GraphicData { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" }; var picture1 = new Picture(); picture1.AddNamespaceDeclaration("pic", "http://schemas.openxmlformats.org/drawingml/2006/picture"); var nonVisualPictureProperties1 = new NonVisualPictureProperties(); var nonVisualDrawingProperties1 = new NonVisualDrawingProperties { Id = 0U, Name = name, Description = description }; var nonVisualPictureDrawingProperties1 = new NonVisualPictureDrawingProperties(); var pictureLocks1 = new PictureLocks { NoChangeAspect = true, NoChangeArrowheads = true }; nonVisualPictureDrawingProperties1.AppendChild(pictureLocks1); nonVisualPictureProperties1.AppendChild(nonVisualDrawingProperties1); nonVisualPictureProperties1.AppendChild(nonVisualPictureDrawingProperties1); var blipFill1 = new BlipFill(); var blip1 = new Blip { Embed = relationshipId }; var blipExtensionList1 = new BlipExtensionList(); var blipExtension1 = new BlipExtension { Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}" }; var useLocalDpi1 = new UseLocalDpi { Val = false }; useLocalDpi1.AddNamespaceDeclaration("a14", "http://schemas.microsoft.com/office/drawing/2010/main"); blipExtension1.AppendChild(useLocalDpi1); blipExtensionList1.AppendChild(blipExtension1); blip1.AppendChild(blipExtensionList1); var sourceRectangle1 = new SourceRectangle(); var stretch1 = new Stretch(); var fillRectangle1 = new FillRectangle(); stretch1.AppendChild(fillRectangle1); blipFill1.AppendChild(blip1); blipFill1.AppendChild(sourceRectangle1); blipFill1.AppendChild(stretch1); var shapeProperties1 = new ShapeProperties { BlackWhiteMode = BlackWhiteModeValues.Auto }; var transform2D1 = new Transform2D(); var offset1 = new Offset { X = 0L, Y = 0L }; var extents1 = new Extents { Cx = extent1.Cx, Cy = extent1.Cy }; transform2D1.AppendChild(offset1); transform2D1.AppendChild(extents1); var presetGeometry1 = new PresetGeometry { Preset = ShapeTypeValues.Rectangle }; var adjustValueList1 = new AdjustValueList(); presetGeometry1.AppendChild(adjustValueList1); var noFill1 = new NoFill(); var outline1 = new Outline(); var noFill2 = new NoFill(); outline1.AppendChild(noFill2); shapeProperties1.AppendChild(transform2D1); shapeProperties1.AppendChild(presetGeometry1); shapeProperties1.AppendChild(noFill1); shapeProperties1.AppendChild(outline1); picture1.AppendChild(nonVisualPictureProperties1); picture1.AppendChild(blipFill1); picture1.AppendChild(shapeProperties1); graphicData1.AppendChild(picture1); graphic1.AppendChild(graphicData1); inline1.AppendChild(extent1); inline1.AppendChild(effectExtent1); inline1.AppendChild(docProperties1); inline1.AppendChild(nonVisualGraphicFrameDrawingProperties1); inline1.AppendChild(graphic1); drawing1.AppendChild(inline1); run1.AppendChild(runProperties1); run1.AppendChild(drawing1); paragraph1.AppendChild(run1); return paragraph1; }
static void Main(string[] args) { Student myrecord = new Student { StudentId = "200430242", FirstName = "BalaPrathima", LastName = "Gade" }; Student student1 = new Student(); List <string> directories = FTP.GetDirectory(Constants.FTP.BaseUrl); List <Student> students = new List <Student>(); foreach (var directory in directories) { Student student = new Student() { AbsoluteUrl = Constants.FTP.BaseUrl }; student.UID = Guid.NewGuid().ToString(); student.FromDirectory(directory); if (student.StudentId == "200430242") { student.IsMe = true; } students.Add(student); } HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(string.Format("https://jsonplaceholder.typicode.com/users")); WebReq.Method = "GET"; HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse(); Console.WriteLine(WebResp.StatusCode); Console.WriteLine(WebResp.Server); string jsonString; using (Stream stream = WebResp.GetResponseStream()) //modified from your code since the using statement disposes the stream automatically when done { StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8); jsonString = reader.ReadToEnd(); } List <Model.Users> users = JsonConvert.DeserializeObject <List <Model.Users> >(jsonString); Console.WriteLine(users.Count()); Console.WriteLine(jsonString); /*-----------------------WORD DOCUMENT-------------------------------------- */ string docxFilePath = $"{Constants.Locations.DataFolder}//info.docx"; //string ftpImagePath = Constants.FTP.BaseUrl + "/200430242 BalaPrathima Gade/myimage.jpg"; string studentsImagePath = $"{Constants.Locations.ImagesFolder}//myimage.jpg"; // Create a document by supplying the filepath. using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(docxFilePath, WordprocessingDocumentType.Document)) { // Add a main document part. MainDocumentPart mainPart = wordDocument.AddMainDocumentPart(); // Create the document structure and add some text. mainPart.Document = new Document(); Body body = mainPart.Document.AppendChild(new Body()); ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg); Paragraph para = body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); foreach (var user in users) { run.AppendChild(new Text("Id:")); run.AppendChild(new Text(user.Id.ToString())); run.AppendChild(new Text(" ")); run.AppendChild(new Text("My Name is: ")); run.AppendChild(new Text(user.Name.ToString())); run.AppendChild(new Text(" ")); run.AppendChild(new Text("My Email is: ")); run.AppendChild(new Text(user.Email.ToString())); run.AppendChild(new Text(" ")); run.AppendChild(new Break()); using (FileStream stream = new FileStream(studentsImagePath, FileMode.Open)) { imagePart.FeedData(stream); } Word.AddImageToBody(wordDocument, mainPart.GetIdOfPart(imagePart)); run.AppendChild(new Break() { Type = BreakValues.Page }); } } /*-----------------------------EXCEL DOCUMENT-------------------------------------------*/ string xlsxFilePath = $"{Constants.Locations.DataFolder}//info.xlsx"; // Create a spreadsheet document by supplying the filepath. // By default, AutoSave = true, Editable = true, and Type = xlsx. SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(xlsxFilePath, SpreadsheetDocumentType.Workbook); //Creating Excel Document Structure// // Add a WorkbookPart to the document. WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart(); workbookpart.Workbook = new Workbook(); // Add a WorksheetPart to the WorkbookPart. WorksheetPart worksheetPart = workbookpart.AddNewPart <WorksheetPart>(); worksheetPart.Worksheet = new Worksheet(new SheetData()); // Add Sheets to the Workbook. Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild <Sheets>(new Sheets()); SharedStringTablePart shareStringPart; shareStringPart = spreadsheetDocument.WorkbookPart.AddNewPart <SharedStringTablePart>(); WorksheetPart worksheetPart2 = workbookpart.AddNewPart <WorksheetPart>(); worksheetPart2.Worksheet = new Worksheet(new SheetData()); Sheet sheet = new Sheet() { Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart2), SheetId = 1, Name = "studentdata" }; sheets.Append(sheet); //Creating Heading Row string[] headingRow = { "UID", "StudentID", "FirstName", "LastName", "DateofBirth", "IsMe", "Age" }; char headingIndex = 'A'; for (int i = 0; i < headingRow.Count(); i++) { Excel.InsertCellInWorksheet(headingIndex.ToString(), 1, worksheetPart2).CellValue = new CellValue(Excel.InsertSharedStringItem(headingRow[i], shareStringPart).ToString()); Excel.InsertCellInWorksheet(headingIndex.ToString(), 1, worksheetPart2).DataType = new EnumValue <CellValues>(CellValues.SharedString); headingIndex++; } //Processing student Data uint rowIndex = 2; foreach (var student in students) { char columnIndex = 'A'; int uidIndex = Excel.InsertSharedStringItem(student.UID.ToString(), shareStringPart); Cell uidCell = Excel.InsertCellInWorksheet(columnIndex.ToString(), rowIndex, worksheetPart2); uidCell.CellValue = new CellValue(uidIndex.ToString()); uidCell.DataType = new EnumValue <CellValues>(CellValues.SharedString); columnIndex++; string ID = student.StudentId; int studentIdIndex = Excel.InsertSharedStringItem(ID, shareStringPart); Cell studentCell = Excel.InsertCellInWorksheet(columnIndex.ToString(), rowIndex, worksheetPart2); studentCell.CellValue = new CellValue(studentIdIndex.ToString()); studentCell.DataType = new EnumValue <CellValues>(CellValues.SharedString); columnIndex++; int firstIndex = Excel.InsertSharedStringItem(student.FirstName.ToString(), shareStringPart); Cell firstCell = Excel.InsertCellInWorksheet(columnIndex.ToString(), rowIndex, worksheetPart2); firstCell.CellValue = new CellValue(firstIndex.ToString()); firstCell.DataType = new EnumValue <CellValues>(CellValues.SharedString); columnIndex++; int Lastindex = Excel.InsertSharedStringItem(student.LastName.ToString(), shareStringPart); Cell LastCell = Excel.InsertCellInWorksheet(columnIndex.ToString(), rowIndex, worksheetPart2); LastCell.CellValue = new CellValue(Lastindex.ToString()); LastCell.DataType = new EnumValue <CellValues>(CellValues.SharedString); columnIndex++; int DOBIndex = Excel.InsertSharedStringItem(student.DateOfBirthDT.ToShortDateString(), shareStringPart); Cell DOBCell = Excel.InsertCellInWorksheet(columnIndex.ToString(), rowIndex, worksheetPart2); DOBCell.CellValue = new CellValue(DOBIndex.ToString()); DOBCell.DataType = new EnumValue <CellValues>(CellValues.SharedString); columnIndex++; int IsMeIndex = Excel.InsertSharedStringItem(student.IsMe.ToString(), shareStringPart); Cell IsMeCell = Excel.InsertCellInWorksheet(columnIndex.ToString(), rowIndex, worksheetPart2); IsMeCell.CellValue = new CellValue(IsMeIndex.ToString()); IsMeCell.DataType = new EnumValue <CellValues>(CellValues.SharedString); columnIndex++; int ageIndex = Excel.InsertSharedStringItem(student.Age.ToString(), shareStringPart); Cell ageCell = Excel.InsertCellInWorksheet(columnIndex.ToString(), rowIndex, worksheetPart2); ageCell.CellValue = new CellValue(ageIndex.ToString()); ageCell.DataType = new EnumValue <CellValues>(CellValues.SharedString); rowIndex++; } // Save and Close the document. workbookpart.Workbook.Save(); spreadsheetDocument.Close(); }