【问题标题】:Excel Range in Word Document Does not keep Formatting after updating linkWord文档中的Excel范围在更新链接后不保持格式
【发布时间】:2017-12-15 14:47:48
【问题描述】:

我有一个 Word 文件,里面有几个来自 excel 文件的链接表。但是,当我更新链接时,文件中的表格不会保留表格格式。

如果我通过 Word 手动操作,格式会保留。

我尝试使用以下代码以编程方式进行:

using Word = Microsoft.Office.Interop.Word;

public void LaunchWord()
{
    WordApp = new Word.Application();
    Document = WordApp.Documents.Open(PathToTemporaryTemplate, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Word.WdOpenFormat.wdOpenFormatAuto, Missing.Value, true, Missing.Value, Missing.Value);
    Fields = Document.Fields;
    Document.UpdateStylesOnOpen = false;
    Document.Activate();
}

然后我尝试像这样更新链接:

public void ChangeLinks(string pathToNewExcel)
{
    var links = Fields.Cast<Word.Field>().AsEnumerable().Where(c => c.LinkFormat != null).ToList();

    foreach (Word.Field field in links)
    {
        //field.LinkFormat.AutoUpdate = false;
        //field.DoClick();
        field.LinkFormat.SourceFullName = pathToNewExcel;
        //field.OLEFormat.Activate();
        field.OLEFormat.PreserveFormattingOnUpdate = true;
        field.LinkFormat.Update();
        //field.LinkFormat.SavePictureWithDocument = true;  
        //field.UpdateSource();
        field.Update();
     }
     Document.Save();
 }

使用 cmets 是我尝试过的所有其他东西,但没有奏效。

感谢任何帮助。

感谢您的宝贵时间!

【问题讨论】:

    标签: c# excel ms-word interop


    【解决方案1】:

    经过很多尝试和问题,我得出了以下解决方案:

    foreach (Word.Field field in links)
    {
        field.Code.Text = field.Code.Text.Replace(oldPath, newPath);
        field.Update();
    }
    

    如何在 Code.Path 属性中精确定位 excel 文件的路径有点棘手,但它会在更新字段后保留所有格式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-06
      • 1970-01-01
      • 1970-01-01
      • 2015-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多