簡體   English   中英

Perl將數據從csv復制到Excel工作簿

[英]Perl Copy data from csv to excel workbook

我正在嘗試打開一個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指向工作表的正確名稱,要么是我發現錯誤的最后一行和最后一列的方法,但是我正在努力找出解決方法。 誰能發現我的錯誤?

我通過編輯我的最后6行代碼來解決此問題

我在來源表上進行了選擇

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

並在粘貼我的數據之前刪除了選擇

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

復制/粘貼現在可以使用了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM