如何使用Perl修改现有的Excel工作簿?

use*_*033 8 perl xls spreadsheet

有了Spreadsheet::WriteExcel,我可以创建一个新的工作簿,但是如果我想打开现有的书并修改某些列呢?我怎么做到这一点?

我可以解析工作表中的所有数据,Spreadsheet::ParseExcel然后使用,然后使用某些行/列中的新值将其写回Spreadsheet::WriteExcel.有没有一个模块已经结合了这两个?

主要是我只想打开一个.xls,覆盖某些行/列,并保存它.

Eth*_*her 14

Spreadsheet :: ParseExcel将读入现有的excel文件:

my $parser   = Spreadsheet::ParseExcel->new();
# $workbook is a Spreadsheet::ParseExcel::Workbook object
my $workbook = $parser->Parse('Book1.xls');
Run Code Online (Sandbox Code Playgroud)

但你真正想要的是Spreadsheet :: ParseExcel :: SaveParser,它是Spreadsheet :: ParseExcelSpreadsheet :: WriteExcel的组合.文档底部附近有一个示例.


j_r*_*ker 9

如果您安装了Excel,那么使用它几乎是微不足道的Win32::OLE.以下是Win32::OLE自己文档中的示例:

use Win32::OLE;

# use existing instance if Excel is already running
eval {$ex = Win32::OLE->GetActiveObject('Excel.Application')};
die "Excel not installed" if $@;
unless (defined $ex) {
    $ex = Win32::OLE->new('Excel.Application', sub {$_[0]->Quit;})
            or die "Oops, cannot start Excel";
}

# get a new workbook
$book = $ex->Workbooks->Add;

# write to a particular cell
$sheet = $book->Worksheets(1);
$sheet->Cells(1,1)->{Value} = "foo";

# write a 2 rows by 3 columns range
$sheet->Range("A8:C9")->{Value} = [[ undef, 'Xyzzy', 'Plugh' ],
                                   [ 42,    'Perl',  3.1415  ]];

# print "XyzzyPerl"
$array = $sheet->Range("A8:C9")->{Value};
for (@$array) {
    for (@$_) {
        print defined($_) ? "$_|" : "<undef>|";
    }
    print "\n";
}

# save and exit
$book->SaveAs( 'test.xls' );
undef $book;
undef $ex;
Run Code Online (Sandbox Code Playgroud)

基本上,Win32::OLE为您提供VBA或Visual Basic应用程序可用的所有内容,其中包括各种各样的内容 - 从Excel和Word自动化到通过Windows脚本宿主枚举和安装网络驱动器.它已成为ActivePerl最后几个版本的标准配置.