writeToFile() public method

public writeToFile ( $filename )
Beispiel #1
3
 static function xls()
 {
     return function ($req, $res, $svc, $app) {
         $time = date('H:i:s', time());
         $date = date('d-m-Y');
         $exportFile = __DIR__ . "/../xls/relatorio-tickets-{$time}.xlsx";
         $headers = [['Protocolo', 'Operadora', 'Status', 'Cidade', 'Problema', 'Designação', 'Cliente Final', 'Data']];
         $rows = array_map(function ($ticket) {
             return [$ticket->protocolo, $ticket->operadora, $ticket->status, $ticket->cidade, $ticket->tipo_problema, $ticket->designacao, $ticket->cliente_final, date('d/m/Y', strtotime($ticket->criado_em))];
         }, Tickets::filter($req, $app));
         $writer = new \XLSXWriter();
         $writer->writeSheet(array_merge($headers, $rows), 'Relatório ' . $date);
         $writer->setAuthor('Sim TV - Trouble Ticket');
         $writer->writeToFile($exportFile);
         $res->file($exportFile, "Relatório Tickets {$time}.xlsx");
     };
 }
Beispiel #2
2
<?php

include_once "../xlsxwriter.class.php";
$header = array('year' => 'string', 'month' => 'string', 'amount' => 'money', 'first_event' => 'datetime', 'second_event' => 'date');
$data1 = array(array('2003', '1', '-50.5', '2010-01-01 23:00:00', '2012-12-31 23:00:00'), array('2003', '=B2', '23.5', '2010-01-01 00:00:00', '2012-12-31 00:00:00'));
$data2 = array(array('2003', '01', '343.12'), array('2003', '02', '345.12'));
$writer = new XLSXWriter();
$writer->setAuthor('Some Author');
$writer->writeSheet($data1, 'Sheet1', $header);
$writer->writeSheet($data2, 'Sheet2');
$writer->writeToFile('test.xlsx');
<?php

include_once "../../xlsxwriter.class.php";
$writer = new XLSXWriter();
$writer->setAuthor('Some Author');
$header = array('General' => 'string', 'Simple Integer' => '0', '2 Decimal Places Integer' => '0.00', 'Integer 1000s Group' => '#,##0', '1000s,Decimal,Leading Zero' => '#,##0.00', '1000s,Decimal,No Leading Zero' => '#,###.00', 'Negative In Parentheses' => '#,##0_);(#,##0)', 'Negative In Parentheses With Decimal' => '#,##0.00_);(#,##0.00)');
$row = array('1000', '2000', '3000', '4000', '0.50', '0.50', '-50', '-50');
$writer->writeSheet(array($row), 'Number', $header);
$header = array('Whole Percent' => '0%', 'Decimal Percent' => '0.00%');
$row = array('1', '1');
$writer->writeSheet(array($row), 'Percent', $header);
$header = array('USD' => '[$$-409]#,##0.00;[RED]-[$$-409]#,##0.00', 'CAD' => '[$$-1009]#,##0.00;[RED]-[$$-1009]#,##0.00', 'Euro' => '#,##0.00 [$€-407];[RED]-#,##0.00 [$€-407]', 'JPY' => '[$¥-411]#,##0;[RED]-[$¥-411]#,##0', 'CNY' => '[$¥-804]#,##0.00;[RED]-[$¥-804]#,##0.00');
$row = array('1000', '2000', '3000', '4000', '5000');
$writer->writeSheet(array($row), 'Currency', $header);
$header = array('M/D/YY' => 'M/D/YY', 'MM/DD/YYYY' => 'MM/DD/YYYY', 'YYYY-MM-DD' => 'YYYY-MM-DD', 'YYYY-MM-DD HH:MM:SS' => 'YYYY-MM-DD HH:MM:SS', 'NN' => 'NN', 'NNN' => 'NNN', 'NNNN' => 'NNNN', 'D' => 'D', 'DD' => 'DD', 'M' => 'M', 'MM' => 'MM', 'MMM' => 'MMM', 'MMMM' => 'MMMM', 'YY' => 'YY', 'YYYY' => 'YYYY', 'Q YY' => 'Q YY', 'Q YYYY' => 'Q YYYY');
$row = array('1999-01-01', '1999-01-01', '1999-12-31', '1999-12-31 00:00:00', '1999-12-31', '1999-12-31', '1999-12-31', '1999-12-31', '1999-12-31', '1999-12-31', '1999-12-31', '1999-12-31', '1999-12-31', '1999-12-31', '1999-12-31', '1999-12-31', '1999-12-31');
$writer->writeSheet(array($row), 'Date', $header);
$header = array('HH:MM' => 'HH:MM', 'HH:MM:SS' => 'HH:MM:SS', 'HH:MM AM/PM' => 'HH:MM AM/PM', 'HH:MM:SS AM/PM' => 'HH:MM:SS AM/PM');
$row = array('12-31-1999 01:23:00', '12-31-1999 01:23:00', '12-31-1999 01:23:00', '12-31-1999 01:23:00');
$writer->writeSheet(array($row), 'Time', $header);
$writer->writeToFile('formats.xlsx');
Beispiel #4
0
 static function xls()
 {
     return function ($req, $res, $svc, $app) {
         $time = date('H:i:s', time());
         $date = date('d-m-Y');
         $exportFile = __DIR__ . "/../xls/relatorio-clientes-{$time}.xlsx";
         $headers = [['Cidade', 'Contrato', 'Designação', 'Cliente', 'Velocidade', 'Operadora', 'Equipamento', 'Endereço', 'Criado em']];
         $clientes = $app->db->cadcliente;
         if ($req->cidade) {
             $clientes->where_equal('cidade', $req->cidade);
         }
         $rows = array_map(function ($cliente) {
             return [$cliente->cidade, $cliente->contrato, $cliente->designacao, $cliente->cliente, $cliente->velocidade, $cliente->operadora, $cliente->equipamento, $cliente->endereco, date('d/m/Y', strtotime($cliente->data))];
         }, $clientes->find_many());
         $writer = new \XLSXWriter();
         $writer->writeSheet(array_merge($headers, $rows), 'Relatório ' . $date);
         $writer->setAuthor('Sim TV - Trouble Ticket');
         $writer->writeToFile($exportFile);
         $res->file($exportFile, "Relatório Cliente {$time}.xlsx");
     };
 }
