none
Excel Style part using openXMl in C# RRS feed

  • Question

  • Hi,

    I have copied the template.xlsx to test.xlsx and i am opening the test.xlsx.

    And i tried to add style part to the test.xlsx .

     var stylesPart =
                        myWorkbook.WorkbookPart.AddNewPart<WorkbookStylesPart>();
                    Stylesheet styles = new CustomStylesheet();
                    styles.Save(stylesPart);

    But it throwing error saying "Only one instance of the type is allowed for this parent.".

    Please explain the solution.

    thanks,

    Elangovan P



    Tuesday, January 3, 2012 2:06 PM

Answers

All replies

  • Hi Elangovan P,

    Thank you for posting.

    I reproduced the scenario on my side and I figured out your problem, the error means that we can't add more than one WorkbookStylePart to the Stylesheet. I tried to modified the code like this:

    using DocumentFormat.OpenXml.Packaging;
    using DocumentFormat.OpenXml.Spreadsheet;
     
    namespace OpenXmlExcelStylePart
    {
        class Program
        {
            static void Main(string[] args)
            {
                string filename = @"test.xlsx";
                using (SpreadsheetDocument xl = SpreadsheetDocument.Open(filename, true))
                {
                    var wsp = xl.WorkbookPart.WorkbookStylesPart;
                    // if the workbookstylespart exists, then delete the original
                    if (wsp != null)
                    {
                        xl.WorkbookPart.DeletePart(wsp);
                    }
                    // add the new workbookstylepart
                    var stylesPart = xl.WorkbookPart.AddNewPart<WorkbookStylesPart>();
                    Stylesheet styles = new Stylesheet();
                    styles.Save(stylesPart);
                }
            }
        }
    }
    

    Hope this can help you and just feel free to follow up after you have tried.

    Best Regards,


    Bruce Song [MSFT]
    MSDN Community Support | Feedback to us
    Thursday, January 5, 2012 7:11 AM
  • Hi Bruce,

    Thanks for your reply. in the above example we are deleting the whole sheet. can we delete only the style part and append new styles?

    thanks,

    Elangovan P

     

    Thursday, January 5, 2012 7:36 AM
  • Hi Elangovan P,

    The sample code doesn't delete the whole sheets, it just delete the workbook style part which is referenced by the worksheets. As far as I know, we can just modify the style part by appending new one or deleting them. You can refer to this thread which I have replied:

    http://social.msdn.microsoft.com/Forums/en-US/oxmlsdk/thread/b32be1bc-2aeb-4de2-ac76-b14290579cf6

    Hope this can help you.

    Best Regards,


    Bruce Song [MSFT]
    MSDN Community Support | Feedback to us
    Friday, January 6, 2012 9:22 AM