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

Number in this cell is formatted as text or preceded by apostrophe-Excel

$
0
0

Hi,

I had apply number format with decimal as below for cells, getting the error "Number in this cell is formatted as text or preceded by apostrophe"  and number does not have decimal point. When i see the format cells(right click on the cell) in excel by manually, style format applied correctly.Could you please some one advise on this.

Number format:

NumberingFormats numberingFormats1 = new NumberingFormats() { Count = (UInt32Value)2U };
            NumberingFormat numberingFormat1 = new NumberingFormat() { NumberFormatId = (UInt32Value)164U, FormatCode = "###,###,###,###,###,###,###,##0.00" };
            NumberingFormat numberingFormat2 = new NumberingFormat() { NumberFormatId = (UInt32Value)165U, FormatCode = "###,###,###,###,###,##0.0000000000" };

            numberingFormats1.Append(numberingFormat1);
            numberingFormats1.Append(numberingFormat2);



Shared String is missing in excel

$
0
0

Hi,

I have generated the excel in DFT task(SSIS) and it has text and numeric fields. After generated the excel, i have to apply the style format for that excel using Openxml. When i apply number format for the numeric field, the datatype say its inlinestring. When i lookup the shared string for the excel cell  nothing found and it returns null.I am using below code to check the datatype and value.Could you please some one advise why it does not have shared string for the excel cell/workbook. Please note that if i open the excel by manually and save it with out making any changes, after that i could see shared string for the excel work book. its confusing me.

publicstaticstring ChangeTextCellToNumber(string fileName,

           string sheetName,

           string addressName)

        {

           string value =null;

 

           // Open the spreadsheet document for read-only access.

           using (SpreadsheetDocument document =

                SpreadsheetDocument.Open(fileName,true))

            {

                

                // Retrieve a reference to the workbook part.

                WorkbookPart wbPart = document.WorkbookPart;

                Sheet theSheet = wbPart.Workbook.Descendants<Sheet>().

                  Where(s => s.Name == sheetName).FirstOrDefault();

 

               // Throw an exception if there is no sheet.

               if (theSheet ==null)

                {

                   thrownew ArgumentException("sheetName");

                }

 

               // Retrieve a reference to the worksheet part.

                WorksheetPart wsPart =

                    (WorksheetPart)(wbPart.GetPartById(theSheet.Id));

 

                Cell theCell = wsPart.Worksheet.Descendants<Cell>().

                  Where(c => c.CellReference == addressName).FirstOrDefault();

               if (theCell.InnerText.Length > 0)

                {

                    value = theCell.InnerText;

 

                   if (theCell.DataType !=null)

                    {

                       switch (theCell.DataType.Value)

                        {

                           case CellValues.InlineString:

 

                               // For shared strings, look up the value in the

                               // shared strings table.

                               var stringTable =

                                    wbPart.GetPartsOfType<SharedStringTablePart>()

                                    .FirstOrDefault();

                               if (stringTable !=null)

                                {

                                   value =

                                        stringTable.SharedStringTable

                                        .ElementAt(int.Parse(value)).InnerText;

                                   // Convert to number

                                    theCell.CellValue = new CellValue(value);

                                    theCell.DataType = new EnumValue<CellValues>(CellValues.Number);

                                   

                                    wsPart.Worksheet.Save();

                                }

                               break;

 

                           case CellValues.Boolean:

                               switch (value)

                                {

                                    case"0":

                                        value = "FALSE";

                                       break;

                                   default:

                                        value = "TRUE";

                                       break;

                                }

                               break;

                        }

                    }

                }

            }

           return value;

        }

Deleting PowerPoint Section

$
0
0

Hello,

How can I delete PowerPoint sections using only OpenXML? PowerPoint sections are the section titles with a small drop-down arrow that separate slides in the slides list. For instance, if I wanted to delete a section titled "Welcome", how would I do so?

Thank you!

C# Excel get data from all Tables in Workbook

$
0
0

I have spent several hours already trying to do this and don't seem to be able to find any information elsewhere on the web

I want to: Find all Tables within a given Excel Workbook and extract this data using C# and Open XML. 

If someone can point me to some code, or a wrapper library, that can do this please. 

