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

How to split text box columns via APIs?

$
0
0

Hi,

I used OpenXml SDK to create text box and add texts in the box. There is the case that the added texts run over the size of the text box and even the size of the page. Is there any API to split the text box column to 2 or 3? This can be done manually in PowerPoint. Can we do it programmatically?

Thanks in advance!!!


How to insert a scroll Bar in a spreadsheet by code behind c# using Open XML Format SDK ?

$
0
0

I need to implement a scrollbar in an excel by linking it into a cell, is it possible to do it with Open XML Format SDK, if it possible , could you please help me on this by posting sample code?

Thanks in advance.

Thanks,
Praveen Kumar P

How To Create Style Heading1 in Office Open XML C#

$
0
0
 I try to create Heading1 style in the word document but nothing works.


I have this code to create style and document.

    public static void CreateWord(string filepath)
    {
        var wdoc = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document);
        var mdoc = wdoc.AddMainDocumentPart();

        AddStylesPartToPackage(wdoc);
        // Create the document structure and add some text.
        mdoc.Document = new Document();
        var body = mdoc.Document.AppendChild(new Body());

        CreateStyleHeading(mdoc,"Heading1","Heading 1");

        var par = body.AppendChild(new Paragraph());
        var run = par.AppendChild(new Run());
        var r = run.AppendChild(new Run());
        r.AppendChild(new Text("Create text in body - CreateWordprocessingDocument"));


        // ReSharper disable once UseMethodAny.2
        if (par.Elements<ParagraphProperties>().Count() == 0)
            par.PrependChild<ParagraphProperties>(new ParagraphProperties());
        // Get the ParagraphProperties element of the paragraph.
        var pPr = par.Elements<ParagraphProperties>().First();
        // Set the value of ParagraphStyleId to "Heading3".
        pPr.ParagraphStyleId = new ParagraphStyleId() { Val = "Heading1" };

        wdoc.Close();

    }

    // Add a StylesDefinitionsPart to the document.  Returns a reference to it.
    public static StyleDefinitionsPart AddStylesPartToPackage(WordprocessingDocument doc)
    {
        StyleDefinitionsPart part;
        part = doc.MainDocumentPart.AddNewPart<StyleDefinitionsPart>();
        Styles root = new Styles();
        root.Save(part);
        return part;
    }

    public static void CreateStyleHeading(MainDocumentPart mdoc,  string styleid,string stylename)
    {



        var styles = mdoc.StyleDefinitionsPart.Styles;
        if (styles == null)
        {
            mdoc.StyleDefinitionsPart.Styles = new Styles();
            mdoc.StyleDefinitionsPart.Styles.Save();
        }

        // Create a new paragraph style element and specify some of the attributes.
        var style = new Style()
        {
            Type = StyleValues.Paragraph,
            StyleId = styleid,
            CustomStyle = true,
            Default = false
        };

        // Create and add the child elements (properties of the style).
        var uiPriority1 = new UIPriority { Val = 9 };

        //Aliases aliases1 = new Aliases() { Val = "" };
        var autoredefine1 = new AutoRedefine() { Val = OnOffOnlyValues.Off };
        var basedon1 = new BasedOn() { Val = "Normal" };
        var linkedStyle1 = new LinkedStyle() { Val = "OverdueAmountChar" };
        var locked1 = new Locked() { Val = OnOffOnlyValues.Off };
        var primarystyle1 = new PrimaryStyle() { Val = OnOffOnlyValues.On };
        var stylehidden1 = new StyleHidden() { Val = OnOffOnlyValues.Off };
        var semihidden1 = new SemiHidden() { Val = OnOffOnlyValues.Off };
        var styleName1 = new StyleName() { Val = stylename };
        var nextParagraphStyle1 = new NextParagraphStyle() { Val = "Normal" };
        var uipriority1 = new UIPriority() { Val = 1 };
        var unhidewhenused1 = new UnhideWhenUsed() { Val = OnOffOnlyValues.On };

        style.Append(uiPriority1);
        style.Append(autoredefine1);
        style.Append(basedon1);
        style.Append(linkedStyle1);
        style.Append(locked1);
        style.Append(primarystyle1);
        style.Append(stylehidden1);
        style.Append(semihidden1);
        style.Append(styleName1);
        style.Append(nextParagraphStyle1);
        style.Append(uipriority1);
        style.Append(unhidewhenused1);

        // Create the StyleRunProperties object and specify some of the run properties.
        var styleRunProperties1 = new StyleRunProperties();
        var bold1 = new Bold();
        var color1 = new Color() { ThemeColor = ThemeColorValues.Accent2 };
        var font1 = new RunFonts() { Ascii = "Lucida Console" };
        var italic1 = new Italic();
        // Specify a 12 point size.
        var fontSize1 = new FontSize() { Val = "24" };
        styleRunProperties1.Append(bold1);
        styleRunProperties1.Append(color1);
        styleRunProperties1.Append(font1);
        styleRunProperties1.Append(fontSize1);
        styleRunProperties1.Append(italic1);

        // Add the run properties to the style.
        style.Append(styleRunProperties1);

        // Add the style to the styles part.
        styles.Append(style);
    }





