在Perl中读写Excel文件

3

我是一个新手Perl用户。我需要关于在Perl中读写文件的帮助。

让我解释一下情况:例如,我有一个名为input.xls的文件,其中包含字符串、数字和下拉列表。工作表中的一些单元格是锁定的。

我想从input.xls文件中读取数据,并将其写入一个名为output.xls的新文件中。

我遇到的问题是,我无法保留从中读取的文件的格式。

即生成的输出文件不显示下拉列表,而输入文件中锁定的单元格也不出现在输出文件中。

此外,即使是输入文件的格式也会在输出文件中发生变化。例如,如果在输入文件中合并了单元格,则输出文件中的格式不会保持相同。请指导。

以下是我的代码供您参考:

#!/usr/bin/perl -w

use strict;
use Spreadsheet::ParseExcel;
use Spreadsheet::WriteExcel;
use Spreadsheet::ParseExcel::SaveParser;
use CGI;
use CGI::Carp qw(fatalsToBrowser);
print qq[Content-type:text/html \n\n];
my $cs='Book2.xls';
 # Open the template with SaveParser
my $parser   = new Spreadsheet::ParseExcel::SaveParser;
#my $formatter=Spreadsheet::ParseExcel::FmtJapan->new();
my $template = $parser->Parse('e.xls');

my $sheet    = 0;
my $row      = 0;
my $col      = 2;

# Get the format from the cell
my $format   = $template->{Worksheet}[$sheet]
                        ->{Cells}[$row][$col]
                        ->{FormatNo};



# Write data to some cells
$template->AddCell(0, $row,   $col,   1,     $format);
$template->AddCell(0, $row+1, $col, "This is a hello world eg", $format);
#$format->{Lock};
# Add a new worksheet
# $template->AddWorksheet('New Data');

# The SaveParser SaveAs() method returns a reference to a
# Spreadsheet::WriteExcel object. If you wish you can then
# use this to access any of the methods that aren't
# available from the SaveParser object. If you don't need
# to do this just use SaveAs().
#
my $workbook;

{
    # SaveAs generates a lot of harmless warnings about unset
    # Worksheet properties. You can ignore them if you wish.
    local $^W = 0;

    # Rewrite the file or save as a new file
    $workbook = $template->SaveAs('new.xls');

}

# Use Spreadsheet::WriteExcel methods

my $worksheet  = $workbook->sheets(0);
# $worksheet->protect();
#$worksheet->write('A1:B1','=1+2');
#my $locked  = $workbook->add_format();
# $locked->set_locked(1); # A non-op

#my $unlocked = $workbook->add_format();
#$locked->set_locked(0);

# Enable worksheet protection
#$worksheet->protect();

# This cell cannot be edited.
#$worksheet->write('A1:B1', '=1+2', $locked);

$worksheet->write($row+2, $col, "World2");

$workbook->close();
print qq[
<head>
<script> 

</script>
</head>
<body>

<p>The download should start shortly. If it doesn't, click
<a id="downloadLink" href="http://128.9.45.168/~mint/MINT_Portal/macro             /963/cgi/$cs"     download="$cs" target="_blank">here</a>.</p>
</body>
</html>

];
1个回答

1
对于任意的电子表格,保持单元格格式是非常困难的。Spreadsheet::ParseExcel 并不真正理解很多格式(大部分会被忽略)。
你可能会发现,你在一个特定的电子表格上工作得很好,但是你会发现有更复杂的格式的电子表格无法正常工作。
你需要的是能够与 Excel 文档对象模型进行无损交互的东西。(即加载现有电子表格,克隆一些行,更改数据值,删除其他行,保存到不同文件中)。
我发现唯一可靠的代码是 Apache POI,但它只是 Java API。
不幸的是,我最终编写了一堆嵌入在我的 perl 脚本 Inline::Java 里的 Java 管道代码。(虽然也有可以做到这一点的 .NET API,但我使用的是 Linux,而且我从来都无法运行大部分 Office 自动化工具的 MONO+Wine 栈。)
这种方法可行,但实现起来的代码非常复杂。我建议不要尝试 :-)
有没有办法避免使用Perl来完成这个任务?(或者只是这个部分?)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接