Ideally the end result would be a collection of DataTables but if someone can show me how to get a list of the Tables and how to get at the data they reference that would be wonderful


using openxml writer to set up the width of the columns in excel

$
0
0

Hello

I am currently using the below example to write my excel file (my excel file has a lot of records).

I want to ask how I can use openxml writer to set up the width of the columns?

Here is the sample code.  can someone provide the solution of how to do it?

I tried to create columns class in between worksheet and sheetdata, but i have trouble create excel file.

Appreciate it! thanks.

using (SpreadsheetDocument xl = SpreadsheetDocument.Create("LargeFile.xlsx", SpreadsheetDocumentType.Workbook))
{
    List<OpenXmlAttribute> oxa;
    OpenXmlWriter oxw;

    xl.AddWorkbookPart();
    WorksheetPart wsp = xl.WorkbookPart.AddNewPart<WorksheetPart>();

    oxw = OpenXmlWriter.Create(wsp);
    oxw.WriteStartElement(new Worksheet());
    oxw.WriteStartElement(new SheetData());

    for (int i = 1; i <= 50000; ++i)
    {
        oxa = new List<OpenXmlAttribute>();
        // this is the row index
        oxa.Add(new OpenXmlAttribute("r", null, i.ToString()));

        oxw.WriteStartElement(new Row(), oxa);

        for (int j = 1; j <= 100; ++j)
        {
            oxa = new List<OpenXmlAttribute>();
            // this is the data type ("t"), with CellValues.String ("str")
            oxa.Add(new OpenXmlAttribute("t", null, "str"));

            // it's suggested you also have the cell reference, but
            // you'll have to calculate the correct cell reference yourself.
            // Here's an example:
            //oxa.Add(new OpenXmlAttribute("r", null, "A1"));

            oxw.WriteStartElement(new Cell(), oxa);

            oxw.WriteElement(new CellValue(string.Format("R{0}C{1}", i, j)));

            // this is for Cell
            oxw.WriteEndElement();
        }

        // this is for Row
        oxw.WriteEndElement();
    }

    // this is for SheetData
    oxw.WriteEndElement();
    // this is for Worksheet
    oxw.WriteEndElement();
    oxw.Close();

    oxw = OpenXmlWriter.Create(xl.WorkbookPart);
    oxw.WriteStartElement(new Workbook());
    oxw.WriteStartElement(new Sheets());

    // you can use object initialisers like this only when the properties
    // are actual properties. SDK classes sometimes have property-like properties
    // but are actually classes. For example, the Cell class has the CellValue
    // "property" but is actually a child class internally.
    // If the properties correspond to actual XML attributes, then you're fine.
    oxw.WriteElement(new Sheet()
    {
        Name = "Sheet1",
        SheetId = 1,
        Id = xl.WorkbookPart.GetIdOfPart(wsp)
    });

    // this is for Sheets
    oxw.WriteEndElement();
    // this is for Workbook
    oxw.WriteEndElement();
    oxw.Close();

    xl.Close();
}


Insert a Picture into the Picture/Image Content Control using Open XML SDK 2.0

$
0
0

I have created a word template as follows

Here PizzaPicture is a Picture Content Control, PizzaName is a Plain Text Content Control and PizzaDescription is a Rich Text Content Control

 

I am able to assign text to PizzaName and PizzaDescription Easily but not able to even locate the PizzaPicture. Here is my code

 

