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

How to create a combination pivot chart using open XML with C#

$
0
0

Step1:
We have created a bar chart using below code, we were able to get a pivot chart with stocked column.
But in one of the series , we need to add a line chart to this chart.
How can we achieve this?
Please let us know.
Thanks in advance.

private void GenerateChartPartContent(ChartPart chartPart,  string reportFileName, string sheetName, string tableName, string fileName)
        {
            //C.ChartSpace chartSpace1 = new C.ChartSpace();

            chartPart.ChartSpace = new C.ChartSpace();
            chartPart.ChartSpace.Append(new C.EditingLanguage() { Val = new StringValue("en-US") });
            DocumentFormat.OpenXml.Drawing.Charts.Chart chart = chartPart.ChartSpace.AppendChild<DocumentFormat.OpenXml.Drawing.Charts.Chart>(
                new DocumentFormat.OpenXml.Drawing.Charts.Chart());


            C.Date1904 date19041 = new C.Date1904() { Val = false };
            C.EditingLanguage editingLanguage1 = new C.EditingLanguage() { Val = "en-US" };
            C.RoundedCorners roundedCorners1 = new C.RoundedCorners() { Val = false };

            AlternateContent alternateContent2 = new AlternateContent();

            AlternateContentChoice alternateContentChoice2 = new AlternateContentChoice() { Requires = "c14" };
            alternateContentChoice2.AddNamespaceDeclaration("c14", "");
            C14.Style style1 = new C14.Style() { Val = 102 };

            alternateContentChoice2.Append(style1);

            AlternateContentFallback alternateContentFallback1 = new AlternateContentFallback();
            C.Style style2 = new C.Style() { Val = 2 };

            alternateContentFallback1.Append(style2);

            alternateContent2.Append(alternateContentChoice2);
            alternateContent2.Append(alternateContentFallback1);

            C.PivotSource pivotSource1 = new C.PivotSource();
            C.PivotTableName pivotTableName1 = new C.PivotTableName();
            pivotTableName1.Text = "[" + fileName + "]" + sheetName + "!" + tableName;
            C.FormatId formatId1 = new C.FormatId() { Val = (UInt32Value)14U };

            pivotSource1.Append(pivotTableName1);
            pivotSource1.Append(formatId1);

            chartPart.ChartSpace.Append(pivotSource1);

            C.Chart chart1 = new C.Chart();

            C.PivotFormats pivotFormats1 = new C.PivotFormats();

            // Create a new clustered column chart.
            C.PlotArea plotArea = chart.AppendChild<C.PlotArea>(new C.PlotArea());
            C.Layout layout = plotArea.AppendChild<C.Layout>(new C.Layout());

            C.BarChart barChart = plotArea.AppendChild<C.BarChart>(new C.BarChart(new C.BarDirection() { Val = new EnumValue<C.BarDirectionValues>(C.BarDirectionValues.Column) },
                new C.BarGrouping() { Val = new EnumValue<C.BarGroupingValues>(C.BarGroupingValues.Stacked) }));
            barChart.Append(new C.AxisId() { Val = new UInt32Value(48650112u) });
            barChart.Append(new C.AxisId() { Val = new UInt32Value(48672768u) });
            C.Overlap overlap1 = new C.Overlap() { Val = 100 };
            C.GapWidth gapWidth1 = new C.GapWidth() { Val = (UInt16Value)219U };

            C.DataLabels dataLabels1 = new C.DataLabels();
            C.ShowLegendKey showLegendKey1 = new C.ShowLegendKey() { Val = true };
            C.ShowValue showValue1 = new C.ShowValue() { Val = false };
            C.ShowCategoryName showCategoryName1 = new C.ShowCategoryName() { Val = false };
            C.ShowSeriesName showSeriesName1 = new C.ShowSeriesName() { Val = false };
            C.ShowPercent showPercent1 = new C.ShowPercent() { Val = false };
            C.ShowBubbleSize showBubbleSize1 = new C.ShowBubbleSize() { Val = false };
            C.AutoTitleDeleted autoTitleDeleted1 = new C.AutoTitleDeleted() { Val = false };
            C.NoMultiLevelLabels noMultiLevelLabels1 = new C.NoMultiLevelLabels { Val = true };
            dataLabels1.Append(showLegendKey1);
            dataLabels1.Append(showValue1);
            dataLabels1.Append(showCategoryName1);
            dataLabels1.Append(showSeriesName1);
            dataLabels1.Append(showPercent1);
            dataLabels1.Append(showBubbleSize1);
            //overlap column
            barChart.Append(overlap1);
            //gridlines width
            barChart.Append(gapWidth1);
            uint i = 0;
            barChart.Append(dataLabels1);

            ////////////////////////

            // Page filters code
            C.ChartSpaceExtensionList chartSpaceExtensionList1 = new C.ChartSpaceExtensionList();

            C.ChartSpaceExtension chartSpaceExtension1 = new C.ChartSpaceExtension() { Uri = "{E28EC0CA-F0BB-4C9C-879D-F8772B89E7AC}" };

            C.ChartSpaceExtension chartSpaceExtension2 = new C.ChartSpaceExtension() { Uri = "{781A3756-C4B2-4CAC-9D66-4F8BD8637D16}" };

            C14.PivotOptions pivotOptions1 = new C14.PivotOptions();
            C14.DropZoneFilter dropZoneFilter1 = new C14.DropZoneFilter() { Val = true };
            C14.DropZoneCategories dropZoneCategories1 = new C14.DropZoneCategories() { Val = true };
            C14.DropZoneData dropZoneData1 = new C14.DropZoneData() { Val = true };
            C14.DropZoneSeries dropZoneSeries1 = new C14.DropZoneSeries() { Val = true };
            C14.DropZonesVisible dropZonesVisible1 = new C14.DropZonesVisible() { Val = true };

            pivotOptions1.Append(dropZoneFilter1);
            pivotOptions1.Append(dropZoneCategories1);
            pivotOptions1.Append(dropZoneData1);
            pivotOptions1.Append(dropZoneSeries1);
            pivotOptions1.Append(dropZonesVisible1);

            chartSpaceExtension2.Append(pivotOptions1);

            chartSpaceExtensionList1.Append(chartSpaceExtension1);
            chartSpaceExtensionList1.Append(chartSpaceExtension2);
            chartPart.ChartSpace.Append(chartSpaceExtensionList1);
            /////////////////////////////////////


            // Add the Category Axis.
            C.CategoryAxis catAx = plotArea.AppendChild<C.CategoryAxis>(new C.CategoryAxis(new C.AxisId() { Val = new UInt32Value(48650112u) }, new C.Scaling(new C.Orientation()
            {
                Val = new EnumValue<DocumentFormat.
                    OpenXml.Drawing.Charts.OrientationValues>(DocumentFormat.OpenXml.Drawing.Charts.OrientationValues.MinMax)
            }),
                new C.AxisPosition() { Val = new EnumValue<C.AxisPositionValues>(C.AxisPositionValues.Bottom) },

                new C.TickLabelPosition() { Val = new EnumValue<C.TickLabelPositionValues>(C.TickLabelPositionValues.NextTo) }, //NextTo KB00--Line
                new C.CrossingAxis() { Val = new UInt32Value(48672768U) },
                new C.Crosses() { Val = new EnumValue<C.CrossesValues>(C.CrossesValues.AutoZero) },
                new C.AutoLabeled() { Val = new BooleanValue(true) },
                new C.Delete() { Val = new BooleanValue(false) },//Category axis values
                new C.LabelAlignment() { Val = new EnumValue<C.LabelAlignmentValues>(C.LabelAlignmentValues.Center) },
                new C.LabelOffset() { Val = new UInt16Value((ushort)100) }));

            // Add the Value Axis.
            C.ValueAxis valAx = plotArea.AppendChild<C.ValueAxis>(new C.ValueAxis(new C.AxisId() { Val = new UInt32Value(48672768u) },
                new C.Scaling(new C.Orientation()
                {
                    Val = new EnumValue<DocumentFormat.OpenXml.Drawing.Charts.OrientationValues>(
                        DocumentFormat.OpenXml.Drawing.Charts.OrientationValues.MinMax)
                }),
                new C.AxisPosition() { Val = new EnumValue<C.AxisPositionValues>(C.AxisPositionValues.Left) },
                new C.MajorGridlines(),
                new DocumentFormat.OpenXml.Drawing.Charts.NumberingFormat()
                {
                    FormatCode = new StringValue("General"),
                    SourceLinked = new BooleanValue(true)
                }, new C.TickLabelPosition()
                {
                    Val = new EnumValue<C.TickLabelPositionValues>
                        (C.TickLabelPositionValues.NextTo)
                }, new C.CrossingAxis() { Val = new UInt32Value(48650112U) },
                 new C.AutoLabeled() { Val = new BooleanValue(true) },
                new C.Crosses() { Val = new EnumValue<C.CrossesValues>(C.CrossesValues.AutoZero) },
                 new C.Delete() { Val = new BooleanValue(false) },//value axis values
                   new C.LabelAlignment() { Val = new EnumValue<C.LabelAlignmentValues>(C.LabelAlignmentValues.Center) },
                 new C.CrossBetween() { Val = new EnumValue<C.CrossBetweenValues>(C.CrossBetweenValues.Between) }));
            // Add the chart Legend.
            C.Legend legend = chart.AppendChild<C.Legend>(new C.Legend(new C.LegendPosition() { Val = new EnumValue<C.LegendPositionValues>(C.LegendPositionValues.Right) },//This is for Right Legends position //NextTo KB00--Line
                new C.Layout()));

            chart.Append(new C.PlotVisibleOnly() { Val = new BooleanValue(true) });
            chart.Append(autoTitleDeleted1);
            // Save the chart part.
            chartPart.ChartSpace.Save();

            }


