2

我正在尝试doc从 DOCX 文件中删除变量。这是我正在使用的代码,但它不会删除任何...

这是完整的代码:

class Program
    {
        static void Main(string[] args)
        {
            string filePath = "C:\\..\\..sample.docx";
            Remove removedocvars = new Remove();
            removedocvars.RemoveDocVariables(filePath);

        }
    }

//method to remove doc vars
  public void RemoveDocVariables(string fileName)
        {
            using (WordprocessingDocument doc = WordprocessingDocument.Open(fileName, true))
            {

                List<DocumentVariables> DocVarsToDelete = doc.MainDocumentPart.RootElement.Descendants<DocumentVariables>().ToList();
                foreach (DocumentVariables dc in DocVarsToDelete)
                {
                    dc.Remove();
                }
                doc.MainDocumentPart.Document.Save();
            }
        }
4

3 回答 3

1

变量位于 settings.xml 文件中,因此您必须使用 MainDocumentPart.DocumentSettingsPart.Settings.Descendants<>()。

public void RemoveDocVariables(string fileName)
{
    using (var doc = WordprocessingDocument.Open(fileName, true))
    {
        doc.MainDocumentPart.DocumentSettingsPart.Settings.RemoveAllChildren<DocumentVariables>();
    }
}
于 2011-08-10T22:18:46.420 回答
0

如果这是您的代码的范围,那么您不会错过对 save 方法的调用吗?

就像是:

    foreach (DocumentVariable dc in DocVarsToDelete)
    {
        dc.Remove();
    } 
    document.Save();
于 2010-12-02T21:43:59.160 回答
0

这是一个已有 6 年历史的问题,但我认为添加答案仍然很有价值。您的问题可能与此有关:

https://github.com/OfficeDev/Open-XML-SDK/issues/198

https://github.com/OfficeDev/Open-XML-SDK/issues/222

在应用上述链接之一中提到的补丁之前,OpenXML 过去不像访问机制的混合。

于 2017-07-26T20:56:50.597 回答