perl - 将范围指向表格单元格的末尾
问题描述
在 Perl CGI 中,使用 Win32::OLE,我需要在表格单元格中插入几行文本,但要一行一行地插入。
我使用的不同对象是:
- $go_document , Word 文档
- $lo_table,Word 表
- $li_row和$li_col,表格中的单元格坐标
- @ly_lines,文本数组
这是我的代码,它可以正常工作:
for (my $ii = 0; $ii <= $#ly_lines; $i++)
{
my $lo_range = $lo_table->Cell($li_row, $li_col)->Range;
$lo_range->InsertAfter($ly_lines[$ii]);
$lo_range = $lo_table->Cell($li_row, $li_col)->Range;
$lo_range->InsertParagraphAfter();
}
当我尝试将样式应用于每个文本行时,就会出现我的问题。
由于我不想设置整个单元格的样式,而是要插入的行的样式,所以我尝试了这个(样式存储在@ly_styles数组中):
for (my $ii = 0; $ii <= $#ly_lines; $i++)
{
my $lo_range = $lo_table->Cell($li_row, $li_col)->Range;
$lo_range->Collapse(wdCollapseEnd);
$go_document->Styles->Add($ly_styles[$ii]);
$lo_range->{'Style'} = $ly_styles;
$lo_range->InsertAfter($ly_lines[$ii]);
$lo_range = $lo_table->Cell($li_row, $li_col)->Range;
$lo_range->Collapse(wdCollapseEnd);
$lo_range->InsertParagraphAfter();
}
With this loop, the text lines read in a reversed order and in the cell next to the one I want!
It seems that the Collapse(wdCollapseEnd) command doesn't set the range to the end of the aimed cell, but to the beginning of the next one.
Does anyone know how to fix this? Thanks in advance.
解决方案
You're on the right track.
Immediately after wdCollapseEnd
try moving the range backwards by a character:
$lo_range->MoveEnd(wdCharacter, -1)
The "why" is a bit arcane and I'm not sure if what I imagine is the reason is is correct... What I believe is the reason is that collapsing the Range puts the focus at the beginning of the next cell. Think of it as if the entire cell were selected and pressing right-arrow moved to the next cell instead of at the end of the text in the selected cell. So it's necessary to move back one character (like pressing left-arrow) to get to the end of the original cell.
Range
has MoveEnd
and MoveStart
. Using a positive number with MoveStart
or a negative number with MoveEnd
will effectively move the entire Range
without including additional content. A negative value with MoveStart
or a positive value with MoveEnd
will extand the Range
to include new content. Again, think of it like using the arrow keys, but this time with Shift
held down to extend the selection. There are various parameters (WdUnits
Enumeration) that can be used with these methods that work with objects such as cells, paragraphs, etc. The list can be found in the Word Language Reference.
推荐阅读
- javascript - 动画迭代计数无限循环
- flutter - 如何解决在应用程序中使用 ImagePicker 的错误?
- header - 如何在样式化组件中对重复的标题元素实现 DRY?
- css - 具有弹性基础的CSS网格?
- reactjs - Are callbacks that are passed into other functional components updated on refresh?
- javascript - 获取 oneOf-prop 更改 className、CSS 模块
- python - 如何以相反的顺序找到两个字母之间的长度/间隔?
- elasticsearch - Logstash 更新 Elasticsearch 中的先前文档
- javascript - 如何为 Laravel API 设置 Vue-axios 跨域源?
- variables - 检查 redhat 机器中的多个包是否已经安装,如果不可用,则通过 ansible playbook 安装