using (WordprocessingDocument document = WordprocessingDocument.Open(@".\test.docx", true)) {
                MainDocumentPart mainPart = document.MainDocumentPart;
                DocumentFormat.OpenXml.Wordprocessing.Text text = null;
                SdtContentBlock pizzaNameBlock = null;  
                SdtContentBlock pizzaDescriptionBlock = null;  //SdtContentBlock pizzaPictureBlock = null;  

                List<SdtBlock> sdtList = mainPart.Document.Descendants<SdtBlock>().ToList();foreach (SdtBlock sdt in sdtList)
                {
                    Console.WriteLine(sdt.SdtProperties.GetFirstChild<Tag>().Val.Value);
                }

                SdtBlock s1 = mainPart.Document.Body.Descendants<SdtBlock>().Where(r => r.SdtProperties.GetFirstChild<Tag>().Val == "PizzaName").Single();
                SdtBlock s2 = mainPart.Document.Body.Descendants<SdtBlock>().Where(r => r.SdtProperties.GetFirstChild<Tag>().Val == "PizzaDescription").Single();
                SdtBlock s3 = mainPart.Document.Body.Descendants<SdtBlock>().FirstOrDefault(r =>
                {
                    SdtProperties p = r.Elements<SdtProperties>().FirstOrDefault();if (p != null)
                    {
                        Console.WriteLine("P is not null");// Is it a picture content control?
                        SdtContentPicture pict =
                            p.Elements<SdtContentPicture>().FirstOrDefault();if (pict != null) Console.WriteLine("Pict is not null");// Get the alias.
                        SdtAlias a = p.Elements<SdtAlias>().FirstOrDefault();if (pict != null&& a.Val == "PizzaPicture")returntrue;
                    }returnfalse;
                });if (s3 == null) {
                    Console.Write(" s3 is Null");
                } else { 
                    Console.WriteLine("s3 not null");
                }if (s1 != null) {
                    pizzaNameBlock = s1.Descendants<SdtContentBlock>().FirstOrDefault();
                    text = pizzaNameBlock.Descendants<DocumentFormat.OpenXml.Wordprocessing.Text>().FirstOrDefault();// here you can set the current time
                    text.Text = "Peperoni";
                    Console.WriteLine(text.Text);
                }string embed = null;if (s3 != null)
                {
                    Drawing dr = s3.Descendants<Drawing>().FirstOrDefault();if (dr != null)
                    {
                        Blip blip = dr.Descendants<Blip>().FirstOrDefault();if (blip != null)
                            embed = blip.Embed;
                    }
                }if (embed != null)
                {
                    IdPartPair idpp = document.MainDocumentPart.Parts
                        .Where(pa => pa.RelationshipId == embed).FirstOrDefault();if (idpp != null)
                    {
                        ImagePart ip = (ImagePart)idpp.OpenXmlPart;using (FileStream fileStream =
                            File.Open(@"c:\temp\pepperoni.jpg", FileMode.Open))
                            ip.FeedData(fileStream);                        
                    }
                }if (s2 != null) {
                    pizzaDescriptionBlock = s2.Descendants<SdtContentBlock>().FirstOrDefault();string altChunkId = "AltChunkId12345";
                    AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Xhtml, altChunkId);
                    chunk.FeedData(File.Open(@".\html.txt", FileMode.Open));
                    AltChunk altChunk = new AltChunk();
                    altChunk.Id = altChunkId;////Replace content control with altChunk information                
                    OpenXmlElement parent = pizzaDescriptionBlock.Parent;
                    parent.InsertAfter(altChunk, pizzaDescriptionBlock);
                    pizzaDescriptionBlock.Remove();
                }

                mainPart.Document.Save();
                document.Close();
            }


Here the call mainPart.Document.Descendants<SdtBlock>().ToList(); returns me only 2 items PizzaName, PizzaDescription butno PizzaPicture.

 

Secondly the line   SdtContentPicture pict =  p.Elements<SdtContentPicture>().FirstOrDefault();returns NULL. So it seems that there is no element of type SdtContentPicture.

What am I doing wrong? I am pretty sure that I have put PizzaPicture as a Picture content control.

 

My objective is to locate this control in the document and then insert an image into it programmatically.

 

 


MSDNStudent Knows not much!

Word Open XML - Adding a new element

$
0
0

I have a content control like this

SdtBlock xSdtBlock = (SdtBlock)contentcontrol;
SdtProperties sdrprops = xSdtBlock.Descendants<SdtProperties>().FirstOrDefault();

How do I add an element inside of that? The element I want to add is 

     <w15:appearance w15:val="hidden"/>

so that the xml block looks like

    <w:sdtPr>
     <w:rPr>
      <w:lang w:val="en-GB"/>
     </w:rPr>
     <w:alias w:val="TitleTest"/>
     <w:tag w:val="TagTest"/>
     <w:id w:val="1500618722"/>
     <w:temporary/>
     <w:showingPlcHdr/>
     <w15:appearance w15:val="hidden"/>
     <w:picture/>
    </w:sdtPr>