Problem in GroupShape

$
0
0

Hi,

I am trying to plot the PowerPoint slide in HTML using OOXML. While I read XML for group shape in a slide the child off and child ext value is coming different. 

While calculating the position and plot them in html is not correct as i am converting EMU to Pixel.

Logic to get the position is  (child off - group off) give me child off values and width is  from child chext.

<a:off x="4194176" y="1703373" />
<a:ext cx="3781425" cy="4638675" />
<a:chOff x="1805" y="845" />
<a:chExt cx="2820" cy="3194" />

My trouble group off and ext value unit is EMU and choff and chExt unit is in EMU ?

And how to calculate the position and dimensions of shape when choff and chExt is coming that small.

Thnaks,

Vishal Sood

c# change cell color from value (xlsx)

$
0
0
I have a file xlsx which contains data:
ID 	VALUE
ID1204  0
ID5611  0
ID6711  1
ID4572  2

I want to color the cells in the ID column if VALUE is greater than 1.
I need to set background color in red the cell number ID4572.
The number of rows in the file can be more than 1000.
How to do it?
I use ClosedXML.Excel

My question is ¿OpenXml supports creating diagrams in excel?

$
0
0

Hello world/everyone.

I have a question. I like use the diagrams in microsoft excel but i have a data in sql server and i try to make this diagram with my database but Openxlm support creating diagrams with C#? And database?

Thanks i still wait for your comments.

Regards

EESB


ESALAS

highlight excel cell using openxml

$
0
0

I am using openxml for excel operations.Using openxml , I have appended rows to the end of an excel file.

Now,I need to highlight the appended rows ,so that the user will know which are the rows appended.

