2

使用 c# openxml - 我正在尝试打开一个 excel 文件,绑定到它的 connection.xml 流,并更新嵌入式 SQL 查询。我能够使用连接/命令节点成功替换单个字符序列,但尝试显式设置命令属性(即 node.Attribute["command"].Value = select * from ....)会导致损坏

xmlDoc.Load(wkb.WorkbookPart.ConnectionsPart.GetStream());

csNode = xmlDoc.SelectSingleNode("*/*/*[@connection]");

csNode.Attributes["command"].Value = Regex.Replace(csNode.Attributes["command"].Value,        @"\(\[\w*\].\[\w*\].\[\w*\].\[\w*\].*\)", "(" + subQry + ")", RegexOptions.Multiline);

xmlDoc.Save(wkb.WorkbookPart.ConnectionsPart.GetStream()); 

wkb.Close();
4

1 回答 1

0

不确定这是否是解决此问题的唯一方法,但我能够通过删除原始的 connections.xml 流并创建/附加一个具有正确值的新流到工作簿来纠正它。

 //select connections node from loaded xml Excel
 csNode = xmlDoc.SelectSingleNode("*/*/*[@connection]");

 //store original node values
 oldConnValue = csNode.Attributes["connection"].Value;
 oldCommValue = csNode.Attributes["command"].Value;

 //delete existing ConnectionsPart - to ensure that bleed-over data is not present
 wkb.WorkbookPart.DeletePart(wkb.WorkbookPart.ConnectionsPart);

 //create a replacement ConnectionsPart
 wkb.WorkbookPart.AddNewPart<ConnectionsPart>();

 csNode.Attributes["connection"].Value = oldConnValue; //reassign existing connection value
 csNode.Attributes["command"].Value = baseQry;         //assign new query

 //save changes to stream
 xmlDoc.Save(wkb.WorkbookPart.ConnectionsPart.GetStream());
于 2012-11-14T15:27:30.107 回答