[英]Why am I getting an exception when I try to set the value of a cell in Excel using Perl's Win32::OLE?
[英]I try to modify an Excel using Perl and Win32::Ole
我為此而苦苦掙扎,並且有很多文章介紹了它應該如何工作,但是我沒有成功:
我的系統是安裝並激活Office 2016的Windows 7。 我想使用Excel文件作為模板進行修改並將其保存到新位置。 這是我的代碼:
sub ExcelWriter {
my $Template = "../templates/template.xls";
my $ExcelFile = $MyOutDir."New_Excel_File.xls";
my $Excel = new Win32::OLE('Excel.Application');
if (-f $Template) {
my $WorkBook = $Excel->Workbooks->Open($Template);
my $WorkSheet = $WorkBook->Worksheets('Overview');
$WorkSheet->Cells(5,3)->{Value} = $Customer;
$WorkBook->SaveAs($ExcelFile);
$WorkBook->Close();
undef $WorkBook;
undef $Excel;
}
}
我收到“ Can't call method "Worksheets" on an undefined value at...
”當我使用“ Workbooks->Add
”和“ Worksheets->Add
”創建新工作簿時,可以編寫單元格。 即使選擇工作表也可以在這里工作!
對於專家來說,這似乎很明顯,但是我一定在這里錯過了一些東西。 我已經將工作簿從“ .xlsx”保存到“ .xls”,並刪除了所有公式等,甚至創建了一個新的空白工作簿!
謝謝您的幫助
問候勞倫特
我將代碼修改為(使用原始的“ .xlsx”文件):
sub ExcelWriter {
my ($Volume, $Directory, $File) = File::Spec->splitpath(__FILE__);
my $Template = $Volume.$Directory.'..\templates\template.xlsx';
my $ExcelFile = $MyOutDir.'New_Excel_File.xlsx';
my $Excel = new Win32::OLE('Excel.Application');
my $WorkBook = $Excel->Workbooks->Open($Template);
my $WorkSheet = $WorkBook->Worksheets('Overview');
$WorkSheet->Cells(5,3)->{Value} = $Customer;
$WorkBook->SaveAs($ExcelFile);
$WorkBook->Close();
undef $WorkBook;
undef $Excel;
}
...而且效果很好!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.