Is there a way to do it?

Word document set document property

$
0
0

Hello,

I'm looking to set a single property in a new document using Visual Studio 2017, C# and the current NuGet package for OpenXML. 

There are two attempts, one C#, second C# and VB.NET. Bottom line is first attempt sets the property but does not persist after saving/opening via WinWord while the second does not work which I indicate where below.

Followed instructions in the following documentation. In Visual Studio 2017 local window the property Title gets set but not saved.

I did search through this forum yet the two attempts seemed the most logical out of several search pages.

Thanks for any thoughts.

First attempt

Code execution (_DocumentFolder is an existing folder below the executable folder)

public void CreateNewEmptyDocumentWithCustomProperties()
{
    var fileName = Path.Combine(_DocumentFolder, "NewEmptyDocument.docx");
    using (var document = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document))
    {
        MainDocumentPart mainPart = document.AddMainDocumentPart();
        mainPart.Document = new Document();
        mainPart.Document.AppendChild(new Body());
        mainPart.Document.Save();
    }


    SetCustomProperty(fileName, "Title", "My title", PropertyTypes.Text);
}

Code taken from documentation (see link above)

public void CreateNewEmptyDocumentWithCustomProperties()
{
    var fileName = Path.Combine(_DocumentFolder, "NewEmptyDocument.docx");
    using (var document = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document))
    {
        MainDocumentPart mainPart = document.AddMainDocumentPart();
        mainPart.Document = new Document();
        mainPart.Document.AppendChild(new Body());
        mainPart.Document.Save();
    }

    //var x = new Class1();
    //x.WDSetCustomProperty(fileName, "Title", "Writing code");
    SetCustomProperty(fileName, "Title", "My title", PropertyTypes.Text);
}

public static string SetCustomProperty(string pFileName, string pPropertyName, object pPropertyValue, PropertyTypes pPropertyType)
{
    string returnValue = null;

    var newProp = new CustomDocumentProperty();
    bool propSet = false;

    switch (pPropertyType)
    {
        case PropertyTypes.DateTime:

            // The date/time value passed in should represent a UTC date/time.
            if ((pPropertyValue) is DateTime)
            {
                newProp.VTFileTime = new VTFileTime($"{Convert.ToDateTime(pPropertyValue):s}Z");
                propSet = true;
            }

            break;

        case PropertyTypes.NumberInteger:
            if ((pPropertyValue) is int)
            {
                newProp.VTInt32 = new VTInt32(pPropertyValue.ToString());
                propSet = true;
            }

            break;

        case PropertyTypes.NumberDouble:
            if (pPropertyValue is double)
            {
                newProp.VTFloat = new VTFloat(pPropertyValue.ToString());
                propSet = true;
            }

            break;

        case PropertyTypes.Text:
            newProp.VTLPWSTR = new VTLPWSTR(pPropertyValue.ToString());
            propSet = true;

            break;

        case PropertyTypes.YesNo:
            if (pPropertyValue is bool)
            {
                // Must be lowercase.
                newProp.VTBool = new VTBool(Convert.ToBoolean(pPropertyValue).ToString().ToLower());
                propSet = true;
            }

            break;
    }

    if (!propSet)
    {
        // If the code was not able to convert the property to a valid value, throw an exception.
        throw new InvalidDataException("propertyValue");
    }

    // Now that you have handled the parameters, start working on the document.
    newProp.FormatId = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}";
    newProp.Name = pPropertyName;

    using (var document = WordprocessingDocument.Open(pFileName, true))
    {
        var customProps = document.CustomFilePropertiesPart;
        if (customProps == null)
        {
            // No custom properties? Add the part, and the
            // collection of properties now.
            customProps = document.AddCustomFilePropertiesPart();
            customProps.Properties = new DocumentFormat.OpenXml.CustomProperties.Properties();
        }

        var props = customProps.Properties;
        if (props != null)
        {
            // This will trigger an exception if the property's Name 
            // property is null, but if that happens, the property is damaged, 
            // and probably should raise an exception.
            var prop = props.FirstOrDefault(p => ((CustomDocumentProperty) p).Name.Value == pPropertyName);

            // Does the property exist? If so, get the return value, 
            // and then delete the property.
            if (prop != null)
            {
                returnValue = prop.InnerText;
                prop.Remove();
            }

            // Append the new property, and fix up all the property ID values. 
            // The PropertyId value must start at 2.
            props.AppendChild(newProp);

            var pid = 2;
            foreach (CustomDocumentProperty item in props)
            {
                item.PropertyId = pid++;
            }

            props.Save();

            //document.Save(); // not in original code sample
        }

        return returnValue;

    }
}

Second attempt

Reading from the following post (in VB.NET) I decided to create a VB.NET class project, added it as a reference to the C# project. It's hacked enough to run for testing. On the line Dim node As XmlNode it returns Nothing which in turn bypasses setting the intended property. If this had worked I would rewrite in C# but it does not work.

Code execution

public void CreateNewEmptyDocumentWithCustomProperties()
{
    var fileName = Path.Combine(_DocumentFolder, "NewEmptyDocument.docx");
    using (var document = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document))
    {
        MainDocumentPart mainPart = document.AddMainDocumentPart();
        mainPart.Document = new Document();
        mainPart.Document.AppendChild(new Body());
        mainPart.Document.Save();
    }

    var x = new Class1();
    x.WDSetCustomProperty(fileName, "Title", "Writing code");
}

VB.NET Code

Imports System.IO
Imports System.Xml

