【问题标题】:Using Word Interop in C# : wrong text wrapping style after add picture into picture content control在 C# 中使用 Word 互操作:将图片添加到图片内容控件后的文本环绕样式错误
【发布时间】:2018-09-23 11:11:24
【问题描述】:

我对图片内容控件的文本环绕样式有疑问。请按照以下步骤操作:

1/ 我有一个 Word 文档。有一个带有环绕样式的图片内容控件是“方形”

2/ 在 C# 中,我在上面的内容控件中添加了一张图片。这是我的示例代码:

        object missing = System.Reflection.Missing.Value;
        object readOnly = false;
        object isVisible = true;

        object fileName = "C:\\Temp\\Pic.docx";

        var applicationWord = new Microsoft.Office.Interop.Word.Application();

        applicationWord.Visible = true;

        var document = new Microsoft.Office.Interop.Word.Document();
        document = applicationWord.Documents.Open(ref fileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing);

        var contentControlsWithMatchingTag = document.SelectContentControlsByTag("Pic");

        foreach (ContentControl contentControl in contentControlsWithMatchingTag)
        {
            var cc = contentControl.Range.InlineShapes.AddPicture("C:\\Temp\\PType.jpg");
        }



        document.Save();
        applicationWord.Documents.Close();

3/ 结果,环绕样式始终设置为第一个选项“与文本一致”

4/ 在 C# 代码中,如果我在添加图片后尝试更改包装样式:

        foreach (ContentControl contentControl in contentControlsWithMatchingTag)
        {
            var cc = contentControl.Range.InlineShapes.AddPicture("C:\\Temp\\PType.jpg");

            applicationWord.Selection.Range.ShapeRange.WrapFormat.Type = WdWrapType.wdWrapSquare;
        }

它总是引发错误“Type 方法或属性不可用,因为绘图操作无法应用于当前选择。” (这是一个 System.Runtime.InteropServices.COMException)

我使用的是 Win10、VS 2015 和 MS Office 2016

你对我的问题有任何线索吗?

【问题讨论】:

  • 出于好奇,您为什么使用互操作服务?使用互操作我总是发现一些问题,所以建议使用 openXML 之类的东西或类似的东西
  • 内容控件和图片不是一个实体。内容控件包含一个 InlineShape 对象(图片)。如果您使用文本换行对其进行格式化,它将从内容控件中删除图片。您可以在文本框(绘图类型)或单单元格表格中插入内容控件,并使用文本换行对其进行格式化,而内容控件及其图片与文本保持“内嵌”。
  • 您对我提供的信息满意吗?我应该把它写下来作为答案,还是我们应该以“不可重现”来结束这个问题?
  • 嗨 Cindy,你的解决方案救了我。非常感谢

标签: c# ms-word interop office-interop com-interop


【解决方案1】:

var cc = contentControl.Range.InlineShapes.AddPicture("C:\\Temp\\PType.jpg");

替换为

var pic = document.Shapes.AddPicture("C:\\Temp\\PType.jpg");

并改变它

pic.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapSquare;

【讨论】:

  • 如果答案能详细说明为什么这样做会有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多