开发者

Excel to XML in C#

Ho开发者_JAVA百科w would I go about converting an Excel file to an XML document using C#?


You may use the .NET framework to do so. I quick google search got me this example that demonstrates how to read an Excel sheet. Having stored your sheet in an object, you could serialize that object into XML as shown here.


The newer Office formats are XML documents anyway (if your Excel saves as "xlsx" then it's saving as an XML document).

(If that's not enough, you should perhaps explain what kind of XML schema you're looking for.)


I use this method to create XML from a sheet of an Excel (.xlsx) file:

// Using an OleDbConnection to connect to excel
var cs = $@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={excelFile};Extended Properties=""Excel 12.0 Xml; HDR = Yes; IMEX = 2"";Persist Security Info=False";
var con = new OleDbConnection(cs);
con.Open();

// Using OleDbCommand to read data of the sheet(sheetName)
var cmd = new OleDbCommand($"select * from [{sheetName}$]", con);
var ds = new DataSet();
var da = new OleDbDataAdapter(cmd);
da.Fill(ds);

// Convert DataSet to Xml
using (var fs = new FileStream(xmlFile, FileMode.CreateNew))
{
    using (var xw = new XmlTextWriter(fs, Encoding.UTF8))
    {
        ds.WriteXml(xw);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