【问题标题】:I try to modify an Excel using Perl and Win32::Ole我尝试使用 Perl 和 Win32::Ole 修改 Excel
【发布时间】:2017-10-16 20:50:02
【问题描述】:

我正在为此苦苦挣扎,并且有很多文章显示它应该如何工作,但我没有成功:

我的系统是安装并激活了 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”,并删除了所有公式等......甚至创建了一个新的空白工作簿!

感谢您的帮助

问候 洛朗

【问题讨论】:

  • 我想我刚刚发现了。变量 $Template 使用“../”,它通过 WIN32::OLE 模块重定向到“..AppData\Roaming\Microsoft\Windows”

标签: excel perl win32ole


【解决方案1】:

我将代码修改为(使用原始的“.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;
}

...而且效果很好!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-21
    • 1970-01-01
    相关资源
    最近更新 更多