Public Class Class1
    Private Enum PropertyTypes
        YesNo
        Text
        DateTime
        NumberInteger
        NumberDouble
    End Enum

    Public Function WDSetCustomProperty(ByVal docName As String, ByVal propertyName As String, ByVal propertyValue As Object) As Boolean

        Dim propertyType = PropertyTypes.Text ' Karen being lazy

        Dim documentRelationshipType As String = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"
        Dim customPropertiesRelationshipType As String = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties"
        Dim customPropertiesSchema As String = "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties"
        Dim customVTypesSchema As String = "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"

        Dim retVal As Boolean = False
        Dim documentPart As System.IO.Packaging.PackagePart = Nothing
        Dim propertyTypeName As String = "vt:lpwstr"
        Dim propertyValueString As String = Nothing

        ' Calculate the correct type.
        Select Case propertyType
            Case PropertyTypes.DateTime
                propertyTypeName = "vt:filetime"
                ' Make sure you were passed a real date, 
                ' and if so, format in the correct way. 
                ' The date/time value passed in should 
                ' represent a UTC date/time.
                If propertyValue.GetType() Is GetType(System.DateTime) Then
                    propertyValueString = String.Format("{0:s}Z", Convert.ToDateTime(propertyValue))
                End If
            Case PropertyTypes.NumberInteger
                propertyTypeName = "vt:i4"
                If propertyValue.GetType() Is GetType(System.Int32) Then
                    propertyValueString =
                    Convert.ToInt32(propertyValue).ToString()
                End If

            Case PropertyTypes.NumberDouble
                propertyTypeName = "vt:r8"
                If propertyValue.GetType() Is GetType(System.Double) Then
                    propertyValueString = Convert.ToDouble(propertyValue).ToString()
                End If

            Case PropertyTypes.Text
                propertyTypeName = "vt:lpwstr"
                propertyValueString = Convert.ToString(propertyValue)

            Case PropertyTypes.YesNo
                propertyTypeName = "vt:bool"
                If propertyValue.GetType() Is GetType(System.Boolean) Then
                    ' Must be lower case!
                    propertyValueString =
                     Convert.ToBoolean(propertyValue).ToString().ToLower()
                End If
        End Select

        If propertyValueString Is Nothing Then
            ' If the code wasn't able to convert the 
            ' property to a valid value, 
            ' throw an exception:
            Throw New InvalidDataException("Invalid parameter value.")
        End If

        ' Next code block goes here.
        Using wdPackage As System.IO.Packaging.Package = System.IO.Packaging.Package.Open(docName, FileMode.Open, FileAccess.ReadWrite)

            ' Get the main document part (document.xml).
            For Each relationship As System.IO.Packaging.PackageRelationship In wdPackage.GetRelationshipsByType(documentRelationshipType)

                Dim documentUri As Uri =
                 System.IO.Packaging.PackUriHelper.ResolvePartUri(New Uri("/", UriKind.Relative), relationship.TargetUri)

                documentPart = wdPackage.GetPart(documentUri)
                ' There is only one document.
                Exit For
            Next

            ' Work with the custom properties part.
            Dim customPropsPart As System.IO.Packaging.PackagePart = Nothing

            ' Get the custom part (custom.xml). 
            ' It may not exist.
            For Each relationship As System.IO.Packaging.PackageRelationship In wdPackage.GetRelationshipsByType(customPropertiesRelationshipType)
                Dim documentUri As Uri = System.IO.Packaging.PackUriHelper.ResolvePartUri(New Uri("/", UriKind.Relative), relationship.TargetUri)

                customPropsPart =
                 wdPackage.GetPart(documentUri)
                ' There is only one custom properties part, 
                ' if it exists at all.
                Exit For
            Next

            ' Manage namespaces to perform Xml 
            ' XPath queries.
            Dim nt As New NameTable()
            Dim nsManager As New XmlNamespaceManager(nt)
            nsManager.AddNamespace("d", customPropertiesSchema)
            nsManager.AddNamespace("vt", customVTypesSchema)

            Dim customPropsUri As New Uri("/docProps/custom.xml", UriKind.Relative)
            Dim customPropsDoc As XmlDocument = Nothing
            Dim rootNode As XmlNode = Nothing

            ' Next code block goes here.
            If customPropsPart Is Nothing Then
                customPropsDoc = New XmlDocument(nt)

                ' Part doesn't exist. Create it now.
                Try
                    customPropsPart = wdPackage.GetPart(customPropsUri)
                Catch ex As Exception
                    customPropsPart = wdPackage.CreatePart(customPropsUri, "application/vnd.openxmlformats-officedocument.custom-properties+xml")
                End Try

                ' Set up the rudimentary custom part.
                rootNode = customPropsDoc.CreateElement("Properties", customPropertiesSchema)
                rootNode.Attributes.Append(customPropsDoc.CreateAttribute("xmlns:vt"))
                rootNode.Attributes("xmlns:vt").Value = customVTypesSchema

                customPropsDoc.AppendChild(rootNode)

                ' Create the document's relationship to _
                ' the new custom properties part:
                wdPackage.CreateRelationship(customPropsUri, System.IO.Packaging.TargetMode.Internal, customPropertiesRelationshipType)
            Else
                ' Load the contents of the custom 
                ' properties part into an XML document.
                customPropsDoc = New XmlDocument(nt)
                customPropsDoc.Load(customPropsPart.GetStream())

                rootNode = customPropsDoc.DocumentElement
            End If

            ' Next block goes here.
            Dim searchString As String = String.Format("d:Properties/d:property[@name='{0}']", propertyName)
            Dim node As XmlNode = customPropsDoc.SelectSingleNode(searchString, nsManager)

            Dim valueNode As XmlNode = Nothing

            If node IsNot Nothing Then
                ' You found the node. Now check its type:
                If node.HasChildNodes Then
                    valueNode = node.ChildNodes(0)
                    If valueNode IsNot Nothing Then
                        Dim typeName As String = valueNode.Name
                        If propertyTypeName = typeName Then
                            ' The types are the same. Simply 
                            ' replace the value of the node:
                            valueNode.InnerText = propertyValueString
                            ' If the property existed, and 
                            ' its type hasn't changed, you're done:
                            retVal = True
                        Else
                            ' Types are different. Delete the node, and clear 
                            ' the node variable:
                            node.ParentNode.RemoveChild(node)
                            node = Nothing
                        End If
                    End If
                End If
            End If

            ' Next block goes here.
            If node Is Nothing Then
                Dim pidValue As String = "2"

                Dim propertiesNode As XmlNode = customPropsDoc.DocumentElement
                If propertiesNode.HasChildNodes Then
                    Dim lastNode As XmlNode = propertiesNode.LastChild
                    If lastNode IsNot Nothing Then
                        Dim pidAttr As XmlAttribute = lastNode.Attributes("pid")
                        If Not pidAttr Is Nothing Then
                            pidValue = pidAttr.Value
                            Dim value As Integer
                            If Integer.TryParse(pidValue, value) Then
                                pidValue = Convert.ToString(value + 1)
                            End If
                        End If
                    End If
                End If

                ' Next block goes here.
                node = customPropsDoc.CreateElement("property", customPropertiesSchema)
                node.Attributes.Append(customPropsDoc.CreateAttribute("name"))
                node.Attributes("name").Value = propertyName

                node.Attributes.Append(
                 customPropsDoc.CreateAttribute("fmtid"))
                node.Attributes("fmtid").Value = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"

                node.Attributes.Append(
                 customPropsDoc.CreateAttribute("pid"))
                node.Attributes("pid").Value = pidValue

                valueNode = customPropsDoc.CreateElement(propertyTypeName, customVTypesSchema)
                valueNode.InnerText = propertyValueString
                node.AppendChild(valueNode)
                rootNode.AppendChild(node)
                retVal = True
            End If

            ' Save the properties XML back to its part.
            customPropsDoc.Save(customPropsPart.GetStream(FileMode.Create, FileAccess.Write))

            wdPackage.Close()

        End Using

        Return retVal
    End Function
