简体   繁体   中英

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

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?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM