我正在尝试打开一个csv文件,并从其中复制数据,以将其粘贴到已构建的excel(2016)工作簿的选项卡中。
我的问题似乎是在正确访问csv文件。 这是我的代码
use utf8;
use Cwd;
use warnings;
use strict;
use Win32::OLE;
use Win32::OLE qw(in with);
use Win32::OLE::Const "Microsoft Office .* Object Library";
my $Excel = Win32::OLE->GetActiveObject('Excel.Application') || Win32::OLE->new('Excel.Application', 'Quit');
$Excel->{Visible} = 0;
$Excel->{DisplayAlerts}=0;
my $XLSX_LOG_IN = "book1.xlsx";
my $Book_In = $Excel->Workbooks->Open("$XLSX_LOG_IN") or die "Excel Logfile Workbook not opened - Ensure file 'book1.xlsx' is in the working directory\n";
my $csv_in = $Excel->Workbooks->Open("$csv") or die "Excel Logfile Workbook not opened - Ensure file \"$csv\" is in the working directory\n";
my @s_ins = in $csv_in->worksheets;
my $s_in = $s_ins[0];
my $name = $csv_in->Worksheets($s_in)->{Name};
print "$s_in - sheet I'm trying to open\n";
print "$name - sheet I'm trying to open\n";
my $res_sheet = $csv_in -> Worksheets("$name");
my $last_row = $res_sheet -> UsedRange -> Find({What => "*", SearchDirection => 2, SearchOrder => 1}) -> {Row};
my $last_col = $res_sheet -> UsedRange -> Find({What => "*", SearchDirection => 2, SearchOrder => 2}) -> {Column};
my $range = "A1:".$last_col.$last_row;
$res_sheet->range($range)->copy();
my $ResReport = $Book_In -> Worksheets("ModelReserveReport");
$ResReport->range('A1')->Select();
$ResReport->paste();
$csv_in->Close();
我不断收到以下错误 Win32 :: OLE(0.1712)错误0x8002000b:“索引无效”
我认为我不是将excel指向工作表的正确名称,或者我找到了错误地查找最后一行和最后一列的方法,但是我正在努力找出解决方法。 谁能发现我的错误?
答案 0 :(得分:0)
我通过编辑最后6行代码来解决了这个问题
我在源工作表上进行了选择
my $range = "A1:CZ".$last_row;
$res_sheet->range($range)->copy();
并在粘贴我的数据之前删除了选择
my $ResReport = $Book_In -> Worksheets("ModelReserveReport");
$ResReport->paste();
$csv_in->Close();
现在复制/粘贴有效。