instead of current

      

    <w:sdtPr>
     <w:rPr>
      <w:lang w:val="en-GB"/>
     </w:rPr>
     <w:alias w:val="TitleTest"/>
     <w:tag w:val="TagiTest"/>
     <w:id w:val="1500618722"/>
     <w:temporary/>
     <w:showingPlcHdr/>
     <w:picture/>
    </w:sdtPr>

I'm trying to accomplish the same that what can be done in Word by setting content control properties "Show as" to "None" instead of "Bounding Box" so that the placeholder image wouldn't be displayed anymore.

How to get content under sections of the document using open xml sdk c#

$
0
0

hi all,

i am new to using open xml sdk. we have a requirement to lift a content from one section of a document to another. i have not seen an example of doing this. any sample or example would be of great help.

eg: copy section 1 of doc1.docz to section 1 of doc2.docx


Creating multple paragrahs in Microsoft 365 Word docs

$
0
0

Hi

I want try out creating a word document in say an Azure function. 

Looking at the docs:

https://docs.microsoft.com/en-us/office/open-xml/how-to-open-and-add-text-to-a-word-processing-document

It seems that the number of paragraphs I want to add must match the <w:t> elements in WordProcessingML template .

<w:document xmlns:w="https://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p><w:r><w:t>Example text.</w:t></w:r></w:p></w:body></w:document>
  1. Has anybody done this recently with the latest versions of Word - was it stable?
  2. Are there any examples of the templates anywhere?
  3. Is there limit to amount of text per paragraph?
  4. Is the way to add headings prior to each paragraph?


Collaboration Solutions Architect

What's the fastest way to read a .docx file line-by-line in c#

$
0
0

Hello there,

After upload I want to read a .docx file line by line.

This is my file.docx and is divided for chapters and paragraphs of the chapter

The structure of file.docx

Chapter 1 - Events
alert or disservices
significant activities
Chapter 2 – Safety near miss security checks
Chapter 3 – Training environment upkeep

I need read a .docx file line by line and according to the chapter I have to insert chapter and content of the paragraph in the corresponding database table

e.g.

Chapter 1 - Events
 - alert or disservices
Lorem ipsum dolor sit amet, consectetur adipiscing elit ….
…. ….
…. ….
- significant activities
Phasellus dui nunc, rutrum vitae dictum eleifend, ullamcorper hendrerit sem ….
…. ….
…. ….

must be inserted in the table Events

