Quantcast
Channel: Open XML Format SDK forum
Viewing all 1288 articles
Browse latest View live

How to set vertical alignment and line folding for excel cell?

$
0
0
How to set vertical alignment and line folding for excel cell?

Create subtotal

$
0
0

Hi
I need create subtotal from DocumentFormat.OpenXml, any idea ?

thanks !


zambrano

Add HTML content with Image into header and footer in Open XML SDK 2.0

$
0
0

I facing issue with header and footer in docx using OpenXml SDK. Here I adding html content with image in both and header and footer. Its a dynamic header footer content so can't hard code into coding part.

Issue is that After adding content with image using lib NotesFor.HtmlToOpenXml.HtmlConverterin header and footer, the docx get generate successfully but header and footer image is broken. After googing found that header1.xml.relsis not generating.

Please help me how can I generate this file. 

Sample code

  public static void AddHeaderFooter(String documentPath)
        {
            // Replace header in target document with header of source document.
            using (WordprocessingDocument document = WordprocessingDocument.Open(documentPath, true))
            {
                // Get the main document part
                MainDocumentPart mainDocumentPart = document.MainDocumentPart;

                // Delete the existing header and footer parts
                mainDocumentPart.DeleteParts(mainDocumentPart.HeaderParts);
                mainDocumentPart.DeleteParts(mainDocumentPart.FooterParts);

                // Create a new header and footer part
                HeaderPart headerPart = mainDocumentPart.AddNewPart<HeaderPart>();
                FooterPart footerPart = mainDocumentPart.AddNewPart<FooterPart>();

                // Get Id of the headerPart and footer parts
                string headerPartId = mainDocumentPart.GetIdOfPart(headerPart);
                string footerPartId = mainDocumentPart.GetIdOfPart(footerPart);

                GenerateHeaderPartContent(headerPart, mainDocumentPart);

                GenerateFooterPartContent(footerPart, mainDocumentPart);

                // Get SectionProperties and Replace HeaderReference and FooterRefernce with new Id
                IEnumerable<SectionProperties> sections = mainDocumentPart.Document.Body.Elements<SectionProperties>();

                foreach (var section in sections)
                {
                    // Delete existing references to headers and footers
                    section.RemoveAllChildren<HeaderReference>();
                    section.RemoveAllChildren<FooterReference>();

                    // Create the new header and footer reference node
                    section.PrependChild<HeaderReference>(new HeaderReference() { Id = headerPartId });
                    section.PrependChild<FooterReference>(new FooterReference() { Id = footerPartId });
                    
                }

                wordprocessingDocument.MainDocumentPart.Document.Save();
                // Close the document.
                wordprocessingDocument.Close();

            }
        }


 public static void GenerateHeaderPartContent(HeaderPart part, MainDocumentPart mainDocumentPart)
        {
            Header header1 = new Header();
            var converter = new NotesFor.HtmlToOpenXml.HtmlConverter(mainDocumentPart);
            var paragraph = converter.Parse(@"<p><img src='http://localhost:62626/PPContent/40/Resources/HeaderFooter/HFk2FtngryxI_6f7ELxbjMCN_None_273182_80_DX546_DY546_CX273_CY182.jpg' style='width: 273px; height: 182px;' />header content</p>");
            header1.Append(paragraph);

            part.Header = header1;
        }

        public static void GenerateFooterPartContent(FooterPart part, MainDocumentPart mainDocumentPart)
        {
            Footer footer1 = new Footer();
            var converter = new NotesFor.HtmlToOpenXml.HtmlConverter(mainDocumentPart);
            var paragraph = converter.Parse(@"<p><img src='http://localhost:62626/PPContent/40/Resources/HeaderFooter/HFk2FtngryxI_6f7ELxbjMCN_None_273182_80_DX546_DY546_CX273_CY182.jpg' style='width: 273px; height: 182px;' />footer content</p>");
            footer1.Append(paragraph);
            part.Footer = footer1;
        }

Calculated dates values are not calculated on read but on save

$
0
0

