2010-02-09 97 views
4

我在Spreadsheet::WriteExcel和使用VLOOKUP的公式中遇到了問題。以下測試腳本使用一些數據填充工作表並嘗試創建VLOOKUP公式。當我打開生成的Excel文件時,公式結果顯示爲#VALUE!。如果我手動編輯任何包含公式的單元格(按F2,然後按ENTER鍵而不更改任何內容),我可以使用Excel來正確評估公式。任何想法出了什麼問題?如何獲得Perl的Spreadsheet :: WriteExcel以使用VLOOKUP創建公式?

對於什麼是值得的,如果我在OpenOffice中打開相同的文件,公式工作正常。

use strict; 
use warnings; 
use Spreadsheet::WriteExcel; 

my $wb = Spreadsheet::WriteExcel->new('foo.xls'); 
my $ws = $wb->add_worksheet; 

for my $r (0 .. 9){ 
    for my $c (0 .. 4){ 
     $ws->write($r, $c, $r * 10 + $c); 
    } 
    $ws->write($r, 10, $r * 10); 
    my $formula = sprintf('=VLOOKUP(K%s, A1:B10, 2, FALSE)', $r + 1); 
    $ws->write($r, 11, $formula); 
    # $ws->write_formula($r, 11, $formula); # Does not help either. 
} 

版本信息:

  • 的Excel 2007 SP2。
  • Spreadsheet :: WriteExcel:試過2.25和2.37。
+0

您使用的是什麼版本的'Spreadsheet :: WriteExcel'?您的代碼在OSX上使用Excel在2.25中正常工作。可能只是你的Excel安裝? – 2010-02-09 19:34:03

+0

確實調用了write_formula而不是寫入工作? – ysth 2010-02-09 20:00:17

+0

@ysth和@Jack M.好主意,但沒有運氣。我使用版本信息編輯了問題。 – FMc 2010-02-09 21:00:48

回答

7

我是Spreadsheet :: WriteExcel的作者。

這是公式分析器和WriteExcel中某些公式類型的已知錯誤。您可以使用store_formula()repeat_formula()解決它,如下圖所示:

use strict; 
use warnings; 
use Spreadsheet::WriteExcel; 

my $wb = Spreadsheet::WriteExcel->new('foo.xls'); 
my $ws = $wb->add_worksheet; 

my $formula = $ws->store_formula('=VLOOKUP(K1, A1:B10, 2, FALSE)'); 

# Workaround for VLOOKUP bug in WriteExcel. 
@$formula = map {s/_ref2d/_ref2dV/;$_} @$formula; 

for my $r (0 .. 9){ 
    for my $c (0 .. 4){ 
     $ws->write($r, $c, $r * 10 + $c); 
    } 
    $ws->write($r, 10, $r * 10); 

    $ws->repeat_formula($r, 11, $formula, undef, qr/^K1$/, 'K' . ($r +1)); 
} 
+0

非常感謝。我很感激幫助。 – FMc 2010-02-09 21:55:22

+0

有趣的是,OP報告它在OpenOffice中工作 – ysth 2010-02-10 04:30:29

+0

您能解釋解決方法嗎?我在Ruby中使用WriteExcel - https://github.com/cxn03651/writeexcel並面臨同樣的問題。我想知道在變通方法中發生了什麼,以便我可以在Ruby中對其進行編碼。謝謝 – 2011-06-02 12:48:07

4

我writeexcel ruby​​gem的維護者。例如, ,ruby代碼如下。

require 'rubygems' 
require 'writeexcel' 

wb = WriteExcel.new('fooruby.xls') 
ws = wb.add_worksheet 

formula = ws.store_formula('=VLOOKUP(K1, A1:B10, 2, FALSE)') 

# Workaround for VLOOKUP bug in WriteExcel. 
formula.map! {|f| f.sub(/_ref2d/, '_ref2dV') } 

(0..9).each do |row| 
    (0..4).each { |col| ws.write(row, col, row * 10 + col) } 
    ws.write(row, 10, row * 10) 
    ws.repeat_formula(row, 11, formula, nil, /^K1$/, "K#{row+1}") 
end 

wb.close 
+0

謝謝cxn03651。 – 2011-06-03 07:20:12

相關問題