End Class


Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
VB Forums - moderator
profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

Where can I download the OpenXML SDK 2.9 app

Open XML SDK v2 FAQ Part 1

$
0
0


Open XML SDK 2.0 FAQ

Commonly Asked Questions

General

1.     What is the Open XML SDK 2.0 for Microsoft Office?

2.     Where to download Open XML SDK 2.0?

3.     How to upgrade Open XML SDK?

4.     How many versions of Open XML Format SDK are there and which version is available in your solution?

Spreadsheet

5.     How to delete a sheet which contains a defined-name?

6.     How to insert a cell with a format style in Excel document using SDK 2.0?

7.     How to populate a spreadsheet with data from a real SQL database and create a cool looking chart based on that data

Wordprocessing

8.     How to generate TOC (table of contents) in Word document?

9.     How to update TOC (table of contents) dynamically in Word document?

10.     How to apply heading styles in Word using SDK 2.0?

11.        How to search for the Content Controls inside the Word file with SDK 2.0?

12.        How to add a watermark to a Word document?

13.        How to generate document from database based on document template?

14.        How to merge several documents into one document by using AltChunk?

15.        How to embed custom data in the custom XML part in to Word document by using content control?

16.        How to retrieve the text content of a Word document?

17.        How to add a new CustomXml part a Word document?

Presentation

18.        How to add rows to PowerPoint table?

19.        How to merge multiple PPT slides?

20.        How to find Open XML errors with Open XML SDK Validation?

Else

21.        Is there a Java version of Open XML SDK?

22.        Can I convert Open XML file format to HTML using SDK 2.0?

23.        Can I protect/add passwords to a Word document using SDK 2.0?

24.        Can I open a password protected Excel file using SDK 2.0?

25.        Can I add digital signature to a Word document using SDK 2.0?

26.        Can I open a signed document using SDK 2.0?

27.        Can I add or run macro in Word document using SDK 2.0?

28.        Can I insert building blocks with the SDK?

29.        Can I run formula calculation with SDK 2.0?

30.        Can I calculate the size of a paragraph with SDK 2.0?  

 

1.    What is the Open XML SDK 2.0 for Microsoft Office?

The Open XML SDK provides developers a set of classes to easily create, consume, and manipulate Open XML files without the need for automating Office client applications. The Open XML SDK is designed to let developers build high performance client-side or server-side solutions that perform complex operations using only a small amount of program code. When combined with Office Services, such as Excel and Word Automation Services, the Open XML SDK is able to accomplish many end-to-end scenarios. In addition to the Open XML SDK a new Productivity Tool has been released that provides a number of features designed to improve a developer’s productivity while working with the Open XML SDK and Open XML files. The tool is capable of automatically generating Open XML SDK source code based on document content. The source code can be used to generate all or part of the document. Another feature of the Productivity Tool is the ability to validate Open XML files according to Office 2007 and Office 2010. The Open XML SDK and the Productivity Tool adds important advances in the area of document format interoperability for Office.TOP

2.    Where to download Open XML SDK 2.0?

You can download Open XML SDK 2.0 for Microsoft Office RTW fromhere.TOP

3.    How to upgrade Open XML SDK?

After you upgrade Open XML SDK, Visual Studio can’t find previous version assembly, so you need to add new reference for the upgraded SDK again.TOP

4.    How many versions of Open XML Format SDK are there and which version is available in your solution?

So far, there have been two versions of Open XML Format SDK: V1 (1.0) and V2 (2.0). V1 is a product version, which can be redistributed in your solution. The latest version isOpen XML Format SDK 2.0 RTW, you are able to redistribute the final RTW version of the Open XML SDK 2.0 with your solution. For more information about the product, please download it and see “OpenXMLSDK.chm” file in it.TOP

