mk-j/PHP_XLSXWriterを使う
PHPでExcelファイルを出力できるライブラリ、mk-j/PHP_XLSXWriterを使ってみました。

インストール
公式GitHub のCode ⇒ Download Zipでダウンロードして展開します。
出てきた xlsxwriter.class.php を、php.iniのinclude_pathの通っている場所に配置すれば完了です。

サンプルプログラム
ダウンロードしたZip内に多数のサンプルプログラムがついているので参考になります。 以下は、タブ区切りのテキストファイルを読み、 1行目を見出し行として灰色に塗り、2行目以降をデータ行として、 共に四方に罫線を引いて.xlsxファイルに出力するサンプルです。

<?php
include_once("xlsxwriter.class.php");
$data = file_get_contents("shiten.dat");  // UTF-8形式。SJISなどの場合は変換が必要
$header = [
  "支店コード"=>"string", "支店名称"=>"string", "地域"=>"integer",
  "所在地"=>"string",     "従業員数"=>"integer"
];

$writer = new XLSXWriter();
$writer->writeSheetHeader('Sheet1', $header,
  $col_options = ['border'=>'left,right,top,bottom', 'fill'=>"#DDDDDD", 'widths'=>[10,10,5,40,10]]);
// ↑背景色の設定は#RRGGBB。#は必要

$style = ['border'=>'left,right,top,bottom'];
foreach(explode("\n", $data) as $rowbuf){
    if($rowbuf == ""){ continue; }
    $writer->writeSheetRow('Sheet1', explode("\t", $rowbuf), $style);
}
$writer->writeToFile("./shiten-output.xlsx");

Open Source Web Architecture Top

(first uploaded 2022/07/09 last updated (not ever), MISUMI URANO)