I'm working on a system that reads excel sheets and parses it. Using a method like this:

            string strDoc = @"C:\Users\Public\Documents\Sheet11.xlsx";
            using (Stream stream = File.Open(strDoc, FileMode.Open))
             using (SpreadsheetDocument document = SpreadsheetDocument.Open(stream, false))
            {

                Workbook workBook = document.WorkbookPart.Workbook;
                IEnumerable<Sheet> workSheets = workBook.Descendants<Sheet>();
                SharedStringTable sharedStrings = document.WorkbookPart.SharedStringTablePart.SharedStringTable;

                var testCaseSheet = workSheets.First();
                var testCaseSheetID = testCaseSheet.Id;
                WorksheetPart testCasesSheet = (WorksheetPart)document.WorkbookPart.GetPartById(testCaseSheetID);
                var worksheet = testCasesSheet.Worksheet;

                IEnumerable<Row> dataRows =
                    from row in worksheet.Descendants<Row>()
                    //where row.RowIndex > 1
                    select row;

                foreach (Row row in dataRows)
                {
                    IEnumerable<Cell> cellValues =
                        from cell in row.Descendants<Cell>()
                        where cell.CellValue != null
                        select cell;

                    var list = cellValues.ToList();
                }
            }

The field that needs to be read is in this format:=TEXT(DATE(YEAR(TODAY())+30;MONTH(TODAY());DAY(TODAY()));"JJJJ-MM-DD"). As of today, this field which should produce 2050-12-18 instead produces (debugging the cellvalues) 2049-12-5

However - if I save this file this problem is fixed! As such, I go look into the save date which is (in retrospect not surprisingly) 2018-12-5.

I expected the formula to run when I read the file, is there any way to get the desired behaviour?


Not able to have a Content Control in which I can add line breaks

$
0
0

I am trying to insert some text at a Bookmark in document.

Here is my sequence.

1. Start a loop for a number of Questions.

2. Add Question Text with line break at beginning and end.

3. Add Content Control for Question, where users are supposed to enter Answer text.

All this works fine, but I can't hit enter in Content Control (I am not inserting plain text content control, but RichText control, so multiline = true doesn't apply).

Observation: If I remove lines for adding breaks before start and end , everything get inserted in same line. Now if I hit enter at the end of question text and bring all in new lines it works as expected. but I would want document to have line breaks when presented to end users.

Also If I put everything in a para as that's what happens after above mentioned steps in my code. then doc generated doesn't open at all. althrough document.xml I see doesn't have anything seemingly wrong in it.

Here is my code snippet.

static void Main(string[] args)
        {
            Console.WriteLine("Start");

            string base64String = "UEsDBBQABgAIAAAAIQDfpNJsWgEAACAFAAATAAgCW0NvbnRlbnRfVHlwZXNdLnhtbCCiBAIooAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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ECLQAUAAYACAAAACEAvdSNvycBAACPAgAAFAAAAAAAAAAAAAAAAAAZIwAAd29yZC93ZWJTZXR0aW5ncy54bWxQSwECLQAUAAYACAAAACEABfQCncQBAACLBQAAEgAAAAAAAAAAAAAAAAByJAAAd29yZC9mb250VGFibGUueG1sUEsBAi0AFAAGAAgAAAAhALc2ZClxAQAA7wIAABEAAAAAAAAAAAAAAAAAZiYAAGRvY1Byb3BzL2NvcmUueG1sUEsBAi0AFAAGAAgAAAAhAAbpHx9xAQAAxwIAABAAAAAAAAAAAAAAAAAADikAAGRvY1Byb3BzL2FwcC54bWxQSwUGAAAAAAsACwDBAgAAtSsAAAAA";

            string filePath;
            string fileName = "G1.docx";
            string currentPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

            filePath = currentPath + fileName;
            File.WriteAllBytes(filePath, Convert.FromBase64String(base64String));

            WordprocessingDocument wordDoc = WordprocessingDocument.Open(filePath, true);

            Body body = wordDoc.MainDocumentPart.Document.GetFirstChild<Body>();
            var bookmarkStart = body.Descendants<BookmarkStart>()
                                .Where(o => o.Name == "Questionnaire_Start")
                                .FirstOrDefault();

            var bmkParent = bookmarkStart.Parent;
            var rsidP = ((Paragraph)bmkParent).RsidParagraphProperties;
            for (int i = 0; i < 3; i++)
            {
                // 1 question para
                Text text = new Text(Environment.NewLine + "Question 123-" + i.ToString());
                Run run = new Run();

                run.Append(new Break());
                run.Append(text);
                run.Append(new Break());


                //Paragraph para = new Paragraph();
                //para.Append(run);
                //bmkParent.AppendChild(para);
                bmkParent.AppendChild(run);

                // 3 add content control
                // block and props

                //praragraph to be added to the rich text content control
                Run blockRun = new Run(new Text("Question 123-" + i.ToString()) { Space = SpaceProcessingModeValues.Preserve });
                //Paragraph blockParagraph = new Paragraph();
                //blockParagraph.RsidParagraphProperties = rsidP;

                SdtProperties sdtPr = new SdtProperties(
                        new SdtAlias { Val = i.ToString() },
                        new Tag { Val = i.ToString() } );
                SdtContentBlock sdtCBlock = new SdtContentBlock(blockRun);
                
                SdtBlock sdtBlock = new SdtBlock(sdtPr, sdtCBlock);

                //blockParagraph.Append(blockRun);
                bmkParent.AppendChild(sdtBlock);
                
                //wordDoc.MainDocumentPart.Document.Body.AppendChild(newLine);

            }

            wordDoc.Save();
            wordDoc.Close();

            Console.WriteLine("done");
        }