-- ----------------------------
-- Table structure for events
-- ----------------------------
DROP TABLE IF EXISTS `events`;
CREATE TABLE `events` (
  `sID` int(11) NOT NULL AUTO_INCREMENT,
  `alert_or_disservices` longtext,
  `significant_activities` longtext,
  PRIMARY KEY (`sID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

I wanted how to do it as efficiently as possible within the .NET C# OpenXML scope of things.

Do you have any example of OpenXML for my case?

Please can you help me?

Thanks in advance for any help or suggestion

Sincerely

Chevy


Failed to update PPtx chart data use open xml power tools

$
0
0
Using the updatechart example of openxml power tools, when I want to use the specified chartpart, I need to use ChartSpace to get the chart title. But when I define ChartSpace, the updatechart example has a problem. The updated data needs to be opened to update the excel sheet, otherwise the updated data will not be displayed. Or there are other ways to update the embedded chart data,I hope to get help, thank you.

Bookmark in Word buildingblocks disappear in Open XML Glossary part of a template

$
0
0
Hi

We have a Word template file with some predefined header and footer parts saved as building blocks in the template.
When we use this template in our Word Add In application it behaves as expected.
But if we try to use the building blocks on our Open XML service, some of the bookmarks ar missing.

After some digging around in the templaqte we found that Word does not handle the content och the building block correctly in the resulting XML file.
Using Open XML Productivity Tool , we found that the in Glossary part of the document some of our bookmarks is missing.
When we open the same file in word and insert the building block, the bookmark is there as expected.

Why is this? It is very frustrating nad we have tried replacing the faulty parts in avery possible way but without success.

What is wrong here?

Regards
Peter Karlström

Best Regards Peter Karlström Midrange AB, Sweden

How to programmatically add a text to PowerPoint using OpenXML

$
0
0

I am attempting to use Document.Format.OpenXML 2.0 and I have yet to find a way to programmatically add a simple textbox object to the presentation.  Can anyone provide a solution?  I have found there is a method to add an image (AddImagePart()), so why isn't there an AddTextBoxPart()?

How to Range.ListFormat.ConvertNumbersToText() using OpenXML SDK?

$
0
0
Is there any option to Range.ListFormat.ConvertNumbersToText() using OpenXML SDK without using word interop.

Selvam S

OpenXml manipulate bulleted word document

$
0
0

I have an existing bulleted line in a word document like this:

- Condition1

I would like to add text on the next line with the same bullet like so:

- Condition1

- Condition2 etc.

I am currently using C# and have a line such as the text below but don't know where to go from here - I have tried ParagraphProperties.CloneNode() but without success. 

run.AppendChild(new Text("Condition2");
run.AppendChild(new Break());

which gives me this:

- Condition1

Condition2 (without the (-) bullet)

Any help would be appreciated.


OpenXML SpreadsheetDocument Header and Footer

$
0
0

I am able to edit the document with OpenXML WordprocessingDocument and remove then add back the header and footer with the updated company information.

I am trying to do the same for OpenXML SpreadsheetDocument, but I can't figure out how to remove/delete the existing header and footer. I see the DeletePart as part of the OpenXmlPartContainer which is part of OpenXmlPart : OpenXmlPartContainer. The spreadsheets have header and footers, but I don't see how to access them.

OpenXml SDK- How to uniquely identify a paragraph in a word document

$
0
0

I need to extract paragraphs based on some unique ids or something that can identify/differentiate each paragraph in a 50- 60 pages word document (using TX Text Editor to load it) . I will tag these unique IDs to a list box or some other list control and on-click of the list box item, go to that specific paragraph and highlight it. I thought w:paraID is unique but it is null and not for development purpose. There should be some custom hack where in i can add something.

Right now i convert the TxText Editor loaded content to docx -> wordprocessingML and trying to figure out how to extract certain paragraphs using some unique ids or style. The Content of the Paragraph will not be known, only some mapping between the listitem and Docx will be there to highlight the entire paragraph.

Regards, Jasbir

Tutorials for Open XML

$
0
0
I'm interesting in learning more about Open XML. But examining the XML files of a sample Word documents I created, I find Open XML to be pretty intimidating. Are there any good tutorials? I'm think not really because I've been searching and can only find small articles at best. But I thought I'd ask before giving up. Thanks.

OpenXML not able to get the actual formula text for few cells

$
0
0

We are using openxml nuget package DocumentFormat.OpenXml to read excel cell values. Our requirement is to read the actual formula text from a cell using "cell.CellFormula" property,but for few of the cells we are getting the actual value instead of formula.

Ex:Say the cell(A10) has the formula : =A5+1 AND A5 has value of "2".

our intention is to read the formula in A10 which is "=A5+1" but instead we are getting the value as "2"

  using (var document = SpreadsheetDocument.Open(filePath, false))
            {
                var workbookPart = document.WorkbookPart;
                var workbook = workbookPart.Workbook;
                var sheets = workbook.Descendants<Sheet>();
                foreach (var sheet in sheets)
                {
                    var worksheetPart = (WorksheetPart)workbookPart.GetPartById(sheet.Id);
                    var cells = worksheetPart.Worksheet.Descendants<Cell>();
                    foreach (var cell in cells)
                    {
                            if (cell.CellFormula != null || cell.CellValue != null || cell.DataType != null)
                            {
                                string cellFormula=cell.CellFormula;

                            }
                    }

                }

            }


.Net Winforms Manipulate Word Document “Page number”

$
0
0

Main Question: How do I use OpenXML via c# to change a word document page number?

End Goal: Manipulate Word Document to change its page number.

What I have tried/where I have looked: I have looked at the documentation on Microsoft website and am having a hard time navigating it properly (USER ERROR) so if anyone can give me a better guide it would be much appreciated.

Viewing all 1288 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>