2013-03-31 46 views
3

朋友们,我写了一个Perl脚本,使用Spreadsheet::WriteExcel将一组CSV文件转换为电子表格 格式。经过一番研究,我得出了 的结论,即没有选择将列宽固定为Auto-fit选项。如何使用OLE模块处理excel?

所以我在做什么是我已经打开使用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(); 
    } 
+0

首先,你可以检查一下,你在使用它之前要查找什么? '$ Sheet-> UsedRange-> Find({...})'< - 你确定这个对象存在吗? – gaussblurinc

+0

代码示例中缺少右卷曲。非常痛苦的看到。请添加它。 (我可以添加它,但我认为实际上可能还有其他代码丢失) –

+0

主循环打开中的'in'关键字看起来很可疑。除非你使用扩展Perl的模块(比如Moose),否则它是无效的。 –

回答

2

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

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

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

+0

你知道yar你能解决上面提到的错误吗? –