Programmatically export Excel files to XML using x

2019-05-29 19:58发布

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

2条回答
闹够了就滚
2楼-- · 2019-05-29 20:38

Linq to Excel Provider:

http://solidcoding.blogspot.com/2008/01/linq-to-excel-provider-25.html

and then use linq to xml....

查看更多
Luminary・发光体
3楼-- · 2019-05-29 20:50

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

查看更多
登录 后发表回答