Create Excel .xlsx Files in PHP

Update: This script has been converted into a proper PHP library called MiniSheets that can be installed as a Composer dependency. All instructions below are for the original script.

Excel .xlsx files are actually a set of ZIP compressed XML files (here is the spec). I couldn’t find any examples of building the most basic .xlsx file with PHP so I created this snippet (a local copy) that illustrates the core requirements for a valid XLSX file.

Here are some notes:

  • Requires the PHP ZipArchive extension to actually build the ZIP file.
  • Takes an array of rows which is an array of field values and builds a dictionary of shared strings sharedStrings.xml which are used as a reference in the sheet XML file xlsx_get_sheet_xml().
  • Also includes xml_save() for creating Excel XML files which doesn’t require the PHP Zip extension.

Here is how you would use it:

$fields = array(
	array( 'row 1, col1', 'row 1, col2' ),
	array( 'row 2, col1', 'row 2, col2' ),
);

$excel_builder = new cf7_export_excel();
$excel_builder->add_rows( $fields );

if ( $excel_builder->can_xlsx() ) {
	$excel_file = $excel_builder->xlsx_save();

	header( 'Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=utf-8' );
	header( 'Content-Disposition: attachment; filename=export.xlsx' );
} else {
	$excel_file = $excel_builder->xml_save();

	header( 'Content-Type: text/xml; charset=utf-8' );
	header( 'Content-Disposition: attachment; filename=export.xml' );
}

readfile( $excel_file );
unlink( $excel_file );

I used the PHP_XLSXWriter library as a reference.

3 Comments

  1. Andrew says:

    The only lib ever needed — https://github.com/PHPOffice/PHPExcel

    Quite bulky but reliable and universal reader/writer for all the xls(x) variations.

  2. That’s very nice, Kaspars. Thank you for releasing the code and writing this post to explain it.

    As Andrew also commented, I have also been using PHPExcel. Not entirely without issues, but it did the job.

    • Kaspars says:

      Yeah, the example is more of a prototype but I decided to publish it anyway because I couldn’t find an existing description of the minimum viable Excel spreadsheet :)

Leave a Reply