我尝试使用以下Perl代码,但工作表不会复制(也不会移动),也不会返回错误消息。提前感谢您的想法。
#!/usr/bin/perl -w
use strict;
use warnings;
use OLE;
use Win32::OLE::Const 'Microsoft Excel';
my $Excel = CreateObject OLE "Excel.Application";
my $Book2 = $Excel->Workbooks->Add();
my $Book3 = $Excel->Workbooks->Open("C:\\temp\\test.xlsm");
my $Sheet3 = $Book3->Worksheets(1);
$Sheet3->Select;
$Sheet3->Move("Before" => $Book2->Worksheets(1));
$Book3->Close(0);
$Book2->SaveAs({Filename =>"C:\\temp\\new.xlsm",FileFormat => xlOpenXMLWorkbookMacroEnabled});
$Book2->Close();
$Excel -> Quit();
答案 0 :(得分:1)
如果您需要在Excel中出错,则需要将相关标志设置为3(与Office 2000一起使用):
$Win32::OLE::Warn = 3; # Die on errors in Excel
更基本的问题可能与您的Office版本有关。自从(我相信)Office 2007以来,底层的OLE体系结构已经彻底改变了。我在与Office 2007一起开发的脚本拒绝与Office 2000一起运行时,我曾经面对这个问题。
我建议的最好的操作方法是在VBA模式下按 F2 键,使用Excel(相当令人困惑的)OLE浏览器。
Perl + OLE + Excel的'Hello,World'(适用于Excel 2000):
use strict;
use warnings;
use Win32::OLE qw/in with/;
use Win32::OLE::Const 'Microsoft Excel';
$Win32::OLE::Warn = 3; # Die on errors in Excel
my $excel = Win32::OLE->GetActiveObject('Excel.Application')
|| Win32::OLE->new('Excel.Application', 'Quit');
my $workbook = $excel->Workbooks->Add || warn "Couldn't add a workbook";
my $sheet = $excel->Worksheets->Add || warn "Couldn't add a worksheet";
$sheet->{Name} = "Hello World";
答案 1 :(得分:1)
我在这里使用复制/粘贴在大的单元格范围内找到了解决方法。这种方法可能通过以编程方式识别活动单元格而不是硬编码来改进,这可能会导致在不同版本的Excel之间进行时出现一些问题。
#!/usr/bin/perl -w
use strict;
use warnings;
use Win32::OLE qw/in with/;
use Win32::OLE::Const 'Microsoft Excel';
$Win32::OLE::Warn = 3; # Die on errors in Excel
my $Excel = Win32::OLE->GetActiveObject('Excel.Application')
|| Win32::OLE->new('Excel.Application', 'Quit');
$Excel -> {"Visible"} = 0;
$Excel -> {"DisplayAlerts"} = 0;
my $Book2 = $Excel->Workbooks->Add();
my $Book3 = $Excel->Workbooks->Open("C:\\temp\\test.xlsm");
$Book3->Worksheets(1)->Range("A:AM")->Copy;
$Book2->Worksheets(1)->Range("A:AM")->PasteSpecial;
$Book3->Close(0);
$Book2->SaveAs({Filename =>"C:\\temp\\new.xlsm",FileFormat => xlOpenXMLWorkbookMacroEnabled});
$Book2->Close();
$Excel->Quit();