---
title: Create Excel .xlsx Files in PHP
date: 2016-05-20T07:30:00+00:00
modified: 2019-06-06T07:51:08+00:00
image:: https://kaspars.net/wp-content/uploads/2016/05/excel-xlsx-numbers.png
permalink: https://kaspars.net/blog/excel-xlsx-xml-php
post_type: post
author:
  name: Kaspars
  avatar: https://reverse.kaspars.net/gravatar/avatar/92bfcd3a8c3a21a033a6484d32c25a40b113ec6891f674336081513d5c98ef76?s=96&d=mm&r=g
category:
  - Development
  - WordPress
post_tag:
  - How to
  - PHP
  - Snippet
---

# Create Excel .xlsx Files in PHP

**Update:** This script has been converted into [a proper PHP library called MiniSheets](https://github.com/kasparsd/mini-sheets-php) that can be installed as [a Composer dependency](https://packagist.org/packages/kasparsd/mini-sheets-php). All instructions below are for the original script.

Excel `.xlsx` files are actually a set of ZIP compressed XML files ([here is the spec](https://msdn.microsoft.com/en-us/library/dd922181(v=office.12).aspx)). I couldn’t find any examples of building the most basic `.xlsx` file with PHP so I created [this snippet](https://gist.github.com/kasparsd/ade34dd94a80b97fb9ec59391a0c620f) ([a local copy](https://kaspars.net/wp-content/uploads/2016/05/php-excel-xlsx-xml.php_.txt)) that illustrates the core requirements for a valid XLSX file.

Here are some notes:

- Requires the [PHP ZipArchive extension](http://php.net/manual/en/class.ziparchive.php) 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](https://en.wikipedia.org/wiki/Microsoft_Office_XML_formats) 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](https://github.com/mk-j/PHP_XLSXWriter) as a reference.