使用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();
答案 0 :(得分: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());