【问题标题】:How to programmatically update the command attribute of an embedded, SQL connection如何以编程方式更新嵌入式 SQL 连接的命令属性
【发布时间】:2012-11-13 18:48:53
【问题描述】:

使用 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();

【问题讨论】:

    标签: c# excel openxml


    【解决方案1】:

    不确定这是否是解决此问题的唯一方法,但我能够通过删除原始 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());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-22
      • 1970-01-01
      • 2010-09-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多