Word文档中的Excel范围更新链接后不保留格式

问题描述 投票:2回答:1

我有一个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();
 }

评论是我尝试过的所有其他内容,但没有用。

任何帮助表示赞赏。

感谢您的时间!

c# excel ms-word interop
1个回答
2
投票

经过大量的尝试和问题,我得出了以下解决方案:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.