<?php

include_once "xlsxwriter.class.php";
$header = array('year' => 'string', 'month' => 'string', 'amount' => 'money', 'first_event' => 'datetime', 'second_event' => 'date');
$data1 = array(array('2003', '1', '-50.5', '2010-01-01 23:00:00', '2012-12-31 23:00:00'), array('2003', '=B2', '23.5', '2010-01-01 00:00:00', '2012-12-31 00:00:00'));
$data2 = array(array('2003', '01', '343.12', '4000000000'), array('2003', '02', '345.12', '2000000000'));
$writer = new XLSXWriter();
$writer->setAuthor('Some Author');
$writer->writeSheet($data1, 'Sheet1', $header);
$writer->writeSheet($data2, 'Sheet2');
$writer->writeToFile('example.xlsx');
//$writer->writeToStdOut();
//echo $writer->writeToString();
exit(0);
<?php

include_once "xlsxwriter.class.php";
$writer = new XLSXWriter();
$writer->writeSheetHeader('Sheet1', array('c1' => 'string', 'c2' => 'string', 'c3' => 'string', 'c4' => 'string'));
//optional
for ($i = 0; $i < 50000; $i++) {
    $writer->writeSheetRow('Sheet1', array(rand() % 10000, rand() % 10000, rand() % 10000, rand() % 10000));
}
$writer->writeToFile('output.xlsx');
echo '#' . floor(memory_get_peak_usage() / 1024 / 1024) . "MB" . "\n";
 public function Run()
 {
     $sCode = 'error';
     $iPercentage = 100;
     $sMessage = Dict::Format('ExcelExporter:ErrorUnexpected_State', $this->sState);
     $fTime = microtime(true);
     try {
         switch ($this->sState) {
             case 'new':
                 $oIDSet = new DBObjectSet($this->oSearch);
                 $oIDSet->OptimizeColumnLoad(array('id'));
                 $this->aObjectsIDs = array();
                 while ($oObj = $oIDSet->Fetch()) {
                     $this->aObjectsIDs[] = $oObj->GetKey();
                 }
                 $sCode = 'retrieving-data';
                 $iPercentage = 5;
                 $sMessage = Dict::S('ExcelExporter:RetrievingData');
                 $this->iPosition = 0;
                 $this->aStatistics['objects_count'] = count($this->aObjectsIDs);
                 $this->aStatistics['data_retrieval_duration'] += microtime(true) - $fTime;
                 // The first line of the file is the "headers" specifying the label and the type of each column
                 $this->GetFieldsList($oIDSet, $this->bAdvancedMode);
                 $sRow = json_encode($this->aTableHeaders);
                 $hFile = @fopen($this->GetDataFile(), 'ab');
                 if ($hFile === false) {
                     throw new Exception('ExcelExporter: Failed to open temporary data file: "' . $this->GetDataFile() . '" for writing.');
                 }
                 fwrite($hFile, $sRow . "\n");
                 fclose($hFile);
                 // Next state
                 $this->sState = 'retrieving-data';
                 break;
             case 'retrieving-data':
                 $oCurrentSearch = clone $this->oSearch;
                 $aIDs = array_slice($this->aObjectsIDs, $this->iPosition, $this->iChunkSize);
                 $oCurrentSearch->AddCondition('id', $aIDs, 'IN');
                 $hFile = @fopen($this->GetDataFile(), 'ab');
                 if ($hFile === false) {
                     throw new Exception('ExcelExporter: Failed to open temporary data file: "' . $this->GetDataFile() . '" for writing.');
                 }
                 $oSet = new DBObjectSet($oCurrentSearch);
                 $this->GetFieldsList($oSet, $this->bAdvancedMode);
                 while ($aObjects = $oSet->FetchAssoc()) {
                     $aRow = array();
                     foreach ($this->aAuthorizedClasses as $sAlias => $sClassName) {
                         $oObj = $aObjects[$sAlias];
                         if ($this->bAdvancedMode) {
                             $aRow[] = $oObj->GetKey();
                         }
                         foreach ($this->aFieldsList[$sAlias] as $sAttCodeEx => $oAttDef) {
                             $value = $oObj->Get($sAttCodeEx);
                             if ($value instanceof ormCaseLog) {
                                 // Extract the case log as text and remove the "===" which make Excel think that the cell contains a formula the next time you edit it!
                                 $sExcelVal = trim(preg_replace('/========== ([^=]+) ============/', '********** $1 ************', $value->GetText()));
                             } else {
                                 $sExcelVal = $oAttDef->GetEditValue($value, $oObj);
                             }
                             $aRow[] = $sExcelVal;
                         }
                     }
                     $sRow = json_encode($aRow);
                     fwrite($hFile, $sRow . "\n");
                 }
                 fclose($hFile);
                 if ($this->iPosition + $this->iChunkSize > count($this->aObjectsIDs)) {
                     // Next state
                     $this->sState = 'building-excel';
                     $sCode = 'building-excel';
                     $iPercentage = 80;
                     $sMessage = Dict::S('ExcelExporter:BuildingExcelFile');
                 } else {
                     $sCode = 'retrieving-data';
                     $this->iPosition += $this->iChunkSize;
                     $iPercentage = 5 + round(75 * ($this->iPosition / count($this->aObjectsIDs)));
                     $sMessage = Dict::S('ExcelExporter:RetrievingData');
                 }
                 break;
             case 'building-excel':
                 $hFile = @fopen($this->GetDataFile(), 'rb');
                 if ($hFile === false) {
                     throw new Exception('ExcelExporter: Failed to open temporary data file: "' . $this->GetDataFile() . '" for reading.');
                 }
                 $sHeaders = fgets($hFile);
                 $aHeaders = json_decode($sHeaders, true);
                 $aData = array();
                 while ($sLine = fgets($hFile)) {
                     $aRow = json_decode($sLine);
                     $aData[] = $aRow;
                 }
                 fclose($hFile);
                 @unlink($this->GetDataFile());
                 $fStartExcel = microtime(true);
                 $writer = new XLSXWriter();
                 $writer->setAuthor(UserRights::GetUserFriendlyName());
                 $writer->writeSheet($aData, 'Sheet1', $aHeaders);
                 $fExcelTime = microtime(true) - $fStartExcel;
                 $this->aStatistics['excel_build_duration'] = $fExcelTime;
                 $fTime = microtime(true);
                 $writer->writeToFile($this->GetExcelFilePath());
                 $fExcelSaveTime = microtime(true) - $fTime;
                 $this->aStatistics['excel_write_duration'] = $fExcelSaveTime;
                 // Next state
                 $this->sState = 'done';
                 $sCode = 'done';
                 $iPercentage = 100;
                 $sMessage = Dict::S('ExcelExporter:Done');
                 break;
             case 'done':
                 $this->sState = 'done';
                 $sCode = 'done';
                 $iPercentage = 100;
                 $sMessage = Dict::S('ExcelExporter:Done');
                 break;
         }
     } catch (Exception $e) {
         $sCode = 'error';
         $sMessage = $e->getMessage();
     }
     $this->aStatistics['total_duration'] += microtime(true) - $fTime;
     $peak_memory = memory_get_peak_usage(true);
     if ($peak_memory > $this->aStatistics['peak_memory_usage']) {
         $this->aStatistics['peak_memory_usage'] = $peak_memory;
     }
     return array('code' => $sCode, 'message' => $sMessage, 'percentage' => $iPercentage);
 }
 /**
  * @covers XLSXWriter::writeToFile
  */
 public function testWriteToFile()
 {
     $filename = tempnam("/tmp", "xlsx_writer");
     $header = array('0' => 'string', '1' => 'string', '2' => 'string', '3' => 'string');
     $sheet = array(array('55', '66', '77', '88'), array('10', '11', '12', '13'));
     $xlsx_writer = new XLSXWriter();
     $xlsx_writer->writeSheet($sheet, 'mysheet', $header);
     $xlsx_writer->writeToFile($filename);
     $zip = new ZipArchive();
     $r = $zip->open($filename);
     $this->assertTrue($r);
     $r = $zip->numFiles > 0 ? true : false;
     $this->assertTrue($r);
     $out_sheet = array();
     for ($z = 0; $z < $zip->numFiles; $z++) {
         $inside_zip_filename = $zip->getNameIndex($z);
         if (preg_match("/sheet(\\d+).xml/", basename($inside_zip_filename))) {
             $out_sheet = $this->stripCellsFromSheetXML($zip->getFromName($inside_zip_filename));
             array_shift($out_sheet);
             $out_sheet = array_values($out_sheet);
         }
     }
     $zip->close();
     @unlink($filename);
     $r1 = self::array_diff_assoc_recursive($out_sheet, $sheet);
     $r2 = self::array_diff_assoc_recursive($sheet, $out_sheet);
     $this->assertEmpty($r1);
     $this->assertEmpty($r2);
 }