But when I run:

    CreateWord("file.docx");

When I open file.docx my style is renamed to "Heading 11" instead of "Heading 1" and there is no Navigation. ("This document does not contain headings"). [I cannot add pictures to this post]


I found only how to create style. But i cannot find information how to create Heading1 style. When i unpack created .docx and .docx created by a Word document i found only that Heading1 is added to "latentStyles" but I cannot find how to do this in the code.

Create word document using document template openXML dll

$
0
0

Hello,

I have to create MS word document using one template file in C# using openxml dll.

I do not have any idea how should I start.

requirements is, In template there will be one page which will contain few information as below, and I need to repeat this block of content n'th times.

---------

Employee Name: #Name# 
Address: #Address#
Employee ID : #EmployeeID#
Status: #Status#
Details:#Details#

-------------

Now I need to repeat this section dynamically in c# code as per Employee List.

SO if there are 5 employees this content should get repeat 5 times.

How it is possible with Open XML.

I could replace text of existing block to actual one.
but unable to repeat that block / Page dynamically.

Also I'm not sure how I should create template where I will get starting and ending point of content.
I guess Document template needs to be create in proper format. Which I don't know :(

Thanks in advance.



Using MergeCells causes rare character in xml declaration

$
0
0

Hi there,

I'm using SDK v2.5 for creating an Excel document . I am using examples from MSDN for inserting text and just after, merging two cells to insert another text on them. When I save the worksheet, an strange character is inserted in the first line of Sheet1.xml file created inside the Excel file. When I open the file in Excel (2007), prompts me saying that the file have some incorrect values ​​and it will fix it by clicking yes. If I click yes and then a save the file, Excel removes this character. I checked it and It only Occurs When I am merging cells. The inserted character is: ï»¿

how to add shapes to Specific cell in excel using openxml C#

$
0
0

Please help me to draw shapes using openxml c#. Now I am doing filling color to entire cell instead of this draw circle to Specific cell. 

Add Comment in to selected Text in Word Document Using OpenXML c#

$
0
0

I need to use OpenXML to add comments in to a word document. I need to add a comment to a location or word(or multiple words). Normally in a word document openxml return those text as run elements. But the words which I wanted to add a comment is coming with different run elements. So I couldn't add a comment in to the document words which i actually wanted. It means that I couldn't add specificCommentRangeStart and CommentRangeEnd objects.

My current implementation is as below.

foreach(var paragraph in document.MainDocumentPart.Document.Descendants<DocumentFormat.OpenXml.Wordprocessing.Paragraph>()){foreach(var run in paragraph.Elements<Run>()){var item = run.Elements<Text>().FirstOrDefault(b => b.Text.Trim()=="My words selection to add comment");if(item !=null){
                                    run.InsertBefore(newCommentRangeStart(){Id= id }, item);var cmtEnd = run.InsertAfter(newCommentRangeEnd(){Id= id }, item);
                                    run.InsertAfter(newRun(newCommentReference(){Id= id }), cmtEnd);}}}

Insert vbaProject into PowerPoint and change file type to macro enabled

$
0
0

I want to insert vbaProject binary file into my presentation. I added VbaProjectPart into PresentationPart. However, after the presentation created, I looked at the zip content and saw vbaProject.xml was created under \ppt. It should be vbaProject.bin. How can I change the presentation from .pptx to .pptm - macro enabled?

Thanks in advance!!!


How to insert comments in excel using openxml

$
0
0

Can anyone please explain how to add comments to cell programatically , Also please provide a working example? I tried by creating the vml drawing and comments part , but it's not working , I'm getting a corrupted excel sheet.

Thanks!

Format Cells over a range

$
0
0

Hello,

currently i work with OpenXML to create a excel sheet.

Now i will format serveral Cells over a Range.

I know how to set a Value and Style for one Cell. But is there a way to select a Cell range and set the StyleFormat for all of this Cells?

For example.

//add Heading
Row row = new Row()
{
    RowIndex = (UInt32)1u
};

