简体   繁体   中英

Perl Loop Output to Excel Spreadsheet

I have a Perl script, the relevant bits of which are posted below.

# Pull values from cells
        ROW:
        for my $row ( $row_min + 1 .. $row_max ) {
            my $target_cell   = $worksheet->get_cell( $row, $target_col);
            my $response_cell = $worksheet->get_cell( $row, $response_col);

            if ( defined $target_cell && defined $response_cell ) {
                my $target   = $target_cell->value();
                my $response = $response_cell->value();

# Determine relatedness
                my $value      = $lesk->getRelatedness($target, $response);

# Copy output to new Excel spreadhseet, 'data.xls'
                my $workbook1  = Spreadsheet::WriteExcel->new('data.xls'); 
                my $worksheet1 = $workbook1->add_worksheet();
                $worksheet1->set_column(0, 3, 18);
                my $row = 0;

                foreach ($target) {
                $row++;
                $worksheet1->write( $row, 0, "Target      = $target\n");
                $worksheet1->write( $row, 1, "Response    = $response\n");
                $worksheet1->write( $row, 2, "Relatedness = $value\n");
                }
            }
        }

This script uses the Perl modules ParseExcel and WriteExcel. The input data spreadsheet is a list of words under two columns, one labelled 'Target' and the other labelled 'Response.' The script takes each target word and each response word and computes a value of relatedness between them (that's what the

$lesk->getRelatedness

section of code is doing. It is calling a perl module called WordNet::Similarity that computes a measure of relatedness between words).

All of this works perfectly fine. The problem is I am trying to write the output (the measure of similarity, or $value in this script) into a new Excel file. No matter what I do with the code, the only output it will give me is the relatedness between the LAST target and response words. It ignores all of the rest.

However, this only occurs when I am trying to write to an Excel file. If I use the 'print' function instead, I can see all of the outputs in the command window. I can always just copy and paste this into Excel, but it would be much easier if I could automate this. Any idea what the problem is?

您每次将$ row的值重置为0。

Problem is solved. I just needed to move the

my $workbook1 = Spreadsheet::WriteExcel->new('data.xls'); 
my $worksheet1 = $workbook1->add_worksheet();

lines to another part of the script. Since they were in the 'for' statement, the program kept overwriting the 'data.xls' file every time it ran through the loop.

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