I have spent insane amount of time trying multiple permutation, combinations to achieve it, but somehow it doesn't work.

All help is greatly appreciated.

Ms Word Font issue

$
0
0

Hello.

I use Office 2016 , Hebrew version.

If I open XML file of document on part of runs I see 

<w:rFonts w:hint=“cs”/>

Itdisturbs me covert docx to html.

What does this mean?

How can I remove it  ?

Thn

Interested to split and merge Powerpoint Presentation

$
0
0

 

Hi,

      Can anybody help me in splitting a pptx file into individual pptx files having exaclty one slide in each file based on number of slides in source pptx. Then merge these files into a single pptx file. i.e.,

 

source pptx with 3 slides --- split---> (slide1.pptx, slide2.pptx, slide3.pptx) --- Merge ---> Destination pptx with 3 slides.

Open Xml not provide ahyp:hlinkClr tochange color of hyperlink.

$
0
0
Hi 
I need to change the color of a hyperlink in a presentation using documentformat.openxml in c# but openxml not provide ahyp:hlinkClr to change the color.

Please help.

kamaldeep


How to merge word documents with different headers using openxml?

$
0
0

I am trying to merge multiple documents into a single. I am using AltChunk altChunk = new AltChunk(). When documents are merged, it does not seem to retain seperate hearders of each document. The merged document will contain the headers of the first document during the merging. If the first document being merged contains no hearders, then all the rest of the newly merged document will contain no headers, and vise versa.

My question is, how can I preserve different headers of the documents being merged?

using System;
using System.IO;
using System.Linq;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

namespace WordMergeProject
{
    public class Program
    {
        private static void Main(string[] args)
        {
            byte[] word1 = File.ReadAllBytes(@"..\..\word1.docx");
            byte[] word2 = File.ReadAllBytes(@"..\..\word2.docx");

            byte[] result = Merge(word1, word2);

            File.WriteAllBytes(@"..\..\word3.docx", result);
        }

        private static byte[] Merge(byte[] dest, byte[] src)
        {
            string altChunkId = "AltChunkId" + DateTime.Now.Ticks.ToString();

            var memoryStreamDest = new MemoryStream();
            memoryStreamDest.Write(dest, 0, dest.Length);
            memoryStreamDest.Seek(0, SeekOrigin.Begin);
            var memoryStreamSrc = new MemoryStream(src);

            using (WordprocessingDocument doc = WordprocessingDocument.Open(memoryStreamDest, true))
            {
                MainDocumentPart mainPart = doc.MainDocumentPart;
                AlternativeFormatImportPart altPart =
                    mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId);
                altPart.FeedData(memoryStreamSrc);
                var altChunk = new AltChunk();
                altChunk.Id = altChunkId;
                              OpenXmlElement lastElem = mainPart.Document.Body.Elements<AltChunk>().LastOrDefault();
            if(lastElem == null)
            {
                lastElem = mainPart.Document.Body.Elements<Paragraph>().Last();
            }


            //Page Brake einfügen
            Paragraph pageBreakP = new Paragraph();
            Run pageBreakR = new Run();
            Break pageBreakBr = new Break() { Type = BreakValues.Page };

            pageBreakP.Append(pageBreakR);
            pageBreakR.Append(pageBreakBr);                

            return memoryStreamDest.ToArray();
        }
    }
}

Using Content control to print MSSQL Table

$
0
0

I want to print a table from the database and print on some content control on an MS word document.

I am very new to using content control to print out tables from a Database, Can i use SdtElement?

My code looks like this (Although I never used the SdtElement) I just need to be clear on some few things 

Code looks like this :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

namespace TablePrintExample
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            PrintTablesFromDB();
        }

        public static void AddTable(string fileName, string[,] data)
        {
            using (var document = WordprocessingDocument.Open(fileName, true))
            {
                var doc = document.MainDocumentPart.Document;
                DocumentFormat.OpenXml.Wordprocessing.Table table = new DocumentFormat.OpenXml.Wordprocessing.Table();
                TableProperties props = new TableProperties(
                    new TableBorders(
                        new TopBorder { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 6 },
                        new BottomBorder { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 6 },
                        new LeftBorder { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 6 },
                        new RightBorder { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 6 },
                        new InsideHorizontalBorder { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 6 },
                        new InsideVerticalBorder { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 6 }
                    ));
                table.ClearAllAttributes();
                table.AppendChild<TableProperties>(props);
                for (var i = 0; i <= data.GetUpperBound(0); i++)
                {
                    var tr = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
                    for (var j = 0; j <= data.GetUpperBound(1); j++)
                    {
                        var tc = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
                        string[] datas = data[i, j].ToString().Split('\n');
                        for (int k = 0; k < datas.Length; k++)
                        {
                            tc.Append(new Paragraph(new Run(new Text(datas[k]))));
                            tc.Append(new TableCellProperties(new TableCellVerticalAlignment { Val = TableVerticalAlignmentValues.Center }));
                        }
                        //tc.Append(new TableCellProperties(new TableCellWidth { Type = TableWidthUnitValues.Auto }));
                        tr.Append(tc);
                    }
                    table.Append(tr);
                }
                doc.Body.Append(table);
                doc.Save();
            }
        }

        private void PrintTablesFromDB()
        {
            string constring = @"Data Source=DLX;Initial Catalog=K2;Integrated Security=True";
            using (SqlConnection con = new SqlConnection(constring))
            {
                con.Open();
                string query = "select * from [EmployeeInfoDB].[dbo].[EmpDbTable]";
                using (SqlDataAdapter da = new SqlDataAdapter(query, con))
                {
                    try
                    {
                        DataTable dt = new DataTable();
                        da.Fill(dt);
                        foreach (DataRow row in dt.Rows)
                        {
                            dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Employee Name"), new DataColumn("Desg") });
                            string col1 = dt.Rows[0]["EmployeeName"].ToString();
                            string col2 = dt.Rows[0]["Designation"].ToString();
                            string[,] Tablero = new string[1, 2] { { col1, col2 } };
                            AddTable(@"C:\Users\Administrator\Desktop\TableTest.docx", Tablero);
                            Process.Start(@"C:\Users\Administrator\Desktop\TableTest.docx");
                        }
                    }
                    catch(Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                }
            }
        }
    }
}

How can I do something like this??

List c# Openxml how to print Table on content control

$
0
0
I am trying to print a table to a Content control from a Database (MSSQL), the webservice is supposed to fetch some records and put it to a content control in the form of a table using List. 


So I do something like this 

public bool PrintTableonContentControl(string connectionString, string DbQuery,string filePath, string placeholderText)
{
	try{
		DataTable dt = new DataTable();
	using(SqlConnection con = new SqlConnection(connectionString)){
		con.Open();
	using(SqlCommand cmd = new SqlCommand(DbQuery,con)){
		using(SqlDataAdapter da = new SqlDataAdapter(cmd)){
			da.Fill(dt);
		using(WordprocessingDocument theDoc = WordprocessingDocument.Open(filePath, true)){
			MainDocumentPart mainPart = theDoc.MainDocumentPart;
			List<SdtBlock> sdtSubTable = mainPart.Document.Body.Descendants<SdtBlock>().Where(r => r.SdtProperties.GetFirstChild<Tag>().Val.Value.Contains(placeholderText)).ToList();
			// Here it should print the Table on the content control and save 
				}
			}
		}
	}
	}
	catch(Exception ex)
	{
	     throw ex;
	}
	return true;
}



Normally, I know how to use the simple Text and have the text displayed on a Content control, but tables? I have not seen any useful documentation on that, Please I would be needing help in this case.

Copying powerpoint presentation to Sharepoint-Online corrupts customXML Data

$
0
0

Hello,

Our company develops and distributes a Powerpoint Add-In.

We received a Powerpoint Presentation from our customer from his Sharepoint online server and wanted to place it with our Powerpoint AddIn on our SharePoint Online server. The AddIn adds some customXmls to the presentation and to the slides to a local copy of the presentation and finally using a simple File.Copy command it copies the presentation to a Sharepoint folder which is accessed by webDAV.

