How would I go about converting an Excel file to an XML document using C#?
-
"an XML document" is a bit broad - What are you planning to do with this spreadsheet once it is in an XML format? Save it on disk? transform it? Display it? Parse it? Several answers I can think of depend on your usage scenario.Rob Levine– Rob Levine2010-06-23 22:49:34 +00:00Commented Jun 23, 2010 at 22:49
Add a comment
|
3 Answers
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.
Comments
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.)
3 Comments
Aren
Actually, for clarity sake: .xlsx is a
ZIP file with many xml documents inside it.ryan
Apologies. I need to save the xml to disk after conversion.
Dan Puzey
Which Xml? As stated, a (new-version) office file contains an xml document anyway; if you've saved that to disk then you've saved the xml to disk. You still haven't explained what your xml document is expected to contain...
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);
}
}