如何在open xml excel 中存储自定义xml数据?

如何在open xml excel 中存储自定义xml数据?

而且不能放在隐藏的cell单元格内,也不能放在隐藏的sheet内,要类似web网站的Application变量,但还不能是VBA和宏之类的,要对用户不可见,但是对开发者可见。


曾经试过两个方法:

1.在styles.xml或sheet1.xml中的Extension (extLst/ext)节点下添加自定义节点,用来存储自己的数据。

具体xml节点如下:

  <extLst>

    <ext uri="{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}" xmlns:x14="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main">

      <x14:slicerStyles defaultSlicerStyle="SlicerStyleLight1"/>

    </ext>

  </extLst>

Worksheet的xml里可以有extLst,stylesheet的xml里也可以有extLst,但Worksheet里的不知道怎么用,常见的是在stylesheet里.

虽然Extension (extLst/ext)节点貌似是供扩展数据使用的,但是当使用excel打开此文件并保存时,此自定义节点因为不是excel内置的内容就被清掉了,不能达到目的。

这个地方始终没搞太明白它究竟能做什么?不能做什么?如果哪位兄弟知道,还盼给讲解一下,下面是msdn上相关的链接: 

ExtensionList Class

Defines the ExtensionList Class.When the object is serialized out as xml, its qualified name is x:extLst.

http://msdn.microsoft.com/en-us/library/office/documentformat.openxml.spreadsheet.extensionlist(v=office.14).aspx 

Extension Class

Extension. When the object is serialized out as xml, its qualified name is x:ext.

http://msdn.microsoft.com/en-us/library/office/documentformat.openxml.spreadsheet.extension.aspx

  

2.使用customed defined xml。

从Open Xml架构图入手,发现Custom Defined XML或许可用,如下图:

 

从msdn的文章 (Custom XML Parts Overview http://msdn.microsoft.com/en-us/library/vstudio/bb608618(v=vs.100).aspx) 中摘到:

"You can embed XML data in documents for some Microsoft Office applications. When you embed XML data in a document, the data is named a custom XML part.

You can create and modify custom XML parts in a document by using an application-level or document-level solution in Visual Studio. You do not need to start the Microsoft Office application to create and modify custom XML parts."

可见,我们是可以把任意内容的xml文件,塞到open xml excel中去,作为一个应用程序级别变量使用,类似web站点的Application变量。

第一步:创建下面这个xml文件或内存,里面只有一个ShowAlert变量:

<?xml version='1.0' encoding='UTF-8' ?>

<Root>

  <Extension1 ShowAlert='false' />

</Root>

第二步:将它load进入open xml excel中。

第三步:在自己的代码中查找已经解析并加载进来的xml内容,找到ShowAlert变量,这就达到目的了。

如果之后另存为excel文件,则open xml的目录结构如下,多了customXml目录,该目录里的item1.xml存放的就是刚才的xml内容。

这里没有贴上第二步,第三步的代码,以后再补吧!

 

推荐资料:

Standard ECMA-376 Office Open XML File Formatsedition (December 2006), 2nd edition (December 2008), 3rd edition (June 2011) and 4th edition (December 2012)

http://www.ecma-international.org/publications/standards/Ecma-376.htm 

OFFICE OPEN XML OVERVIEW

http://www.ecma-international.org/news/TC45_current_work/OpenXML%20White%20Paper.pdf 

Introducing the Office (2007) Open XML File Formats

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

Office Open XML, ECMA-376, and ISO/IEC 29500

http://msdn.microsoft.com/en-us/library/office/gg607163(v=office.14).aspx

What is the best way to store XML data in an Excel file
http://stackoverflow.com/questions/4443026/what-is-the-best-way-to-store-xml-data-in-an-excel-file

posted on 2013-07-10 07:58  BobLiu  阅读(1615)  评论(0编辑  收藏  举报