Search code examples
c#xmlexcelexcel-interopnpoi

Programmatically export Excel files to XML using xmlMaps


With the Excel addin OfficeExcel2003XMLToolsAddin I've been able to define XML mapping for an Excel Worksheet (this addin converts a range to a XML list) and now I'm able to manually save the Excel file as a XML file, using Save as.

Excel correctly produces something like

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Row>
        <brand>Brand1</brand>
        <Italian>Description1</Italian>
        <English>Description2</English>
    </Row>
    <Row>
        <brand>Brand2</brand>
        <Italian>Description3</Italian>
        <English>Description4</English>
    </Row>
</Root>

Now, I would like to programmatically do the same (hopefully using c#, .NET 4.0).

I tried using npoi and Microsoft Office Interop Excel, using this code

Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
xlApp.Workbooks.OpenXML(@"excelFile.xls");
xlApp.Workbooks[1].SaveAs(xmlFile, XlFileFormat.SOME_FORMAT);

trying with all the enumerations listed on XlFileFormat reference page, with no success.

Any suggestions? Thanks


Solution

  • This should work

    Application app = new Application();
    app.Workbooks.Open(@"C:\Sample.xlsx",
                       Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                       Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                       Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                       Type.Missing, Type.Missing);
    string data = string.Empty;
    app.ActiveWorkbook.XmlMaps[1].ExportXml(out data);
    app.Workbooks.Close();
    

    data should contain XML