使用Office Open XML将XML数据写入Word2007文档表格之二

来源:互联网 发布:淘宝口红代购哪家好 编辑:程序博客网 时间:2024/05/16 03:55

(续上篇)

2.实施

    经过以上测试准备,整个过程的时间消耗,在同等条件下,主要是数据量的多少决定。现在说说Word2007表格的生成。OOXML Word2007主文件的XML格式主要标记从外到内依次是:

  

”Document”“Body”“Table”“TableRow”“TableCell”“Paragraph”“Run”“Text”

 

 

俺的数据需要放在<Text>标记里

首先,定义表格属性,表格线性和线型宽度

TableProperties tblProp = new TableProperties(

   new TableBorders(

      new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 1 },

      new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 1 },

      new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 1 },

      new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 1 },

      new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 1 },

      new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 1 }

  )

);

    

     其次,定义表格单元格宽度属性,并应用到单元格中

TableCell tc1 = new TableCell();

tc1.Append(new TableCellProperties(new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = 1000 }));

 

这些都准备好,进入下一步开始建立表头,读取数据,并找到列名称:

FileStream fs = File.Open("X_Dialog.xml", FileMode.Open);//打开文件

XmlDocument doc = new XmlDocument();

doc.Load(fs);                                           //XMLDocument读取XML文档流

XmlNode colName = doc.GetElementsByTagName("S_Dialog").Item(0); //获取第一个"S_Dialog"XmlNode

XElement root = XElement.Parse(colName.OuterXml.ToString());   //加载成XElement

IEnumerable<XElement> address =

        from el in root.Elements()

        select el;                                         // 使用LinQ to XML 查找所有子元素

 

//XML元素名称建立Word2007

Table table = new Table();

TableRow tr = new TableRow();

foreach (XElement el in address)

 {

       tr.Append(new TableCell(new Paragraph(new Run(new Text(el.Name.LocalName)))));

 }

//将行加入表中

table.Append(tr);

 

表头建立之后就建立数据行,道理是一样的。将Word2007表格建立后,就其加入到Body中,将Body加入到Document

Body body = new Body();

Document worddoc = new Document();

body.AppendChild<Table>(table);

worddoc.AppendChild<Body>(body);

 

最后将Document写入MainDocumentPart

问题:

1.       运行该程序,整个过程耗时约20秒,内存使用高达1.8GCUP利用率达61%,显然不是很理想。

2.       生成的文档数据量大,打开需要大量资源,这个是不可避免的。

3. 生成Word2007文档如图:

 

结果图

 

原创粉丝点击