在perl中读写excel文件

时间:2013-12-16 09:57:34

标签: excel perl

我是最近的Perl用户。我需要一些关于在perl中读取和写入文件的帮助。

让我解释一下这个场景:例如,我有一个input.xls文件,其中包含字符串,数字,下拉列表。 纸张中的某些单元格已被锁定。

我想从input.xls文件中读取数据,并希望将其写入名为output.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 个答案:

答案 0 :(得分:0)

保持单元格的格式非常困难(对于某些任意电子表格)。 Spreadsheet :: ParseExcel并没有真正理解那么多的格式化(大多数都忽略了它)。

您可能会发现所有这些都适用于特定的电子表格,但随后您会发现一个电子表格中包含更复杂的格式,但这种格式无效。

您需要的是无损与Excel文档对象模型(DOM)交互的内容。 (即加载现有的电子表格,克隆一些行,更改数据值,删除其他一些行,保存到另一个文件)。

我发现的唯一可靠的代码是Apache POI

不幸的是,这是一个Java API。我最后使用Inline::Java编写了一堆嵌入在perl脚本中的管道代码(用Java编写)。 (有.NET API也可以这样做,但我在Linux上,我永远无法使用MONO + Wine堆来运行大多数Office自动化程序。)

这种方法很有效,但是将它拉下来的代码非常复杂。我不鼓励尝试: - )

你有什么方法可以避免在perl中这样做吗? (或者只是这一部分?)