代码之家  ›  专栏  ›  技术社区  ›  FMc TLP

如何让Perl的电子表格::WriteExcel使用VLOOKUP创建公式?

  •  4
  • FMc TLP  · 技术社区  · 15 年前

    Spreadsheet::WriteExcel 以及使用 VLOOKUP . 以下测试脚本使用一些数据填充工作表,并尝试创建 弗卢库普 公式。打开生成的Excel文件时,公式结果显示为 #VALUE!

    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。
    • 电子表格::WriteExcel:尝试了2.25和2.37。
    2 回复  |  直到 15 年前
        1
  •  7
  •   jmcnamara    15 年前

    这是公式解析器和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) );
    }
    
        2
  •  4
  •   cxn03651    13 年前

    我是WriteExcelRubyGem的维护者。

    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