-->

Unable to format Xml for Excel

2019-09-01 03:49发布

问题:

im trying to format an XML-file so that its possible to open it directly using Microsoft Excel.

The problem im having is due to both the default namespace and alias ss: namespace is the same. I can't make excel accept the file otherwise.

When try the code, se below, I get an extra xmlns="" attribute on the WorkSheet node. This makes Excel unable to open the file.

XNamespace nsDefault = "urn:schemas-microsoft-com:office:spreadsheet";
XElement workbook = new XElement(nsDefault + "Workbook", 
    new XAttribute("xmlns", nsDefault),
new XAttribute(XNamespace.Xmlns + "ss", nsDefault));

XElement worksheet = new XElement("Worksheet");
worksheet.SetAttributeValue(nsDefault + "Name", "Shipping");

XElement table = new XElement("Table");

XElement row = new XElement("Row");
XElement cell = new XElement("Cell");
XElement data = new XElement("Data");
data.SetAttributeValue(nsDefault + "Type", "String");
data.Value = "qwerty";

cell.Add(data);
row.Add(cell);
table.Add(row);

worksheet.Add(table);
workbook.Add(worksheet);

workbook.Save(@".\Xml\Test.xml");

Does anyone know how I can get around this?

回答1:

You're better off using the Open XML SDK that Microsoft provides. Get more information about it from here:

http://msdn.microsoft.com/en-us/library/office/hh180830.aspx

http://blogs.msdn.com/b/chrisquon/archive/2009/07/22/creating-an-excel-spreadsheet-from-scratch-using-openxml.aspx