Cell cell1= new Cell()
{

    CellReference = "A1",
    DataType = CellValues.String,
    CellValue = new CellValue("Test"),
    StyleIndex = Convert.ToUInt32(1)
};
row.Append(cell1);

I thought it would be possible like following example. But this does not work :(

//add Body
Row row2 = new Row()
{
    RowIndex = (UInt32)1u
};

Cell cell2= new Cell()
{
    CellReference = "A1:A5",
    DataType = CellValues.String,
    CellValue = new CellValue("new Test"),
    StyleIndex = Convert.ToUInt32(1)
};
row.Append(cecell2l1);

 Can anyone give me an example how to select a range and format it?

Ty for help.

Greetings Nejox

Rotate the Text in a Excel sheet

$
0
0

Hi,

i have following code to format my Cells. On which point i have to add the Alignment to rotate my Text?

I tried it to add in Font index 3 "new Alignment() { TextRotation = (UInt32Value)90U }" but this does not work :(

Can anyone help me?

Greetings Nejox

 private Stylesheet AddStyleSheet()
        {
            Stylesheet stylesheet = null;

            Fonts fonts = new Fonts(new Font(               // Index 0 - default
                new FontSize() { Val = 10 }),
                new Font(                                   // Index 1 - header
                   new FontSize() { Val = 12 },
                   new FontName() { Val = "Arial" },
                   new Bold()),
                    new Font(                               // Index 2
                        new FontSize() { Val = 9 },
                        new FontName() { Val = "Arial" }),
                         new Font(                          // Index 3
                             new FontSize() { Val = 12 },
                             new FontName() { Val = "Arial" },
                             new Bold()
               ));

            Fills fills = new Fills(
                    new Fill(new PatternFill() { PatternType = PatternValues.None }),                                       // Index 0 - default
                    new Fill(new PatternFill() { PatternType = PatternValues.Gray125 }),                                    // Index 1 - default
                    new Fill(new PatternFill(new ForegroundColor { Rgb = new HexBinaryValue() { Value = "66666666" } })
                    { PatternType = PatternValues.Solid })                                                                  // Index 2 - header
                );

            Borders borders = new Borders(
                    new Border(),                                                                                           // index 0 default
                    new Border(                                                                                             // index 1 bottom border
                        new BottomBorder(new Color() { Auto = true }) { Style = BorderStyleValues.Thin }),
                            new Border(                                                                                     //index 2 border
                            new LeftBorder(new Color() { Auto = true }) { Style = BorderStyleValues.Thin },
                            new RightBorder(new Color() { Auto = true }) { Style = BorderStyleValues.Thin },
                            new TopBorder(new Color() { Auto = true }) { Style = BorderStyleValues.Thin },
                            new BottomBorder(new Color() { Auto = true }) { Style = BorderStyleValues.Thin },
                            new DiagonalBorder())
                );


            CellFormats cellFormats = new CellFormats(new CellFormat(),         // default
                    new CellFormat                                              // Format 1
                    {
                        FontId = 1,
                        BorderId = 1,
                        ApplyBorder = true
                    },
                    new CellFormat                                              // Format 2
                    {
                        FontId = 2,
                        BorderId = 0,
                        ApplyFill = true
                    },
                    new CellFormat                                              // Format 3
                    {
                        FontId = 2,
                        BorderId = 2,
                        ApplyFill = true
                    },
                    new CellFormat                                              // Format 4
                    {
                        FontId = 3,
			//Add alignment! How?
                    }

                );

            stylesheet = new Stylesheet(fonts, fills, borders, cellFormats);

            return stylesheet;
        }


Print with openXML

$
0
0

Hello,

i create a SpreadsheetDocument with open XML. When i finish and saved the Document i want to print it with different Values like Landscape format and edit the top margin.

Is there a way with open XML to say Print the Document after Save? I searched in different Forums but didnt found a solution.

Greetungs Nejox

DocumentFormat.OpenXml.Wordprocessing.Body Constructor remove escaped characters

$
0
0

I'm opening a .dotx file and load it into a MemoryStream:

MemoryStream memoryStream = null; //this will hold our in memory Word doc

            using(Stream templateStream = File.Open(templatePath, FileMode.Open, FileAccess.Read))
            {
                memoryStream = new MemoryStream((int)templateStream.Length);
                templateStream.CopyTo(memoryStream);
                templateStream.Flush();
                memoryStream.Position = 0L; //reset position for reading
            }

After that I open the document as WordprocessingDocument and I start doing replacements looking for Merge Fields. I do the replacements in xmlDocXElement (see bellow)


 using (WordprocessingDocument docx = WordprocessingDocument.Open(memoryStream, true))
            {
                var mergeFields = docx.MainDocumentPart.Document.Body;

                XElement xmlDocXElement = XElement.Parse(docx.MainDocumentPart.Document.Body.OuterXml);

                    var dictionary = (IDictionary<string, object>)data;

                foreach (KeyValuePair<string,object> record in dictionary)
                {
                    ... //Replacement logic
                }
//Bug is about to happen
                docx.MainDocumentPart.Document.Body = new Body(xmlDocXElement.ToString());
//Bug happened
            }

Before the bug happens all the Special characters are encoded fine, as I use XElement.Parse before including them in the document. But for some reason after the Body() constructor some of the especial character like &amp; are returned to their normal form?

&amp; --> &

I tried adding & manually during the replacement process and all of them are replaced OK. I found only one Stack Overflow user with the same issue http://stackoverflow.com/questions/37118685/openxml-escaping-in-constructor-of-body-element. It's a bit weird as it doesn't happen all the time so I can't really tell you what to do in order to simulate it.

Here is the row content before Body():

<w:r><w:rPr><w:rFonts w:cs="Arial" /><w:noProof /><w:szCs w:val="20" /></w:rPr><w:t xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">Warwickshire Golf &amp; Country Club North Woodloes,<w:br />Leek Wootton,<w:br />Warwick,<w:br />Warwickshire,<w:br />CV35 7QT</w:t></w:r>

Here is the row content after Body():

<w:r><w:rPr><w:rFonts w:cs="Arial" /><w:noProof /><w:szCs w:val="20" /></w:rPr><w:t xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">Warwickshire Golf & Country Club North Woodloes,<w:br />Leek Wootton,<w:br />Warwick,<w:br />Warwickshire,<w:br />CV35 7QT</w:t></w:r>

As you can see the second piece of code contains the & as a character and not as and xml entity, this will generate a corrupted .docx document.

Any ideas?

Make custom property as read only using OpenXML

$
0
0

So far I've been able to set custom properties to a Word doc by using OpenXML with the help of below code

Code

I want to make this property as non editable ( read only ) from word properties details UI. Is this possible? Also,I would to fix this as a permanent property so no one can delete this property.


Thanks

Write to XLS file without using Office client application ?

$
0
0

https://support.microsoft.com/en-us/kb/257757 said "Microsoft strongly recommends a number of alternatives that do not require Office to be installed server-side, and that can perform most common tasks more efficiently and more quickly than Automation.
Most server-side Automation tasks involve document creation or editing. Office 2007 supports new Open XML file formats that let developers create, edit, read, and transform file content on the server side. These file formats use the System.IO.Package.IO namespace in the Microsoft .NET 3.x Framework to edit Office files without using the Office client applications themselves. This is the recommended and supported method for handling changes to Office files from a service."

Currently, I have a program that uses an existing XLS that already format the column headers with colors and has formulas for some cells, runs a Macro in an XLS file that queries a TXT file, creates a Pivot table, and save the XLS sheet to a different XLS file.
Below is an example of the XLS column header. There are formulas behind the $0 (for ex: =SUMIF(B6:B31378,"=Open",K6:K31378)

The codes for the Macro is the below.
How can I do this without using Office client application ?
Thank you.

Sub myMacro(Var1, Var2)
    With ActiveSheet.QueryTables.Add(Connection:= _"TEXT;" & Var1, Destination:=Range("A6"))
        .Name = "oc_1"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 437
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = False
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = False
        .TextFileSpaceDelimiter = False
        .TextFileOtherDelimiter = "|"
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, _
        1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
    Rows("6:6").Select
    Range(Selection, Selection.End(xlDown)).Select
    ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase, SourceData:= _"OC_Report!R5C1:R25000C23").CreatePivotTable TableDestination:="", _
        TableName:="PivotTable1", DefaultVersion:=xlPivotTableVersion10
    ActiveSheet.PivotTableWizard TableDestination:=ActiveSheet.Cells(3, 1)
    ActiveSheet.Cells(3, 1).Select
    ActiveSheet.PivotTables("PivotTable1").RowGrand = False
    ActiveSheet.PivotTables("PivotTable1").AddFields RowFields:=Array("Firm", _"open/" & Chr(10) & "closed")
    ActiveSheet.PivotTables("PivotTable1").PivotFields("open/" & Chr(10) & "closed").Orientation _
        = xlDataField
        Worksheets("OC_Report").Activate
        ActiveSheet.Range("A6").Select

    Worksheets("Sheet1").Activate
    Sheets("Sheet1").Select
    Sheets("Sheet1").Name = "OCF"

    Worksheets("OC_Report").Activate
    ActiveSheet.Range("A6").Select

    Dim active As Workbook
    Set active = Application.ThisWorkbook

    Dim wb As Workbook
    Set wb = Workbooks.Add

    active.Activate
        Sheets("OC_Report").Select
        Sheets("OC_Report").Copy Before:=Workbooks(wb.Name).Sheets(1)
    active.Activate
        Sheets("OCF").Select
        Sheets("OCF").Copy After:=Workbooks(wb.Name).Sheets(1)
    active.Activate
        Sheets("MyTab2").Select
        Sheets("MyTab2").Copy After:=Workbooks(wb.Name).Sheets(1)

    wb.Sheets("Sheet1").Delete

    ActiveWorkbook.SaveAs Filename:= _
        Var2, FileFormat:=xlNormal, _
        Password:="", WriteResPassword:="", ReadOnlyRecommended:=False, _
        CreateBackup:=False
End Sub


Fill a specific Shape - ShapeStyle with color C# PowerPoint OpenXML

$
0
0

I would like to change the fill color of a few shapes in a slide.

I found this tutorial on msdn, but it only mention a very specific scenario (first shape of first slide, in a presentation where there is only one shape) => Link to the MSDN tutorial

It seems  that when Itry to access the ShapeTree Elements dynamically, Iget a "nullReference exception" or a "not define as an instance of an object", when trying to access the ShapeStyle property (even with the FirstChild() example actually).

So I tried to access it as follows, by itering through the Elements, but no success neither.

ShapeTree tree = slide.Slide.CommonSlideData.ShapeTree;
            for (var i = 0; i <= 30; i++)
            {
                try
                {
                    DRAW.FillReference fillRef = tree.ElementAt(i).GetFirstChild<DocumentFormat.OpenXml.Presentation.Shape>().ShapeStyle.FillReference;


                    fillRef.SchemeColor = new DRAW.SchemeColor();
                    fillRef.SchemeColor.Val = DRAW.SchemeColorValues.Accent6;

                }
                catch (Exception e)
                {
                //Null reference Excpetion on the fillRef initialization, does the same if I cast with DocumentFormat.OpenXml.Drawing.Shape
                }

           }

My goal is really simple, I'd like to change the fill color of a shape, by identifying it's innerText.

Thanks in advance !

Problem to DocumentFormat

$
0
0
Hi,
How to correct this
Error	2	'DocumentFormat.OpenXml.Packaging.SpreadsheetDocument' does not contain a definition for 'WorksheetParts' and no extension method 'WorksheetParts' accepting a first argument of type 'DocumentFormat.OpenXml.Packaging.SpreadsheetDocument' could be found (are you missing a using directive or an assembly reference?)


due to 2nd line below?

                    SpreadsheetDocument Book0 = SpreadsheetDocument.Open(openFileDialog1.FileName, false);
                    WorksheetPart worksheetPart = Book0.WorksheetParts.First();



Many Thanks & Best Regards, Hua Min

how to use cell formula while using openxmlwriter in SAX approach

$
0
0

We are using the SAX approach to write excel because DOM approach is giving issue out of memory exception

Can anybody help to share a reference for

how to use the cellformula if we use openxmlwriter to create the excel.

I have seen alot of reference in web ,  but not for cellformula while using the SAX approach.

Thanks

Why won't we store dates, numeric values in 'Sharedstring.xml' in excel xml package

$
0
0

Hai all,

Why won't we store dates, numeric values in 'Sharedstring.xml' file as other values. and also when i save a date in excel.

In excel I entered by selecting the format date and entered '12/12/2012' but in excel i could see this way.

<sheetData><row r="13" x14ac:dyDescent="0.25" spans="4:4"><c r="D13" s="1"><v>41255</v></c></row></sheetData>

may i know what do that conversion means

Regards,

kiran rachamalla.


Problem to line

$
0
0

Hi,

How to correct
                        Excel.Worksheet sheet2 = Book0.WorkbookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == "Sheet Overall");


due to
Error	2	Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<DocumentFormat.OpenXml.Spreadsheet.Sheet>' to 'Microsoft.Office.Interop.Excel.Worksheet'. An explicit conversion exists (are you missing a cast?)	C:\App\WindowsFormsApplication6\WindowsFormsApplication2\Form1.cs	117	50	WindowsFormsApplication2

                        
?


Many Thanks & Best Regards, Hua Min

Viewing all 1288 articles
Browse latest View live


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