Perl で Excel

Excel ファイルを 作成する

lesson006.pl


use Win32::OLE;

Win32::OLE::CreateObject("Excel.Application", $objExcel) || die "fail! : $!";
$objExcel->{Visible} = 1;
$objExcel->{DisplayAlerts} = 0; #警告メッセージをOFF

$bookIn = $objExcel->WorkBooks->Open($ARGV[0]);
$bookOut = $objExcel->Workbooks->Add;

#いったん、シートを1枚だけにする
for ($iSheet = $bookOut->WorkSheets->Count; $iSheet > 1; $iSheet--)
{
$bookOut->WorkSheets($iSheet)->Delete;
}

for $iSheet (1..$bookIn->WorkSheets->Count)
{
#必要なら、シートを追加する
$bookOut->Sheets->Add(undef, $bookOut->WorkSheets($iSheet - 1)) if ($iSheet > $bookOut->WorkSheets->Count);

$sheetIn = $bookIn->WorkSheets($iSheet);
$sheetOut = $bookOut->WorkSheets($iSheet);

#シート名を変更する
$sheetOut->{Name} = $sheetIn->Name if ($sheetOut->Name != $sheetIn->Name);

#データをコピーする
for $iRow (1..$sheetIn->Cells->CurrentRegion->Rows->Count)
{
for $iCol (1..$sheetIn->Cells->CurrentRegion->Columns->Count)
{
$sheetOut->Cells($iRow, $iCol)->{Value} = $sheetIn->Cells($iRow, $iCol)->Value;
}
}
}

#ブックを保存する
$bookOut->SaveAs($argv[1]);

$bookIn->Close();
$objExcel->Quit();

実行結果

C:\>perl c:\study\perl\chapter004\lesson006.pl c:\study\Book1.xls c:\study\Book2
.xls