5.    How to delete a sheet which contains a defined-name?

There is relationship between the sheet and defined names. We should operate on one sheet each time, remove a sheet and update all localSheetId values of remaining worksheet scoped definedName, then go to next one, which will ensure the whole spreadsheet document's validity. For more detailed information, please refer to:forum discussion thread.

Open XML SDK is based on low level DOM. Low level DOM is xml centric, especially comparing to the client OM. So many functions in the App OM cannot be achieved using the SDK easily, for example: inserting a row into a spreadsheet requires the code to re-index all the cells and correct the references in the formulas, etc. The same operation could be easily done through the Excel OM.TOP

6.    How to insert a cell with a format style in Excel document using SDK 2.0?

It is suggested to use the Productivity Tool. You need to create an empty Excel document as the source document, then format a cell with desired format and save it as the target document. Compare two documents with the productivity tool's Open XML Diff function to see which Open XML part/elements need to be changed. Or you can use the “Code For Diff” function to generate C# code for the difference between the source and target documents. For more detailed information, please refer to: forum discussion thread.TOP

7.    How to populate a spreadsheet with data from a real SQL database and create a cool looking chart based on that data

Blog post link.TOP

8.    How to generate TOC (table of contents) in Word document?

Open XML SDK 2.0 does not have this feature supported. But you can generate a small TOC through Word app, and reflect the TOC parts with Document Reflector component in Open XML SDK Productivity Tool to see how to generate a TOC programmatically. For more detailed information, please refer to: forum discussion thread 1,forum discussion thread 2.TOP

9.    How to update TOC (table of contents) dynamically in Word document?

Creating a TOC requires layout engine in order to determine page numbers, but SDK does not perform such layout functionality. There is a workaround here to let Word update the TOC for you. For more detailed information, please refer to: forum discussion thread.TOP

10.    How to apply heading styles in Word using SDK 2.0?

To apply a heading style on specific text, the document should contain a styles part with a heading definition. We suggest using the Tool to see how to do this. For more detailed information, please refer to: forum discussion thread.TOP

11.How to search for the Content Controls inside the Word file with SDK 2.0?

To search for the content controls inside a Word file, you should use SdtElement instead of SdtBlock. SdtElement will match all content controls (run, block, etc.). It could be that the Content Control inside table is not SdtBlock. For more detailed information, please refer to:forum discussion thread.TOP

12.How to add a watermark to a Word document?

It is suggested to make use of the Productivity Tool. You could create an empty docx document and save it, such as source.docx. Add a watermark to the empty docx and save it as target.docx. Use "Compare Files"-> "View/Hide Code" to see the generated code. For more detailed information, please refer to:forum discussion thread.TOP

13.How to generate document from database based on document template?

Blog post link.TOP

14.How to merge several documents into one document by using AltChunk?

Blog post link.TOP

15.How to embed custom data in the custom XML part in to Word document by using content control?

Blog post link.TOP

16.    How to retrieve the text content of a Word document?

To retrieve the text of a word document, you need to be clear about the file format, usually the text content is under Pragraph\Run\Text element. For more detailed information, please refer to: forum discussion thread. TOP

17.    How to add a new CustomXml part a Word document?

To add a new CustomXmlPart, you should specify the CustomXmlPartType, which is different from the API in Open XML SDK V1. For more detailed information, please refer to: forum discussion thread. TOP

18.How to add rows to PowerPoint table?

Adding rows to PowerPoint table is complex. You could make use of the Productivity Tool to generate the code. For more detailed information, please refer to:forum discussion thread.TOP

19.How to merge multiple PPT slides?

Blog post link.TOP

20.How to find Open XML errors with Open XML SDK Validation?

Blog post link.TOP

21.Is there a Java version of Open XML SDK?

No, currently there is no Microsoft version of the Open XML SDK that works with Java. Open XML SDK should be used on .NET platform. There is no raw C API or COM for the SDK available, too. You can use the Open XML SDK via C# or VB.NET on the .NET platform. For more detailed information, please refer to:forum discussion thread.TOP

22.Can I convert Open XML file format to HTML using SDK 2.0?

No. Format conversion (e.g. converting Open XML file format from/to HTML, RTF, WordOpenXML, XML, etc.) is not covered in Open XML SDK 2.0.

To solve this problem, we suggest using Word Automation Service, which will allow you to convert Word documents to html on the server, without having Word installed. In the meanwhile Eric White is working on a docx to xhtml transformation built on top of the SDK:blog post link.

For more detailed information about file format conversion, please refer to:forum discussion thread 1,forum discussion thread 2 and forum discussion thread 3.TOP

23.Can I protect/add passwords to a Word document using SDK 2.0?

No. The current design of the SDK cannot decode an encrypted OOXML package or add passwords to/encrypt OOXML documents. You may leverage automation or server-side service to implement this requirement or refer to System.IO.Packaging. Open XML SDK only support features to protect a document such as preventing the sheet from being edited in UI. For detailed information, please refer to: forum discussion thread.TOP

24.Can I open a password protected Excel file using SDK 2.0?

No, Open XML SDK doesn’t support protected files. The SDK always throws exceptions for files that are protected by password and said they are corrupt documents. For more detailed information, please refer to: forum discussion thread.TOP

25.Can I add digital signature to a Word document using SDK 2.0?

No. Open XML SDK doesn’t support features like generating digital signature, encryption/decryption of a file.TOP

26.Can I open a signed document using SDK 2.0?

Yes. You can open a signed document with Open XML SDK 2.0. But it does NOT support verifying the signature. Besides, if you make changes to the content part of the document, the digital signature part will not be automatically updated and thus it is NOT guaranteed to open it using Client OM successfully.TOP

27.Can I add or run macro in Word document using SDK 2.0?

