123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785 |
- <?php
- class SimpleXLSX {
-
- const SCHEMA_REL_OFFICEDOCUMENT = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument';
- const SCHEMA_REL_SHAREDSTRINGS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings';
- const SCHEMA_REL_WORKSHEET = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet';
- const SCHEMA_REL_STYLES = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles';
- public static $CF = array(
- 0 => 'General',
- 1 => '0',
- 2 => '0.00',
- 3 => '#,##0',
- 4 => '#,##0.00',
- 9 => '0%',
- 10 => '0.00%',
- 11 => '0.00E+00',
- 12 => '# ?/?',
- 13 => '# ??/??',
- 14 => 'mm-dd-yy',
- 15 => 'd-mmm-yy',
- 16 => 'd-mmm',
- 17 => 'mmm-yy',
- 18 => 'h:mm AM/PM',
- 19 => 'h:mm:ss AM/PM',
- 20 => 'h:mm',
- 21 => 'h:mm:ss',
- 22 => 'm/d/yy h:mm',
- 37 => '#,##0 ;(#,##0)',
- 38 => '#,##0 ;[Red](#,##0)',
- 39 => '#,##0.00;(#,##0.00)',
- 40 => '#,##0.00;[Red](#,##0.00)',
- 44 => '_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)',
- 45 => 'mm:ss',
- 46 => '[h]:mm:ss',
- 47 => 'mmss.0',
- 48 => '##0.0E+0',
- 49 => '@',
- 27 => '[$-404]e/m/d',
- 30 => 'm/d/yy',
- 36 => '[$-404]e/m/d',
- 50 => '[$-404]e/m/d',
- 57 => '[$-404]e/m/d',
- 59 => 't0',
- 60 => 't0.00',
- 61 => 't#,##0',
- 62 => 't#,##0.00',
- 67 => 't0%',
- 68 => 't0.00%',
- 69 => 't# ?/?',
- 70 => 't# ??/??',
- );
- public $workbook_cell_formats = array();
- public $datetime_format = 'Y-m-d H:i:s';
-
- private $workbook;
-
- private $sheets = array();
-
- private $styles;
- private $hyperlinks;
-
- private $package;
- private $datasec;
- private $sharedstrings;
-
- private $error = false;
- private $debug;
- public function __construct( $filename, $is_data = false, $debug = false ) {
- $this->debug = $debug;
- $this->package = array(
- 'filename' => '',
- 'mtime' => 0,
- 'size' => 0,
- 'comment' => '',
- 'entries' => array()
- );
- if ( $this->_unzip( $filename, $is_data ) ) {
- $this->_parse();
- }
- }
- private function _unzip( $filename, $is_data = false ) {
-
- $this->datasec = array();
- if ( $is_data ) {
- $this->package['filename'] = 'default.xlsx';
- $this->package['mtime'] = time();
- $this->package['size'] = strlen( $filename );
- $vZ = $filename;
- } else {
- if ( ! is_readable( $filename ) ) {
- $this->error( 'File not found ' . $filename );
- return false;
- }
-
- $this->package['filename'] = $filename;
- $this->package['mtime'] = filemtime( $filename );
- $this->package['size'] = filesize( $filename );
-
- $vZ = file_get_contents( $filename );
- }
-
-
- if ( ( $pcd = strrpos( $vZ, "\x50\x4b\x05\x06" ) ) === false ) {
- $this->error( 'Unknown archive format' );
- return false;
- }
- $aE = array(
- 0 => substr( $vZ, 0, $pcd ),
- 1 => substr( $vZ, $pcd + 3 )
- );
-
- $aP = unpack( 'x16/v1CL', $aE[1] );
- $this->package['comment'] = substr( $aE[1], 18, $aP['CL'] );
-
- $this->package['comment'] = strtr( $this->package['comment'], array( "\r\n" => "\n", "\r" => "\n" ) );
-
- $aE = explode( "\x50\x4b\x01\x02", $vZ );
-
- $aE = explode( "\x50\x4b\x03\x04", $aE[0] );
-
- array_shift( $aE );
-
- foreach ( $aE as $vZ ) {
- $aI = array();
- $aI['E'] = 0;
- $aI['EM'] = '';
-
- $aP = unpack( 'v1VN/v1GPF/v1CM/v1FT/v1FD/V1CRC/V1CS/V1UCS/v1FNL/v1EFL', $vZ );
-
- $bE = false;
- $nF = $aP['FNL'];
- $mF = $aP['EFL'];
-
- if ( $aP['GPF'] & 0x0008 ) {
- $aP1 = unpack( 'V1CRC/V1CS/V1UCS', substr( $vZ, - 12 ) );
- $aP['CRC'] = $aP1['CRC'];
- $aP['CS'] = $aP1['CS'];
- $aP['UCS'] = $aP1['UCS'];
-
- $vZ = substr( $vZ, 0, - 12 );
- if ( substr( $vZ, - 4 ) === "\x50\x4b\x07\x08" ) {
- $vZ = substr( $vZ, 0, - 4 );
- }
- }
-
- $aI['N'] = substr( $vZ, 26, $nF );
- if ( substr( $aI['N'], - 1 ) === '/' ) {
-
- continue;
- }
-
- $aI['P'] = dirname( $aI['N'] );
- $aI['P'] = $aI['P'] === '.' ? '' : $aI['P'];
- $aI['N'] = basename( $aI['N'] );
- $vZ = substr( $vZ, 26 + $nF + $mF );
- if ( strlen( $vZ ) !== (int) $aP['CS'] ) {
- $aI['E'] = 1;
- $aI['EM'] = 'Compressed size is not equal with the value in header information.';
- } else {
- if ( $bE ) {
- $aI['E'] = 5;
- $aI['EM'] = 'File is encrypted, which is not supported from this class.';
- } else {
- switch ( $aP['CM'] ) {
- case 0:
-
- break;
- case 8:
- $vZ = gzinflate( $vZ );
- break;
- case 12:
- if ( extension_loaded( 'bz2' ) ) {
- $vZ = bzdecompress( $vZ );
- } else {
- $aI['E'] = 7;
- $aI['EM'] = 'PHP BZIP2 extension not available.';
- }
- break;
- default:
- $aI['E'] = 6;
- $aI['EM'] = "De-/Compression method {$aP['CM']} is not supported.";
- }
- if ( ! $aI['E'] ) {
- if ( $vZ === false ) {
- $aI['E'] = 2;
- $aI['EM'] = 'Decompression of data failed.';
- } else {
- if ( strlen( $vZ ) !== (int) $aP['UCS'] ) {
- $aI['E'] = 3;
- $aI['EM'] = 'Uncompressed size is not equal with the value in header information.';
- } else {
- if ( crc32( $vZ ) !== $aP['CRC'] ) {
- $aI['E'] = 4;
- $aI['EM'] = 'CRC32 checksum is not equal with the value in header information.';
- }
- }
- }
- }
- }
- }
- $aI['D'] = $vZ;
-
- $aI['T'] = mktime( ( $aP['FT'] & 0xf800 ) >> 11,
- ( $aP['FT'] & 0x07e0 ) >> 5,
- ( $aP['FT'] & 0x001f ) << 1,
- ( $aP['FD'] & 0x01e0 ) >> 5,
- $aP['FD'] & 0x001f,
- ( ( $aP['FD'] & 0xfe00 ) >> 9 ) + 1980 );
-
- $this->package['entries'][] = array(
- 'data' => $aI['D'],
- 'error' => $aI['E'],
- 'error_msg' => $aI['EM'],
- 'name' => $aI['N'],
- 'path' => $aI['P'],
- 'time' => $aI['T']
- );
- }
- return true;
- }
-
- public function error( $set = false ) {
- if ( $set ) {
- $this->error = $set;
- if ( $this->debug ) {
- trigger_error( __CLASS__ . ': ' . $set, E_USER_WARNING );
- }
- }
- return $this->error;
- }
- private function _parse() {
-
- $this->sharedstrings = array();
- $this->sheets = array();
-
- if ( $relations = $this->getEntryXML( '_rels/.rels' ) ) {
- foreach ( $relations->Relationship as $rel ) {
- $rel_type = trim( (string) $rel['Type'] );
- $rel_target = trim( (string) $rel['Target'] );
- if ( $rel_type === self::SCHEMA_REL_OFFICEDOCUMENT ) {
-
-
- if ( $this->workbook = $this->getEntryXML( $rel_target ) ) {
- if ( $workbookRelations = $this->getEntryXML( dirname( $rel_target ) . '/_rels/workbook.xml.rels' ) ) {
-
- foreach ( $workbookRelations->Relationship as $workbookRelation ) {
- $wrel_type = trim( (string) $workbookRelation['Type'] );
- $wrel_path = dirname( trim( (string) $rel['Target'] ) ) . '/' . trim( (string) $workbookRelation['Target'] );
- if ( ! $this->entryExists( $wrel_path ) ) {
- continue;
- }
- if ( $wrel_type === self::SCHEMA_REL_WORKSHEET ) {
- if ( $sheet = $this->getEntryXML( $wrel_path ) ) {
- $this->sheets[ str_replace( 'rId', '', (string) $workbookRelation['Id'] ) ] = $sheet;
- }
- } else if ( $wrel_type === self::SCHEMA_REL_SHAREDSTRINGS ) {
- if ( $sharedStrings = $this->getEntryXML( $wrel_path ) ) {
- foreach ( $sharedStrings->si as $val ) {
- if ( isset( $val->t ) ) {
- $this->sharedstrings[] = (string) $val->t;
- } elseif ( isset( $val->r ) ) {
- $this->sharedstrings[] = $this->_parseRichText( $val );
- }
- }
- }
- } else if ( $wrel_type === self::SCHEMA_REL_STYLES ) {
- $this->styles = $this->getEntryXML( $wrel_path );
- $nf = array();
- if ( $this->styles->numFmts->numFmt !== null ) {
- foreach ( $this->styles->numFmts->numFmt as $v ) {
- $nf[ (int) $v['numFmtId'] ] = (string) $v['formatCode'];
- }
- }
- if ( $this->styles->cellXfs->xf !== null ) {
- foreach ( $this->styles->cellXfs->xf as $v ) {
- $v = (array) $v->attributes();
- $v['format'] = '';
- if ( isset( $v['@attributes']['numFmtId'] ) ) {
- $v = $v['@attributes'];
- $fid = (int) $v['numFmtId'];
- if ( isset( self::$CF[ $fid ] ) ) {
- $v['format'] = self::$CF[ $fid ];
- } else if ( isset( $nf[ $fid ] ) ) {
- $v['format'] = $nf[ $fid ];
- }
- }
- $this->workbook_cell_formats[] = $v;
- }
- }
- }
- }
- break;
- }
- }
- }
- }
- }
- if ( count( $this->sheets ) ) {
-
- ksort( $this->sheets );
- return true;
- }
- return false;
- }
-
- public function getEntryXML( $name ) {
- if ( $entry_xml = $this->getEntryData( $name ) ) {
-
- $entry_xml = preg_replace('/xmlns[^=]*="[^"]*"/i','', $entry_xml );
- $entry_xml = preg_replace('/[a-zA-Z0-9]+:([a-zA-Z0-9]+="[^"]+")/','$1$2', $entry_xml );
- $entry_xml = preg_replace('/<[a-zA-Z0-9]+:([^>]+)>/', '<$1>', $entry_xml);
- $entry_xml = preg_replace('/<\/[a-zA-Z0-9]+:([^>]+)>/', '</$1>', $entry_xml);
-
- $_old = libxml_disable_entity_loader(true);
- $entry_xmlobj = simplexml_load_string( $entry_xml );
- libxml_disable_entity_loader($_old);
- if ( $entry_xmlobj ) {
- return $entry_xmlobj;
- }
- $e = libxml_get_last_error();
- $this->error( 'XML-entry ' . $name.' parser error '.$e->message.' line '.$e->line );
- } else {
- $this->error( 'XML-entry not found: ' . $name );
- }
- return false;
- }
- public function getEntryData( $name ) {
- $dir = strtoupper( dirname( $name ) );
- $name = strtoupper( basename( $name ) );
- foreach ( $this->package['entries'] as $entry ) {
- if ( strtoupper( $entry['path'] ) === $dir && strtoupper( $entry['name'] ) === $name ) {
- return $entry['data'];
- }
- }
- $this->error( 'Entry not found: '.$name );
- return false;
- }
- public function entryExists( $name ) {
- $dir = strtoupper( dirname( $name ) );
- $name = strtoupper( basename( $name ) );
- foreach ( $this->package['entries'] as $entry ) {
- if ( strtoupper( $entry['path'] ) === $dir && strtoupper( $entry['name'] ) === $name ) {
- return true;
- }
- }
- return false;
- }
- private function _parseRichText( $is = null ) {
- $value = array();
- if ( isset( $is->t ) ) {
- $value[] = (string) $is->t;
- } else {
- foreach ( $is->r as $run ) {
- $value[] = (string) $run->t;
- }
- }
- return implode( ' ', $value );
- }
- public static function parse( $filename, $is_data = false, $debug = false ) {
- $xlsx = new self( $filename, $is_data, $debug );
- if ( $xlsx->success() ) {
- return $xlsx;
- }
- self::parse_error( $xlsx->error() );
- return false;
- }
- public static function parse_error( $set = false ) {
- static $error = false;
- return ($set) ? $error = $set : $error;
- }
- public function success() {
- return ! $this->error;
- }
- public function rows( $worksheet_id = 0 ) {
- if ( ( $ws = $this->worksheet( $worksheet_id ) ) === false ) {
- return false;
- }
- $rows = array();
- $curR = 0;
- list( $cols, ) = $this->dimension( $worksheet_id );
-
- foreach ( $ws->sheetData->row as $row ) {
- $rows[ $curR ] = array();
- foreach ( $row->c as $c ) {
- list( $curC, ) = $this->_columnIndex( (string) $c['r'] );
- $rows[ $curR ][ $curC ] = $this->value( $c );
- }
- for ( $i = 0; $i < $cols; $i ++ ) {
- if ( ! isset( $rows[ $curR ][ $i ] ) ) {
- $rows[ $curR ][ $i ] = '';
- }
- }
- ksort( $rows[ $curR ] );
- $curR ++;
- }
- return $rows;
- }
- public function worksheet( $worksheet_id = 0 ) {
- if ( $worksheet_id === 0 ) {
- reset( $this->sheets );
- $worksheet_id = key( $this->sheets );
- }
- if ( isset( $this->sheets[ $worksheet_id ] ) ) {
- $ws = $this->sheets[ $worksheet_id ];
- if ( isset( $ws->hyperlinks ) ) {
- $this->hyperlinks = array();
- foreach ( $ws->hyperlinks->hyperlink as $hyperlink ) {
- $this->hyperlinks[ (string) $hyperlink['ref'] ] = (string) $hyperlink['display'];
- }
- }
- return $ws;
- }
- $this->error( 'Worksheet ' . $worksheet_id . ' not found.' );
- return false;
- }
-
- public function dimension( $worksheet_id = 0 ) {
- if ( ( $ws = $this->worksheet( $worksheet_id ) ) === false ) {
- return false;
- }
-
- $ref = (string) $ws->dimension['ref'];
- if ( strpos( $ref, ':' ) !== false ) {
- $d = explode( ':', $ref );
- $index = $this->_columnIndex( $d[1] );
- return array( $index[0] + 1, $index[1] + 1 );
- }
- if ( $ref !== '' ) {
- $index = $this->_columnIndex( $ref );
- return array( $index[0] + 1, $index[1] + 1 );
- }
- return array( 0, 0 );
- }
- private function _columnIndex( $cell = 'A1' ) {
- if ( preg_match( '/([A-Z]+)(\d+)/', $cell, $m ) ) {
- list( ,$col, $row ) = $m;
- $colLen = strlen( $col );
- $index = 0;
- for ( $i = $colLen - 1; $i >= 0; $i -- ) {
-
- $index += ( ord( $col[$i] ) - 64 ) * pow( 26, $colLen - $i - 1 );
- }
- return array( $index - 1, $row - 1 );
- }
- $this->error( 'Invalid cell index ' . $cell );
- return false;
- }
- public function value( $cell, $format = null ) {
-
- $dataType = (string) $cell['t'];
- if ( $format === null ) {
- $s = (int) $cell['s'];
- if ( $s > 0 && isset( $this->workbook_cell_formats[ $s ] ) ) {
- $format = $this->workbook_cell_formats[ $s ]['format'];
- }
- }
- if ( strpos( $format, 'm' ) !== false ) {
- $dataType = 'd';
- }
- $value = '';
- switch ( $dataType ) {
- case 's':
-
- if ( (string) $cell->v !== '' ) {
- $value = $this->sharedstrings[ (int) $cell->v ];
- }
- break;
- case 'b':
-
- $value = (string) $cell->v;
- if ( $value === '0' ) {
- $value = false;
- } else if ( $value === '1' ) {
- $value = true;
- } else {
- $value = (bool) $cell->v;
- }
- break;
- case 'inlineStr':
-
- $value = $this->_parseRichText( $cell->is );
- break;
- case 'e':
-
- if ( (string) $cell->v !== '' ) {
- $value = (string) $cell->v;
- }
- break;
- case 'd':
-
- $value = $this->datetime_format ? gmdate( $this->datetime_format, $this->unixstamp( (float) $cell->v ) ) : (float) $cell->v;
- break;
- default:
-
- $value = (string) $cell->v;
-
- if ( is_numeric( $value ) && $dataType !== 's' ) {
- if ( $value == (int) $value ) {
- $value = (int) $value;
- } elseif ( $value == (float) $value ) {
- $value = (float) $value;
- }
- }
- }
- return $value;
- }
- public function unixstamp( $excelDateTime ) {
- $d = floor( $excelDateTime );
- $t = $excelDateTime - $d;
-
- return ( abs( $d ) > 0 ) ? ( $d - 25569 ) * 86400 + round( $t * 86400 ) : round( $t * 86400 );
- }
- public function rowsEx( $worksheet_id = 0 ) {
- if ( ( $ws = $this->worksheet( $worksheet_id ) ) === false ) {
- return false;
- }
- $rows = array();
- $curR = 0;
- list( $cols, ) = $this->dimension( $worksheet_id );
-
- foreach ( $ws->sheetData->row as $row ) {
- $r_idx = (int) $row['r'];
- foreach ( $row->c as $c ) {
- $r = (string) $c['r'];
- $t = (string) $c['t'];
- $s = (int) $c['s'];
- list( $curC, ) = $this->_columnIndex( $r );
- if ( $s > 0 && isset( $this->workbook_cell_formats[ $s ] ) ) {
- $format = $this->workbook_cell_formats[ $s ]['format'];
- if ( strpos( $format, 'm' ) !== false ) {
- $t = 'd';
- }
- } else {
- $format = '';
- }
- $rows[ $curR ][ $curC ] = array(
- 'type' => $t,
- 'name' => $c['r'],
- 'value' => $this->value( $c, $format ),
- 'href' => $this->href( $c ),
- 'f' => (string) $c->f,
- 'format' => $format,
- 'r' => $r_idx
- );
- }
- for ( $i = 0; $i < $cols; $i ++ ) {
- if ( ! isset( $rows[ $curR ][ $i ] ) ) {
-
- for ( $c = '', $j = $i; $j >= 0; $j = (int) ( $j / 26 ) - 1 ) {
- $c = chr( $j % 26 + 65 ) . $c;
- }
- $rows[ $curR ][ $i ] = array(
- 'type' => '',
- 'name' => $c . ( $curR + 1 ),
- 'value' => '',
- 'href' => '',
- 'f' => '',
- 'format' => '',
- 'r' => $r_idx
- );
- }
- }
- ksort( $rows[ $curR ] );
- $curR ++;
- }
- return $rows;
- }
-
- public function getCell( $worksheet_id = 0, $cell = 'A1', $format = null ) {
- if (($ws = $this->worksheet( $worksheet_id)) === false) { return false; }
- list( $curC, $curR ) = is_array( $cell ) ? $cell : $this->_columnIndex( (string) $cell );
- if (isset($ws->sheetData->row[$curR], $ws->sheetData->row[$curR]->c[$curC])) {
- $c = $ws->sheetData->row[ $curR ]->c[ $curC ];
- return $this->value( $c, $format );
- }
- return null;
- }
- public function href( $cell ) {
- return isset( $this->hyperlinks[ (string) $cell['r'] ] ) ? $this->hyperlinks[ (string) $cell['r'] ] : '';
- }
- public function sheets() {
- return $this->sheets;
- }
- public function sheetsCount() {
- return count( $this->sheets );
- }
- public function sheetName( $worksheet_id ) {
- if ( ! isset( $this->workbook->sheets->sheet ) ) {
- return false;
- }
- foreach ( $this->workbook->sheets->sheet as $s ) {
-
- if ( (int) $s->attributes()->sheetId === (int) $worksheet_id ) {
- return (string) $s->attributes()->name;
- }
- }
- return false;
- }
- public function sheetNames() {
- $result = array();
- foreach ( $this->workbook->sheets->sheet as $s ) {
-
-
- $result[ (int) $s->attributes()->sheetId ] = (string) $s->attributes()->name;
- }
- return $result;
- }
-
- public function getStyles() {
- return $this->styles;
- }
- public function getPackage() {
- return $this->package;
- }
- }
|