Perl で Excel
Excel シートの内容を 取得する (ADO)
↓ こんな Excel ファイルを読む
A | B | C | D | E | F | G | H | I | J | |
---|---|---|---|---|---|---|---|---|---|---|
1 | A1 | B1 | C1 | D1 | E1 | F1 | G1 | H1 | J1 | |
2 | A2 | B2 | C2 | D2 | E2 | F2 | G2 | H2 | J2 | |
3 | A3 | B3 | C3 | D3 | E3 | F3 | G3 | H3 | J3 | |
4 | A4 | B4 | C4 | D4 | E4 | F4 | G4 | H4 | J4 | |
5 | A5 | B5 | C5 | D5 | E5 | F5 | G5 | H5 | J5 | |
6 | J6 | |||||||||
7 | A7 | B7 | C7 | D7 | E7 | F7 | G7 | H7 | I7 | J7 |
実行結果
use Win32::OLE;Win32::OLE::CreateObject("ADODB.Connection", $cn);
$cn->{Provider} = "Microsoft.Jet.OLEDB.4.0";
$cn->{ConnectionString} = "Data Source=".$ARGV[0].";Extended Properties=Excel 8.0;";
$cn->{CursorLocation} = 3; # adUseClient
$cn->Open;Win32::OLE::CreateObject("ADODB.Recordset", $rs);
$rs->{Source} = "SELECT * FROM [".$ARGV[1].'$]';
$rs->{ActiveConnection} = $cn;
$rs->{CursorType} = 0; # adOpenForwardOnly
$rs->{LockType} = 1; # adLockReadOnly
$rs->Open;while (!$rs->EOF)
{
@rec = ();
foreach $col ($rs->Fields)
{
push @rec, $col->Value;
}
print join(",", @rec), "\n";$rs->MoveNext();
}$rs->Close;
$cn->Close;
エラーには、ならないが、何も出力されないので、ちょいと変更
C:\>perl c:\study\perl\chapter004\lesson008.pl c:\study\Book1.xls Sheet1
実行結果
use Win32::OLE;Win32::OLE::CreateObject("ADODB.Connection", $cn);
$cn->{Provider} = "Microsoft.Jet.OLEDB.4.0";
$cn->{ConnectionString} = "Data Source=".$ARGV[0].";Extended Properties=Excel 8.0;";
$cn->{CursorLocation} = 3; # adUseClient
$cn->Open;Win32::OLE::CreateObject("ADODB.Recordset", $rs);
$rs->{Source} = "SELECT * FROM [".$ARGV[1].'$]';
$rs->{ActiveConnection} = $cn;
$rs->{CursorType} = 0; # adOpenForwardOnly
$rs->{LockType} = 1; # adLockReadOnly
$rs->Open;while (!$rs->EOF)
{
@rec = ();
foreach $iCol (0..$rs->Fields->Count - 1)
{
push @rec, $rs->Fields($iCol)->Value;
}
print join(",", @rec), "\n";$rs->MoveNext();
}$rs->Close;
$cn->Close;
C:\>perl c:\study\perl\chapter004\lesson008.pl c:\study\Book1.xls Sheet1
A2,B2,C2,D2,E2,F2,G2,H2,,J2
A3,B3,C3,D3,E3,F3,G3,H3,,J3
A4,B4,C4,D4,E4,F4,G4,H4,,J4
A5,B5,C5,D5,E5,F5,G5,H5,,J5
,,,,,,,,,J6
A7,B7,C7,D7,E7,F7,G7,H7,I7,J7