3

How would I go about converting an Excel file to an XML document using C#?

1
  • "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. Commented Jun 23, 2010 at 22:49

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

Actually, for clarity sake: .xlsx is a ZIP file with many xml documents inside it.
Apologies. I need to save the xml to disk after conversion.
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...
1

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);
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.