C# Word文档中的Excel区域在更新链接后不保留格式
我有一个Word文件,里面有一个excel文件中的几个链接表。但是,当我更新链接时,文件中的表不会保留表格式 如果我通过Word手动执行,格式保持不变 我尝试使用以下代码以编程方式执行此操作:C# Word文档中的Excel区域在更新链接后不保留格式,c#,excel,ms-word,interop,C#,Excel,Ms Word,Interop,我有一个Word文件,里面有一个excel文件中的几个链接表。但是,当我更新链接时,文件中的表不会保留表格式 如果我通过Word手动执行,格式保持不变 我尝试使用以下代码以编程方式执行此操作: using Word = Microsoft.Office.Interop.Word; public void LaunchWord() { WordApp = new Word.Application(); Document = WordApp.Documents.Open(PathT
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();
}
public void ChangeLinks(字符串路径tonewexcel)
{
var links=Fields.Cast().AsEnumerable().Where(c=>c.LinkFormat!=null).ToList();
foreach(链接中的Word.Field)
{
//field.LinkFormat.AutoUpdate=false;
//field.DoClick();
field.LinkFormat.SourceFullName=PathToneXcel;
//field.OLEFormat.Activate();
field.OLEFormat.PreserveFormattingOnUpdate=true;
field.LinkFormat.Update();
//field.LinkFormat.SavePictureWithDocument=true;
//field.UpdateSource();
field.Update();
}
Document.Save();
}
带评论的是我尝试过的所有其他东西,但都不起作用
感谢您的帮助
谢谢你抽出时间 经过多次尝试和提问,我得出了以下解决方案:
foreach (Word.Field field in links)
{
field.Code.Text = field.Code.Text.Replace(oldPath, newPath);
field.Update();
}
如何在Code.path属性中精确定位excel文件的路径有点棘手,但它会在更新字段后保留所有格式