Search code examples
c#openxmlnpoi

How to change Application in app.xml (XSSF) with NPOI?


Unzipping an .xlsx generated with NPOI I noticed that NPOI set itself as "Application" in docProps/app.xml and also added "Generator" to docProps/custom.xml.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties" xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes">
    <Application>NPOI</Application>
    <AppVersion>123.456</AppVersion>
</Properties>

How do I edit the Application information in app.xml?

I only found CoreProperties, CustomProperties and ExtendedProperties, but nothing called "AppProperties".


Solution

  • You need to get the underlying properties from the ExtendedProperties and then set the Application property of that. The following example sets the Application and AppVersion:

    static void Main(string[] args)
    {
        XSSFWorkbook workbook = new XSSFWorkbook();
        ISheet sheet1 = workbook.CreateSheet("Sheet1");
    
        POIXMLProperties props = workbook.GetProperties();
    
        //get the underlying properties (of type NPOI.OpenXmlFormats.CT_ExtendedProperties)
        var underlyingProps = props.ExtendedProperties.GetUnderlyingProperties();
        //now set the properties (excuse the vanity!)
        underlyingProps.Application = "petelids";
        underlyingProps.AppVersion = "1.0";
    
        FileStream sw = File.Create("test.xlsx");
        workbook.Write(sw);
        sw.Close();
    }
    

    Generator properties

    Example of changing the Generator in CustomProperties (custom.xml).

    CustomProperties customProperties = properies.CustomProperties;
    customProperties.AddProperty("Generator", "petelids");
    customProperties.AddProperty("Generator Version", "1.0");