1

使用Spreadsheet::ParseExcel(作为模板)编写了一个 Perl 脚本来解析现有的 Excel 工作簿,并在从我们的数据库中添加更新数据的同时创建新文件。

有没有办法在运行 SaveAs 函数之前更新各个工作表的名称?我想将它们重命名为客户编号,而不是默认的 Sheet1、Sheet2 等。我确实阅读了 PerlDoc 并确实看到有一个get_name()选项,但没有什么可以更改和重新保存的。

任何帮助都会很棒。

4

1 回答 1

1

If you are using SpreadSheet::WriteExcel you can specify the name of the worksheet as the method add_worksheet's first param. This is what the doc says:

$worksheet1 = $workbook->add_worksheet();           # Sheet1
$worksheet2 = $workbook->add_worksheet('Foglio2');  # Foglio2
$worksheet3 = $workbook->add_worksheet('Data');     # Data
$worksheet4 = $workbook->add_worksheet();           # Sheet4

So what you'd want to do is probably something like this:

while (my $res = $dbh->fetchrow_hashref) {
  my $worksheet = $workbook->add_worksheet($res->{'customerName'});
  # do stuff with that sheet
}

Update: Since you're only using Spreadsheet::ParseExcel here's another idea. There's no setter method for the name, so let's take a deeper look to find a workaround.

The code of Spreadsheet::ParseExcel::Worksheet shows us how the name of a workbook-object is stored:

###############################################################################
#
# get_name()
#
# Returns the name of the worksheet.
#
sub get_name {

    my $self = shift;

    return $self->{Name};
}

You can just access the key Name directly via the worksheet-object.

$worksheet->{'Name'} = $res->{'customerName'};

Disclaimer: You should never meddle with internal values of objects, especially if you do not have control over their source. The internal structure may change in a future release, thus breaking your code!

于 2012-09-19T18:13:35.363 回答