如何使用linq保存** EXCEL ** XML文件?

时间:2012-08-17 17:53:26

标签: xml vb.net linq excel

我正在使用以下blurb加载并保存使用XElement的Excel XML文件:

    Dim root As XElement = XElement.Load(inFile)
    'code to change elements goes here 
    root.Save(outFile)

问题是Save例程正在添加命名空间标记以及谁知道什么,因此Excel和Windows不再将其识别为Excel XML文件。在我的例子中,我甚至没有操纵元素。我只是加载并保存文件。我基本上想用linq来查找XML中的某些元素,然后更改那些然后保存整个文件。我这么做太难了吗?

inFile XML

<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:o="urn:schemas-microsoft-com:office:office"
 xmlns:x="urn:schemas-microsoft-com:office:excel"
 xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:html="http://www.w3.org/TR/REC-html40">
  <Worksheet ss:Name="Datagrid">
    <Table ss:ExpandedColumnCount="13" ss:ExpandedRowCount="11" x:FullColumns="1"
     x:FullRows="1" ss:DefaultRowHeight="15">
      <Row ss:Index="3" ss:AutoFitHeight="0">
        <Cell ecProperty="email_address">
          <Data ss:Type="String">email address</Data>
        </Cell>
      </Row>
      <Row ss:Index="4" ss:AutoFitHeight="0">
        <Cell ecProperty="synthesis_mode">
          <Data ss:Type="String">Ideal Mode</Data>
        </Cell>
      </Row>
    </Table>
  </Worksheet>
</Workbook>

outFile结果

<?xml version="1.0" encoding="utf-8"?>
<ss:Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="http://www.w3.org/TR/REC-html40">
  <ss:Worksheet ss:Name="Datagrid">
    <ss:Table ss:ExpandedColumnCount="13" ss:ExpandedRowCount="11" x:FullColumns="1" x:FullRows="1" ss:DefaultRowHeight="15">
      <ss:Row ss:Index="3" ss:AutoFitHeight="0">
        <ss:Cell ecProperty="email_address">
          <ss:Data ss:Type="String">email address</ss:Data>
        </ss:Cell>
      </ss:Row>
      <ss:Row ss:Index="4" ss:AutoFitHeight="0">
        <ss:Cell ecProperty="synthesis_mode">
          <ss:Data ss:Type="String">Ideal Mode</ss:Data>
        </ss:Cell>
      </ss:Row>
    </ss:Table>
  </ss:Worksheet>
</ss:Workbook>

1 个答案:

答案 0 :(得分:3)

使用XDocument代替XElement来保留完整的文档。

Dim root As XDocument = XDocument.Load(inFile)
'code to change elements goes here 
root.Save(outFile)