When I try to open the presentation file from Sharepoint with the "Open XML SDK 2.5 Productivity Tool For Microsoft Office" it shows the message: "Cannot open file: The file contains corrupt data.
The depending source presentation file (i.e. the local copy) can be opened with the productivity tool without any problems.
Both presentation can be opened with Powerpoint without any problems

That's confusing me: When I open and save the presentation with Powerpoint once the file was manipulated and saved by OpenXml SDK, I had no problem copying the presentation to the sharepoint. The file was not corrupted!

What' s the difference between the two versions of the presentation: one saved by OpenXml SDK, the other one by Powerpoint?

Sure, obviously the reference ids are renumbered, but that did not make any problems until now. There must be another difference, which corrupts the presentation saved by the OpenXmlSDK.

About help or even just an idea, which triggers this error, I would be very happy. For analysis, I can provide sample files.

Also a tip for a better analysis tool is very welcome ...

Thank you for your help,
Karl

Word found unreadable content in xxx.docx after split a docx using openxml

$
0
0

I have a full.docx which includes two math questions, the docx embeds some pictures and MathType equation (oleobject), I split the doc according to this, get two files (first.docx, second.docx) , first.docx works fine, the second.docx, however, pops up a warning dialog when I try to open it:

"Word found unreadable content in second.docx. Do you want to recover the contents of this document? If you trust the source of this document, click Yes."

After click "Yes", the doc can be opened, the content is also correct, I want to know what is wrong with the second.docx? I have checked it with "Open xml sdk 2.5 productivity tool", but found no reason. Very appreciated for any help. Thanks.

Some code:

        byte[] templateBytes = System.IO.File.ReadAllBytes(TEMPLATE_YANG_FILE);
        using (MemoryStream templateStream = new MemoryStream())
        {
            templateStream.Write(templateBytes, 0, (int)templateBytes.Length);

            string guidStr = Guid.NewGuid().ToString();

            using (WordprocessingDocument document = WordprocessingDocument.Open(templateStream, true))
            {
                document.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document);

                MainDocumentPart mainPart = document.MainDocumentPart;

                mainPart.Document = new Document();
                Body bd = new Body();

                foreach (DocumentFormat.OpenXml.Wordprocessing.Paragraph clonedParagrph in lst)
                {
                    bd.AppendChild<DocumentFormat.OpenXml.Wordprocessing.Paragraph>(clonedParagrph);

                    clonedParagrph.Descendants<Blip>().ToList().ForEach(blip =>
                    {
                        var newRelation = document.CopyImage(blip.Embed, this.wordDocument);
                        blip.Embed = newRelation;
                    });

                    clonedParagrph.Descendants<DocumentFormat.OpenXml.Vml.ImageData>().ToList().ForEach(imageData =>
                    {
                        var newRelation = document.CopyImage(imageData.RelationshipId, this.wordDocument);
                        imageData.RelationshipId = newRelation;
                    });
                }

                mainPart.Document.Body = bd;
                mainPart.Document.Save();
            }

            string subDocFile = System.IO.Path.Combine(this.outDir, guidStr + ".docx");
            this.subWordFileLst.Add(subDocFile);

            File.WriteAllBytes(subDocFile, templateStream.ToArray());
        }

the lst contains Paragraph cloned from original docx using:

(DocumentFormat.OpenXml.Wordprocessing.Paragraph)p.Clone();

The three files have been uploaded to here.



OpenXMLSDK: Draw Scribble shape in Doc

$
0
0

I need to draw Scribble shape in Word doc using Open-Xml in my UWP project. I've searched a lot about this but couldn't find anything. I've also checked MSDN Site.

I'm using OS: Windows 10, OpenXMLSDK 2.10

I've also I've installed Open XML SDK 2.5 Tool and try to generate code by loading word doc file. But when try to open docx, a popup window appear with message : "Can not open the file: File contains corrupted data.".

Help Needed


RTF inside WordProcessing.Paragraph

$
0
0

Hi,

We have a program which takes .docx-files and replaces certain texts (eg. 'something1') with certain replacement values.

Everything goes well when we replace these texts with normal text, but sometimes we want to replace them with RTF-formatted texts. We would do this with AltChunk. When we try to replace these texts, which are inside a Text-element (<w:t>), which are inside a Run-element (<w:r>), which are inside a Paragraph-element (<w:p>), this isn't very reliable (which is to be expected seen the documentation about OpenXML), because sometimes there is some text in the same paragraph after the texts we wish to replace (which would be replaced with an RTF-text using AltChunk). Now our only option is to cut-off the paragraph, insert the RTF at the cut-off, and recommence the rest of our previous paragraph on a new paragraph. Then we would later have to merge the cut-off paragraphs back together, when de AltChunks are applied in the document.

