简体   繁体   English

Perl将数据从csv复制到Excel工作簿

[英]Perl Copy data from csv to excel workbook

I am trying to open a csv file and copy the data from within it to paste it into a tab in an already constructed excel (2016) workbook. 我正在尝试打开一个csv文件并从其中复制数据以将其粘贴到已经构建的excel(2016)工作簿中的选项卡中。

my problem appears to be accessing the csv file properly. 我的问题似乎是正确访问csv文件。 Here is my code 这是我的代码

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();

I keep getting the following error Win32::OLE(0.1712) error 0x8002000b: "Invalid index" 我不断收到以下错误Win32 :: OLE(0.1712)错误0x8002000b:“无效索引”

I think I am either not pointing excel to the right name of the worksheet or I have the method for finding the last row and column wrong but I'm struggling to work out how to fix either. 我想我不是将excel指向工作表的正确名称,要么是我发现错误的最后一行和最后一列的方法,但是我正在努力找出解决方法。 Can anyone spot my mistake? 谁能发现我的错误?

I fixed this by editiing my last 6 lines of code 我通过编辑我的最后6行代码来解决此问题

I made the selection on the source sheet 我在来源表上进行了选择

my $range = "A1:CZ".$last_row;
$res_sheet->range($range)->copy();

and removed the selection before pasting my data 并在粘贴我的数据之前删除了选择

my $ResReport = $Book_In -> Worksheets("ModelReserveReport");
$ResReport->paste();
$csv_in->Close();

The copy/paste now works. 复制/粘贴现在可以使用了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM