我尝试编写一个能够从excel中读取的脚本(逐行显示特定列)并检索该值。例如。 A列和C列。搜索了几天后,我只能找到能够从excel中读取所有内容的简单脚本并将其打印出来。
在Excel中
Column A Column B Column C
Dog Cat PIG
Elephant Rat Snake
我现在的代码。
use strict;
use Spreadsheet::ParseXLSX;
use Spreadsheet::WriteExcel;
my $parser = Spreadsheet::ParseXLSX->new();
my $workbook = $parser->parse('C:\Modules\list.xlsx');
if ( !defined $workbook ) {
die $parser->error(), ".\n";
}
for my $worksheet ( $workbook->worksheets() ) {
my ( $row_min, $row_max ) = $worksheet->row_range();
my ( $col_min, $col_max ) = $worksheet->col_range();
for my $row ( $row_min .. $row_max ) {
for my $col ( $col_min .. $col_max ) {
my $cell = $worksheet->get_cell( $row, $col );
next unless $cell;
print "Row, Col = ($row, $col)\n";
print "Value = ", $cell->value(), "\n";
print "Unformatted = ", $cell->unformatted(), "\n";
print "\n";
}
}
}
预期结果:能够检索A列和C列值并将其转换为变量然后我将该变量用于其他目的(将在循环语句中使用它)。
从excel中检索价值(以下是我想要做的概念)
#Loop Start (loop through excel line by line)
$VariableA = Dog(from column A); or ($VariableA =elephant(from column A));
**select from database**
$sql = "select * from animal where name='$VariableA'";
**perform $sql and other functions**
#End Loop
感谢您的帮助,您可以分享给我什么?谢谢!
答案 0 :(得分:0)
尝试以下代码,根据您的要求,我已将值存储在colA和colC中,如下所示:
<强>代码:强>
use strict;
use warnings;
use Spreadsheet::ParseXLSX;
use Spreadsheet::WriteExcel;
my $parser = Spreadsheet::ParseXLSX->new();
my $workbook = $parser->parse('C:\Modules\list.xlsx');
my @columnA = ();
my @columnC = ();
if ( !defined $workbook ) {
die $parser->error(), ".\n";
}
#Get cell value from excel sheet1 row 1 column 2
my $worksheet = $workbook->worksheet('Sheet1');
my ( $row_min, $row_max ) = $worksheet->row_range();
my ( $col_min, $col_max ) = $worksheet->col_range();
for my $row ( $row_min .. $row_max ) {
my $cellA = $worksheet->get_cell( $row, 0 );
# Print the cell value when not blank
if ( defined $cellA and $cellA->value() ne "" ) {
my $value = $cellA->value();
push( @columnA, $value );
}
my $cellC = $worksheet->get_cell( $row, 2 );
if ( defined $cellC and $cellC->value() ne "" ) {
my $value = $cellC->value();
push( @columnC, $value );
}
}
print "First Value of ColumnA is retrieved:";
my $colA = pop(@columnA);
print $colA;
print "\nFirst Value of ColumnC is retrived:";
my $colC = pop(@columnC);
print $colC;