Is there any way (not using Interop) to insert some RTF-text inside the middle of a paragraph in OpenXML?

Thanks in advance!

Renaud Leroy


COPY DOCUMENT AT END OF OTHER DOCUMENT

$
0
0

I am copying one document at end of other document.

I have written all code including coping styles and other data.

In one case line spacing is not getting copied from source document.

The paragraphs which I am copying don't have line spacing defined so paragraphs must be using line spacing from some where else (document default?)

In main document where I copy paragraph I also copied style from source still line spacing is not coming.

Where line spacing is stored apart from paragraph, how paragraph refers this line spacing?

The copied paragraph currently uses line spacing of last paragraph in main document.

Best regards,

Dhanraj

Need sample examples on applying the font and color to the excel cell with using DocumentFormat.OpenXml

$
0
0

Dear all,

I have a requirement to apply the font and color to the excel cells in a row using DocumentFormat.OpenXml and have to do it programatically. I would like to have sample code examples or article(s) with regards to this. Please share your ideas and information. I appreciate your help and support. Thank you so much!


Narayana Reddy G

Copy Header code sample not working.

$
0
0

Hi,

I am trying to add a header to a word document as per code samples on MSDN.

https://docs.microsoft.com/en-us/office/open-xml/how-to-replace-the-header-in-a-word-processing-document

I am getting following error after adding the header to the document.

Word found unreadable content in documentTest1.docx.

Also, if i select yes to recover doc, the header content is not loading correctly as per original header.

Getting message picture cant be displayed.



Is this something wrong with the code sample or a bug in the SDK?

I am using "Microsoft Open XML SDK 2.5".

Kindly, help.

Thanks,

Sachin R. Chavan.


Sachin R. Chavan.

how to retain different styles in different documents during merging?

$
0
0

I am merging multiple documents using the following code snippet.

However, it is messing around with the styling. First document has a numbered list style and the second document has a bullet list style. But when they merged, the second document's style "bulleted list" gets overridden by the numbered list from first document. How can I retain different styles for different documents being merged?

using System;
using System.IO;
using System.Linq;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

namespace WordMergeProject
{
    public class Program
    {
        private static void Main(string[] args)
        {
            byte[] word1 = File.ReadAllBytes(@"..\..\word1.docx");
            byte[] word2 = File.ReadAllBytes(@"..\..\word2.docx");

            byte[] result = Merge(word1, word2);

            File.WriteAllBytes(@"..\..\word3.docx", result);
        }

        private static byte[] Merge(byte[] dest, byte[] src)
        {
            string altChunkId = "AltChunkId" + DateTime.Now.Ticks.ToString();

            var memoryStreamDest = new MemoryStream();
            memoryStreamDest.Write(dest, 0, dest.Length);
            memoryStreamDest.Seek(0, SeekOrigin.Begin);
            var memoryStreamSrc = new MemoryStream(src);

            using (WordprocessingDocument doc = WordprocessingDocument.Open(memoryStreamDest, true))
            {
                MainDocumentPart mainPart = doc.MainDocumentPart;
                AlternativeFormatImportPart altPart =
                    mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId);
                altPart.FeedData(memoryStreamSrc);
                var altChunk = new AltChunk();
                altChunk.Id = altChunkId;
                              OpenXmlElement lastElem = mainPart.Document.Body.Elements<AltChunk>().LastOrDefault();
            if(lastElem == null)
            {
                lastElem = mainPart.Document.Body.Elements<Paragraph>().Last();
            }


            //Page Brake einfügen
            Paragraph pageBreakP = new Paragraph();
            Run pageBreakR = new Run();
            Break pageBreakBr = new Break() { Type = BreakValues.Page };

            pageBreakP.Append(pageBreakR);
            pageBreakR.Append(pageBreakBr);                

            return memoryStreamDest.ToArray();
        }
    }
}


How to apply Percentage format to the excel cell with DocumentFormat.OpenXml

$
0
0
Dear all,
I have a requirement to apply Percentage Format to the excel cell and also I have to apply other styling like bold and border to the same excel cell. I have to make use of DocumentFormat.OpenXml and achieve it by programming. So, I would like to have sample code examples or article(s) to achieve this functionality. Please share your ideas and information. I would appreciate your help and support. Thank you so much!

Narayana Reddy G

Viewing all 1288 articles
Browse latest View live