2013-08-20 11 views
3

我想在已存在的excel文件中寫入數據,但我嘗試的代碼是創建一個新工作表並使用數據擦除舊工作表。這是我使用的代碼使用Perl重寫現有的xls文件

#!/usr/bin/perl –w 
use strict; 
use Spreadsheet::WriteExcel; 

# Create a new Excel file 
my $FileName = 'Report.xls'; 
my $workbook = Spreadsheet::WriteExcel->new($FileName); 

# Add a worksheet 
my $worksheet1 = $workbook->add_worksheet(); #<- My Doubt 



# Change width for only first column 

$worksheet1->set_column(0,0,20); 

# Write a formatted and unformatted string, row and column 
# notation. 
$worksheet1->write(0,0, "Hello"); 
$worksheet1->write(1,0,"HI"); 
$worksheet1->write(2,0,"1"); 
$worksheet1->write(3,0,"2"); ` 

如何將當前工作表分配到$worksheet1。還有一件事是我需要讀取已經存在的特定單元格。 請給我一些指導。謝謝

回答

4

你不能打開一個現有的電子表格,並且像這樣更新它。您首先要使用Spreadsheet::ReadExcel以及您打開的輸出表打開它,並打開WriteExcel。然後,您讀取輸入文件,寫出現有的單元格,工作表等,並進行任何編輯/更新/插入。然後,您可以關閉這兩個文件,刪除以前的文件,並重命名新文件(可選擇備份以前的版本)。

您只能真正編輯/更改給定的Excel文件,而無需通過使用Win32::OLE打開它,但因爲您肯定需要在Windows系統上(我不確定狀態的葡萄酒),這不是你想要在服務器上做的事情。

你能想到的與Spreadsheet::WriteExcel類似於打開文件與open my $fh, '>', 'output.file'創建文件... output.file被打一頓。

注行:

my $fh = FileHandle->new('>'. $self->{_filename}); 

Spreadsheet::WriteExcel::Workbook->new