如何以编程方式更新embedded式SQL连接的命令属性

使用C#openxml – 我试图打开一个Excel文件,绑定到它的connection.xmlstream,并更新embedded式SQL查询。 我能够成功地用连接/命令节点replace单个字符序列,但试图显式设置命令属性(即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(); 

不知道这是否是解决此问题的唯一方法,但是我可以通过删除原始的connections.xmlstream并使用正确的值创build/附加新的工作簿来纠正。

  //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());