[英]read and write excel file in 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>
];
保持單元格的格式(對於某些任意電子表格)將非常困難。 Spreadsheet::ParseExcel 並沒有真正理解那么多的格式(大多忽略它)。
您需要的是與 Excel 文檔對象模型 (DOM)無損交互的東西。 (即加載現有的電子表格,克隆一些行,更改數據值,刪除一些其他行,保存到不同的文件)。
我發現可靠地執行此操作的唯一代碼是Apache POI 。
不幸的是,這是一個 Java API。 我最終使用Inline::Java編寫了一堆嵌入在我的 perl 腳本中的管道代碼(用 Java 編寫)。
這種方法有效,但實現它的代碼非常復雜。 我不鼓勵嘗試:-)
有什么方法可以避免在 perl 中這樣做嗎? (或者只是這部分?)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.