PHP で Excel

Excel ファイルを 作成する

lesson006.php


<?php
// EXCELインスタンス作成
$excel = new COM("Excel.Application") or die;
$excel->Visible = 1;
$excel->DisplayAlerts = 0;

$bookIn = $excel->Workbooks->Open($argv[1]);
$bookOut = $excel->Workbooks->Add;

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

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

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

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

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

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

$bookIn->Close();
$excel->Quit();
unset($excel);
?>

実行結果

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