如何使用OLE模块处理Excel?

时间:2013-03-31 18:01:36

标签: perl excel automation spreadsheet ole

朋友们,我编写了一个Perl脚本,将一组CSV文件转换为电子表格 格式使用Spreadsheet::WriteExcel。经过一番研究,我来到了 结论是没有选项可以将列宽固定为自动调整选项。

所以我正在做的是在我使用Win32::OLE打开XLS文件的同一个脚本中 模块,在执行此操作时,我收到了错误消息

Can't use an undefined value as a HASH reference

对应代码是:

# spread sheet creation
my $workbook  = Spreadsheet::WriteExcel->new($file_name);
# ...
my $worksheet = $workbook->add_worksheet($work_sheet_name);
# ...
$worksheet->write($rowNum, $j,$_,$default_format);

在这些步骤之后,我在同一个脚本中有更多行:

my $Excel = Win32::OLE->GetActiveObject('Excel.Application')
    || Win32::OLE->new('Excel.Application');
$Excel->{'Visible'} = 0;    #0 is hidden, 1 is visible
$Excel->{DisplayAlerts}=1;  #0 is hide alerts

# Open File and Worksheet
my $return_file_name="C:\\Users\\admin\\Desktop\\Report_Gen\\$file_name";
print ">>$return_file_name<<";
my $Book = $Excel->Workbooks->Open($return_file_name); # open Excel file
foreach my $Sheet (in $Book->Sheets) {
    my $LastCol = $Sheet->UsedRange->Find({What=>"*", 
        SearchDirection=>xlPrevious,
        SearchOrder=>xlByColumns})->{Column};    # mentioned error is from this line
    my $mylastcol = 'A';
    for (my $m=1;$m<$LastCol;$m++) {$mylastcol++;}
    my @columnheaders = ('A:'.$mylastcol);
    foreach my $range (@columnheaders){
        $Sheet->Columns($range)->AutoFit();
    }

1 个答案:

答案 0 :(得分:2)

  

我编写了一个Perl脚本,使用Spreadsheet :: WriteExcel将一组CSV文件转换为电子表格格式。经过一些研究后,我得出结论,没有选项可以将列宽固定为自动调整选项。

Autofit是Excel中的运行时选项,因此无法使用Spreadsheet :: WriteExcel通过文件格式创建它。

但是,Spreadsheet :: WriteExcel文档包含an example of how to simulate autofit,并解释了所涉及的一些问题。