No, Open XML SDK doesn’t support macro. It is a collection of classes that let you create and manipulate Open XML documents.TOP

28.Can I insert building blocks with the SDK?

No. Open XML SDK 2.0 doesn’t support such high level features as building blocks. The Open XML SDK isNOT a replacement for the Office Object Model; and provides no abstraction on top of the file formats. You need to understand the structure of the file formats to leverage the SDK; it doesn't hide it from you. TOP

29.Can I run formula calculation with SDK 2.0?

No. The Open XML SDK is a collection of classes that let you create and manipulate Open XML documents. It isNOT a replacement for the Office Object Model. It does NOT provide application behaviors such as layout (ex. pagination of WordprocessingML documents), formula calculation (which is very common in Excel) or recalculation functionality.TOP

30.Can I calculate the size of a paragraph with SDK 2.0?

No. Calculating the size of a paragraph is some kinds of layout application behavior which Open XML SDK doesn’t support. For detailed information, please refer to Q29. TOP


Change font color of text in CellValue in Excel - OpenXml

$
0
0

How i can change text color of CellValue in excel, i am able to change forgeround color of Cell but it changes color of all text present inside the cell which i dont want , i want to highlight only particular Text in side the Cell i.e CellValue text.

Example - if a cell contains "Microsoft is great" , i want to only highlight Microsoft not whole cell.

I am using below code to highlight Cell Text as , how it can be done for CellValue ? -

foreach(DocumentFormat.OpenXml.Spreadsheet.Cell currentCell in allCells){Fill fill =newFill(){PatternFill=newPatternFill{PatternType=PatternValues.Solid,ForegroundColor=newForegroundColor(){Rgb="FFFF00"}}};
    styleSheet.Fills.AppendChild(fill);//Adding the  CellFormat which uses the Fill element CellFormats cellFormats = styleSheet.CellFormats;CellFormat cf =newCellFormat();
    cf.FillId= styleSheet.Fills.Count;
    cellFormats.AppendChild(cf);
    currentCell.StyleIndex= styleSheet.CellFormats.Count;}

I dont see any property of Style in CellValue

CellValue currentCellValue = currentCell.GetFirstChild<CellValue>();if(currentCell.DataType==CellValues.SharedString)// cell has a cell value that is a string, thus, stored else where{
             data = doc.WorkbookPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault().SharedStringTable.ElementAt(int.Parse(currentCellValue.Text)).InnerText;}

Documents merge issue

$
0
0

Hello experts,

I'm using below code to merge multiple documents. But, after merging, I see some issues in the merged document. 

 public static void MergeDocuments(List<string> documentPaths, string outputFile)
        {
            if (System.IO.File.Exists(outputFile))
                System.IO.File.Delete(outputFile);

            string firstDoc = documentPaths.First();
            System.IO.File.Copy(firstDoc, outputFile);

            documentPaths.RemoveAt(0);

            using (WordprocessingDocument myDoc = WordprocessingDocument.Open(outputFile, true))
            {
                foreach (var documentPath in documentPaths)
                {
                    string altChunkId = string.Format("AltChunkId{0}", Guid.NewGuid().ToString());
                    MainDocumentPart mainPart = myDoc.MainDocumentPart;

                    AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(
                        AlternativeFormatImportPartType.WordprocessingML, altChunkId);
                    using (FileStream fileStream = File.Open(documentPath, FileMode.Open))
                        chunk.FeedData(fileStream);
                    AltChunk altChunk = new AltChunk();
                    altChunk.Id = altChunkId;

                    Paragraph para = new Paragraph(new Run((new Break() { Type = BreakValues.Page })));

                    mainPart.Document.Body.InsertAfter(para, mainPart.Document.Body.LastChild);
                    mainPart.Document.Body.InsertAfter(altChunk, mainPart.Document.Body.LastChild);
                    mainPart.Document.Save();
                }
            }
        }

The second document I merge has some abnormal line spacing issues in the merged document. It adds extra space after each of the paragraphs. Even the lines in a table also get space after them. If you kindly review the documents, you will notice the issues.

I have uploaded 3 documents in the onedrive account.

Doc 1: https://1drv.ms/w/s!AmifSn8Lhbgbg24v61BIYPjJvTt-

Doc 2: https://1drv.ms/w/s!AmifSn8Lhbgbg2wv61BIYPjJvTt-

Merged: https://1drv.ms/w/s!AmifSn8Lhbgbg20v61BIYPjJvTt-

I have merged "Doc 1.docx" and "Doc 2.docx". The output is merged.docx. You can run below code to merge them.

static void Main()
        {
            var list = new List<string>();
            list.Add(@"C:\temp\doc 1.docx");
            list.Add(@"C:\temp\doc 2.docx");

            string output = @"C:\temp\merged.docx";
            MergeDocuments(list, output);
        }

Any help on solving the issues will be highly appreciated.

Thanks in advance.

How to read Multilevel Numbering format in Word 2007 document?

$
0
0

Hi,

How to read Multilevel Numbering format using OpenXML SDK  and also is there any relation between the parent and child sequence like 4-->4.1-->4.1.1 and 4.1.2


Selvam S

Unlock and lock a Word document for form protection without password

$
0
0

Hi

I want to be able to unlock and lock a Word document which has forms protection without a password.
All information I find on the subject involvs setting a password which makes it very complicated.

My customer wants form protected Word documents for user convenience, not security reasons.

How is this done with Open XML 2.5?


Best Regards Peter Karlström Midrange AB, Sweden

OpenXML mailmerge header problem when printing

$
0
0

Hello,

I have a problem with the openXML when I replace all my mailmerges by the value.

After I do a mailmerge, At a first look all is fine : The values are correct on the screen...
When I want to print, in the main document, all is fine, but on the header, all the parameters fields are put back to a mergefield instead of the value.

