我正在尝试在已经存在的 Excel 文件中写入数据,但我尝试的代码是创建一个新工作表并用数据删除旧工作表。这是我使用的代码
#!/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
。另一件事是我需要读取已经存在的特定单元格。
请给我一些指导。谢谢
最佳答案
您无法使用 Spreadsheet::WriteExcel 打开现有电子表格并像这样更新它。您首先要使用 Spreadsheet::ReadExcel 打开它以及使用 WriteExcel
打开的输出表。然后,您读取输入文件,写出现有的单元格、工作表等,并进行您要做的任何编辑/更新/插入。然后,您可以关闭这两个文件,删除以前的文件,然后重命名新文件(可以选择备份以前的版本)。
您只能通过使用Win32::OLE打开它来真正编辑/更改给定的Excel文件,而无需执行此过程。 ,但为此您肯定需要在 Windows 系统上(我不确定 Wine 的状态),而这不是您想要在服务器上执行的操作。
您可以认为使用 Spreadsheet::WriteExcel
创建文件类似于使用 open my $fh, '>', 'output.file'
打开文件... output.file
将被破坏。
注意这一行:
my $fh = FileHandle->new('>'. $self->{_filename});
在Spreadsheet::WriteExcel::Workbook->new
中。
关于perl - 使用 Perl 重写现有 xls 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18330142/