In Perl, how can I copy a subset of columns from an XLSX work sheet to another?

左心房为你撑大大i 提交于 2019-12-25 16:56:26

问题


I have a .xlsx file (only one sheet) with 15 columns. I want to read some specific columns, let's say columns 3, 5, 11, 14 and write it to a new Excel sheet. In this case some cells of input files are empty means don't have any value.

Here what I am trying:

use warnings;
use strict;

use Spreadsheet::ParseXLSX;
use Excel::Writer::XLSX;

my $parser = Spreadsheet::ParseXLSX->new;
my $workbook = $parser->parse("test.xlsx");

if ( !defined $workbook ) {
    die $parser->error(), ".\n";
}

my $worksheet = $workbook->worksheet('Sheet1');

# but from here I don't know how to define row and column range to get specific column data.
# I am trying to get all data in an array, so I can write it in new .xlsx file.

# function to write data in new file
sub writetoexcel
{
    my @fields = @_;
    my $workbook = Excel::Writer::XLSX->new( 'report.xlsx' );
    $worksheet = $workbook->add_worksheet();

    my $row = 0;
    my $col = 0;
    for my $token ( @fields )
    {
        $worksheet->write( $row, $col, $token );
        $col++;
    }
    $row++;
}

I also followed this Question, but no luck.

How can I read specific columns from .xlsx file and write it into new .xlsx file?


回答1:


Have you never copied a subset of columns from an array of arrays to another?

Here is the input sheet I used for this:

and, this is what I get in the output file after the code is run:

#!/usr/bin/env perl

use strict;
use warnings;

use Excel::Writer::XLSX;
use Spreadsheet::ParseXLSX;

my @cols = (1, 3);

my $reader = Spreadsheet::ParseXLSX->new;
my $bookin = $reader->parse($ARGV[0]);
my $sheetin = $bookin->worksheet('Sheet1');

my $writer =  Excel::Writer::XLSX->new($ARGV[1]);
my $sheetout = $writer->add_worksheet('Extract');

my ($top, $bot) = $sheetin->row_range;

for my $r ($top .. $bot) {
    $sheetout->write_row(
        $r,
        0,
        # of course, you need to do more work if you want
        # to preserve formulas, formats etc. That is left
        # to you, as you left that part of the problem
        # unspecified.
        [ map $sheetin->get_cell($r, $_)->value, @cols ],
    );
}

$writer->close;


来源:https://stackoverflow.com/questions/29868881/in-perl-how-can-i-copy-a-subset-of-columns-from-an-xlsx-work-sheet-to-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!