Here is how I do the replace of the value

For example if I have a variable with PrjName.

In the maindocument, PrjName is replaced by TestPrj.

In the header, prjName is also replaced by TestPrj (that is great, exactly what I need.

The problem is that as soon as I do a Print in Office 2010, the document is modified on the preview and on the maindocument, PrjName still has the correct value (TestPrj), but on the header (and footer too), the variavle PrjName is put back to PrjName instead of the value.

Can you please help me?

Thank you

Marc

Private Shared Sub ReplaceMergeFieldield(ByVal RootPart As OpenXmlPartRootElement, ByVal fieldname As String, ByVal fieldValue As String)
        For Each run As Run In RootPart.Descendants(Of Run)()
            For Each txtFromRun As Text In run.Descendants(Of Text)().Where(Function(a) a.Text = "«" & Convert.ToString(fieldname) & "»")

                txtFromRun.Text = fieldValue

            Next
        Next
    End Sub

How to make Visual Basic read the values in the cell, not the formula

$
0
0

Hi everybody,

I am trying to make Visual Basic read out the Value in a cell and turn an object according to this Value. The problem is that I have it pointing towards a Cell that contains a formula in order to calculate the exact value. Copy of the code:

Private Sub Worksheet_Change(ByVal Target As Range)

ActiveSheet.Shapes.Range(Array("Group 179")).Select
Selection.ShapeRange.Rotation = Range("C2").Value * 240


End Sub

Object 179 is supposed to turn between 0 - 240 degrees based on the value in cell C2, only this one calculates a percentage of completion.

Copying slides between presentations and applying destination presentations master part

$
0
0
We are copying slides from one presentation to another using logic given at http://msdn.microsoft.com/en-us/library/office/ee361883(v=office.12).aspx. This adds a new slide master part for every slide from the source. Instead we want to be able to add slides and inherit the slide master of the destination presentation just as it happens when we copy and paste the slide manually. We should also be add the slide layout part of source slide if does not already exist in the destination slide master. Any pointers would be really helpful.

How to Reading XMl File in Micros and insert this attribute in xml dynamic table in word

$
0
0

I have XML file.

I would like to write a Macro program to read values from XML file and insert them into Word file as a dynamic table 

What is a recommended solution?

Thanks.

Extract table of contents from Word Docx

$
0
0

How can we extract only Table of Contents from Word Document?

We were able to successfully extract paragraph from documents, but not able to extract just Table of Contents.

Regards

Get series number from word document

$
0
0

I have document with below mentioned data ....

1.Definitions and Interpretation

1.1Definitions

2.The Facilities

2.1The Facilities

How can we extract the above from word document - with the series number...

I can get the para content but how to get 1.., 1.1.... 2... with the text. I'm not able to



Extract properties of Word Document

$
0
0

Below code works fine, and give us the STYLE properties. How can we fetch other properties also like - numbering, font size, italics/bold, indentation?

const string fileName = @"D:\DocFiles\Scan.docx";
            const string documentRelationshipType = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument";
            const string stylesRelationshipType = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles";
            const string wordmlNamespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
            XNamespace w = wordmlNamespace;
            XDocument xDoc = null;
            XDocument styleDoc = null;

            using (Package wdPackage = Package.Open(fileName, FileMode.Open, FileAccess.Read))
            {
                PackageRelationship docPackageRelationship =
                  wdPackage
                  .GetRelationshipsByType(documentRelationshipType)
                  .FirstOrDefault();
                if (docPackageRelationship != null)
                {
                    Uri documentUri =
                        PackUriHelper
                        .ResolvePartUri(
                           new Uri("/", UriKind.Relative),
                                 docPackageRelationship.TargetUri);
                    PackagePart documentPart =
                        wdPackage.GetPart(documentUri);

                    //  Load the document XML in the part into an XDocument instance.  
                    xDoc = XDocument.Load(XmlReader.Create(documentPart.GetStream()));

                    //  Find the styles part. There will only be one.  
                    PackageRelationship styleRelation =
                      documentPart.GetRelationshipsByType(stylesRelationshipType)
                      .FirstOrDefault();
                    if (styleRelation != null)
                    {
                        Uri styleUri = PackUriHelper.ResolvePartUri(documentUri, styleRelation.TargetUri);
                        PackagePart stylePart = wdPackage.GetPart(styleUri);

                        //  Load the style XML in the part into an XDocument instance.  
                        styleDoc = XDocument.Load(XmlReader.Create(stylePart.GetStream()));
                    }
                }
            }

            string defaultStyle =
                (string)(
                    from style in styleDoc.Root.Elements(w + "style")
                    where (string)style.Attribute(w + "type") == "paragraph" &&
                          (string)style.Attribute(w + "default") == "1"
                    select style
                ).First().Attribute(w + "styleId");

            // Find all paragraphs in the document.  
            var paragraphs =
                from para in xDoc
                             .Root
                             .Element(w + "body")
                             .Descendants(w + "p")
                let styleNode = para
                                .Elements(w + "pPr")
                                .Elements(w + "pStyle")
                                .FirstOrDefault()
                select new
                {
                    ParagraphNode = para,
                    StyleName = styleNode != null ?
                        (string)styleNode.Attribute(w + "val") :
                        defaultStyle
                };

            // Retrieve the text of each paragraph.  
            var paraWithText =
                from para in paragraphs
                select new
                {
                    ParagraphNode = para.ParagraphNode,
                    StyleName = para.StyleName,
                    Text = ParagraphText(para.ParagraphNode)
                };

            foreach (var p in paraWithText)
            {
                    Response.Write(p.StyleName + " -" + p.Text);
             }

Extending WMLtoHTML converter

Viewing all 1288 articles
Browse latest View live


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