dolibarr  16.0.5
export_excel2007.modules.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2006-2015 Laurent Destailleur <eldy@users.sourceforge.net>
3  * Copyright (C) 2012 Marcos GarcĂ­a <marcosgdf@gmail.com>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <https://www.gnu.org/licenses/>.
17  */
18 
25 require_once DOL_DOCUMENT_ROOT.'/core/modules/export/modules_export.php';
26 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
27 
28 use PhpOffice\PhpSpreadsheet\Spreadsheet;
29 use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
30 use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
31 
36 {
40  public $id;
41 
45  public $label;
46 
47  public $extension;
48 
53  public $version = 'dolibarr';
54 
55  public $label_lib;
56 
57  public $version_lib;
58 
59  public $workbook; // Handle file
60 
61  public $worksheet; // Handle sheet
62 
63  public $styleArray;
64 
65  public $row;
66 
67  public $col;
68 
69  public $file; // To save filename
70 
71 
77  public function __construct($db)
78  {
79  global $conf, $langs;
80  $this->db = $db;
81 
82  $this->id = 'excel2007'; // Same value then xxx in file name export_xxx.modules.php
83  $this->label = 'Excel 2007'; // Label of driver
84  $this->desc = $langs->trans('Excel2007FormatDesc');
85  $this->extension = 'xlsx'; // Extension for generated file by this driver
86  $this->picto = 'mime/xls'; // Picto
87  $this->version = '1.30'; // Driver version
88  $this->phpmin = array(5, 6); // Minimum version of PHP required by module
89 
90  $this->disabled = 0;
91 
92  if (empty($this->disabled)) {
93  require_once PHPEXCELNEW_PATH.'Spreadsheet.php';
94  $this->label_lib = 'PhpSpreadSheet';
95  $this->version_lib = '1.6.0'; // No way to get info from library
96  }
97 
98  $this->row = 0;
99  }
100 
106  public function getDriverId()
107  {
108  return $this->id;
109  }
110 
116  public function getDriverLabel()
117  {
118  return $this->label;
119  }
120 
126  public function getDriverDesc()
127  {
128  return $this->desc;
129  }
130 
136  public function getDriverExtension()
137  {
138  return $this->extension;
139  }
140 
146  public function getDriverVersion()
147  {
148  return $this->version;
149  }
150 
156  public function getLibLabel()
157  {
158  return $this->label_lib;
159  }
160 
166  public function getLibVersion()
167  {
168  return $this->version_lib;
169  }
170 
171 
172  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
180  public function open_file($file, $outputlangs)
181  {
182  // phpcs:enable
183  global $user, $conf, $langs;
184 
185  if (!empty($conf->global->MAIN_USE_PHP_WRITEEXCEL)) {
186  $outputlangs->charset_output = 'ISO-8859-1'; // Because Excel 5 format is ISO
187  }
188 
189  dol_syslog(get_class($this)."::open_file file=".$file);
190  $this->file = $file;
191 
192  $ret = 1;
193 
194  $outputlangs->load("exports");
195 
196  require_once DOL_DOCUMENT_ROOT.'/includes/phpoffice/phpspreadsheet/src/autoloader.php';
197  require_once DOL_DOCUMENT_ROOT.'/includes/Psr/autoloader.php';
198  require_once PHPEXCELNEW_PATH.'Spreadsheet.php';
199 
200  if ($this->id == 'excel2007') {
201  if (!class_exists('ZipArchive')) { // For Excel2007, PHPSpreadSheet may need ZipArchive
202  $langs->load("errors");
203  $this->error = $langs->trans('ErrorPHPNeedModule', 'zip');
204  return -1;
205  }
206  }
207 
208  $this->workbook = new Spreadsheet();
209  $this->workbook->getProperties()->setCreator($user->getFullName($outputlangs).' - '.DOL_APPLICATION_TITLE.' '.DOL_VERSION);
210  //$this->workbook->getProperties()->setLastModifiedBy('Dolibarr '.DOL_VERSION);
211  $this->workbook->getProperties()->setTitle(basename($file));
212  $this->workbook->getProperties()->setSubject(basename($file));
213  $this->workbook->getProperties()->setDescription(DOL_APPLICATION_TITLE.' '.DOL_VERSION);
214 
215  $this->workbook->setActiveSheetIndex(0);
216  $this->workbook->getActiveSheet()->setTitle($outputlangs->trans("Sheet"));
217  $this->workbook->getActiveSheet()->getDefaultRowDimension()->setRowHeight(16);
218 
219  return $ret;
220  }
221 
222  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
229  public function write_header($outputlangs)
230  {
231  // phpcs:enable
232  //$outputlangs->charset_output='ISO-8859-1'; // Because Excel 5 format is ISO
233 
234  return 0;
235  }
236 
237 
238  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
248  public function write_title($array_export_fields_label, $array_selected_sorted, $outputlangs, $array_types)
249  {
250  // phpcs:enable
251  global $conf;
252 
253  // Create a format for the column headings
254  $this->workbook->getActiveSheet()->getStyle('1')->getFont()->setBold(true);
255  $this->workbook->getActiveSheet()->getStyle('1')->getAlignment()->setHorizontal(PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT);
256 
257  $this->col = 1;
258  if (!empty($conf->global->MAIN_USE_PHP_WRITEEXCEL)) {
259  $this->col = 0;
260  }
261  foreach ($array_selected_sorted as $code => $value) {
262  $alias = $array_export_fields_label[$code];
263  //print "dd".$alias;
264  if (empty($alias)) {
265  dol_print_error('', 'Bad value for field with code='.$code.'. Try to redefine export.');
266  }
267  if (!empty($conf->global->MAIN_USE_PHP_WRITEEXCEL)) {
268  $this->worksheet->write($this->row, $this->col, $outputlangs->transnoentities($alias), $formatheader);
269  } else {
270  $this->workbook->getActiveSheet()->SetCellValueByColumnAndRow($this->col, $this->row + 1, $outputlangs->transnoentities($alias));
271  if (!empty($array_types[$code]) && in_array($array_types[$code], array('Date', 'Numeric', 'TextAuto'))) { // Set autowidth for some types
272  $this->workbook->getActiveSheet()->getColumnDimension($this->column2Letter($this->col + 1))->setAutoSize(true);
273  }
274  }
275  $this->col++;
276  }
277  $this->row++;
278  return 0;
279  }
280 
281  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
291  public function write_record($array_selected_sorted, $objp, $outputlangs, $array_types)
292  {
293  // phpcs:enable
294  global $conf;
295 
296  // Define first row
297  $this->col = 1;
298  if (!empty($conf->global->MAIN_USE_PHP_WRITEEXCEL)) {
299  $this->col = 0;
300  }
301 
302  $reg = array();
303 
304  foreach ($array_selected_sorted as $code => $value) {
305  if (strpos($code, ' as ') == 0) {
306  $alias = str_replace(array('.', '-', '(', ')'), '_', $code);
307  } else {
308  $alias = substr($code, strpos($code, ' as ') + 4);
309  }
310  if (empty($alias)) {
311  dol_print_error('', 'Bad value for field with code='.$code.'. Try to redefine export.');
312  }
313  $newvalue = $objp->$alias;
314 
315  $newvalue = $this->excel_clean($newvalue);
316  $typefield = isset($array_types[$code]) ? $array_types[$code] : '';
317 
318  if (preg_match('/^Select:/i', $typefield) && $typefield = substr($typefield, 7)) {
319  $array = json_decode($typefield, true);
320  $array = $array['options'];
321  $newvalue = $array[$newvalue];
322  }
323 
324  // Traduction newvalue
325  if (preg_match('/^\((.*)\)$/i', $newvalue, $reg)) {
326  $newvalue = $outputlangs->transnoentities($reg[1]);
327  } else {
328  $newvalue = $outputlangs->convToOutputCharset($newvalue);
329  }
330 
331  if (preg_match('/^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]$/i', $newvalue)) {
332  $newvalue = dol_stringtotime($newvalue);
333  $this->workbook->getActiveSheet()->SetCellValueByColumnAndRow($this->col, $this->row + 1, \PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExcel($newvalue));
334  $coord = $this->workbook->getActiveSheet()->getCellByColumnAndRow($this->col, $this->row + 1)->getCoordinate();
335  $this->workbook->getActiveSheet()->getStyle($coord)->getNumberFormat()->setFormatCode('yyyy-mm-dd');
336  } elseif (preg_match('/^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9]$/i', $newvalue)) {
337  $newvalue = dol_stringtotime($newvalue);
338  $this->workbook->getActiveSheet()->SetCellValueByColumnAndRow($this->col, $this->row + 1, \PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExcel($newvalue));
339  $coord = $this->workbook->getActiveSheet()->getCellByColumnAndRow($this->col, $this->row + 1)->getCoordinate();
340  $this->workbook->getActiveSheet()->getStyle($coord)->getNumberFormat()->setFormatCode('yyyy-mm-dd h:mm:ss');
341  } else {
342  if ($typefield == 'Text' || $typefield == 'TextAuto') {
343  $this->workbook->getActiveSheet()->SetCellValueByColumnAndRow($this->col, $this->row + 1, (string) $newvalue);
344  $coord = $this->workbook->getActiveSheet()->getCellByColumnAndRow($this->col, $this->row + 1)->getCoordinate();
345  $this->workbook->getActiveSheet()->getStyle($coord)->getNumberFormat()->setFormatCode('@');
346  $this->workbook->getActiveSheet()->getStyle($coord)->getAlignment()->setHorizontal(PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT);
347  } else {
348  $this->workbook->getActiveSheet()->SetCellValueByColumnAndRow($this->col, $this->row + 1, $newvalue);
349  }
350  }
351  $this->col++;
352  }
353  $this->row++;
354  return 0;
355  }
356 
357 
358  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
365  public function write_footer($outputlangs)
366  {
367  // phpcs:enable
368  return 0;
369  }
370 
371 
372  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
378  public function close_file()
379  {
380  // phpcs:enable
381  global $conf;
382 
383  $objWriter = new Xlsx($this->workbook);
384  $objWriter->save($this->file);
385  $this->workbook->disconnectWorksheets();
386  unset($this->workbook);
387 
388  return 1;
389  }
390 
391 
392  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
399  public function excel_clean($newvalue)
400  {
401  // phpcs:enable
402  // Rule Dolibarr: No HTML
403  $newvalue = dol_string_nohtmltag($newvalue);
404 
405  return $newvalue;
406  }
407 
408 
415  public function column2Letter($c)
416  {
417 
418  $c = intval($c);
419  if ($c <= 0) {
420  return '';
421  }
422 
423  while ($c != 0) {
424  $p = ($c - 1) % 26;
425  $c = intval(($c - $p) / 26);
426  $letter = chr(65 + $p).$letter;
427  }
428 
429  return $letter;
430  }
431 
440  public function setCellValue($val, $startCell, $endCell = '')
441  {
442  try {
443  $this->workbook->getActiveSheet()->setCellValue($startCell, $val);
444 
445  if (!empty($endCell)) {
446  $cellRange = $startCell.':'.$endCell;
447  $this->workbook->getActiveSheet()->mergeCells($startCell.':'.$endCell);
448  } else {
449  $cellRange = $startCell;
450  }
451  if (!empty($this->styleArray)) {
452  $this->workbook->getActiveSheet()->getStyle($cellRange)->applyFromArray($this->styleArray);
453  }
454  } catch (Exception $e) {
455  $this->error = $e->getMessage();
456  return -1;
457  }
458  return 1;
459  }
460 
468  public function setBorderStyle($thickness, $color)
469  {
470  $this->styleArray['borders'] = array(
471  'outline' => array(
472  'borderStyle' => $thickness,
473  'color' => array('argb' => $color)
474  )
475  );
476  return 1;
477  }
478 
486  public function setFontStyle($bold, $color)
487  {
488  $this->styleArray['font'] = array(
489  'color' => array('argb' => $color),
490  'bold' => $bold
491  );
492  return 1;
493  }
494 
501  public function setAlignmentStyle($horizontal)
502  {
503  $this->styleArray['alignment'] = array('horizontal' => $horizontal);
504  return 1;
505  }
506 
511  public function resetStyle()
512  {
513  $this->styleArray = array();
514  return 1;
515  }
516 
525  public function setBlock($startCell, $TDatas = array(), $boldTitle = false)
526  {
527  try {
528  if (!empty($TDatas)) {
529  $startCell = $this->workbook->getActiveSheet()->getCell($startCell);
530  $startColumn = Coordinate::columnIndexFromString($startCell->getColumn());
531  $startRow = $startCell->getRow();
532  foreach ($TDatas as $column => $TRows) {
533  if ($boldTitle) {
534  $this->setFontStyle(true, $this->styleArray['font']['color']['argb']);
535  }
536  $cell = $this->workbook->getActiveSheet()->getCellByColumnAndRow($startColumn, $startRow);
537  $this->setCellValue($column, $cell->getCoordinate());
538  $rowPos = $startRow;
539  if ($boldTitle) {
540  $this->setFontStyle(false, $this->styleArray['font']['color']['argb']);
541  }
542  foreach ($TRows as $row) {
543  $rowPos++;
544  $cell = $this->workbook->getActiveSheet()->getCellByColumnAndRow($startColumn, $rowPos);
545  $this->setCellValue($row, $cell->getCoordinate());
546  }
547  $startColumn++;
548  }
549  }
550  } catch (Exception $e) {
551  $this->error = $e->getMessage();
552  return -1;
553  }
554  return 1;
555  }
556 
565  public function setBlock2Columns($startCell, $TDatas = array(), $boldTitle = false)
566  {
567  try {
568  if (!empty($TDatas)) {
569  $startCell = $this->workbook->getActiveSheet()->getCell($startCell);
570  $startColumn = Coordinate::columnIndexFromString($startCell->getColumn());
571  $startRow = $startCell->getRow();
572  foreach ($TDatas as $title => $val) {
573  $cell = $this->workbook->getActiveSheet()->getCellByColumnAndRow($startColumn, $startRow);
574  if ($boldTitle) {
575  $this->setFontStyle(true, $this->styleArray['font']['color']['argb']);
576  }
577  $this->setCellValue($title, $cell->getCoordinate());
578  if ($boldTitle) {
579  $this->setFontStyle(false, $this->styleArray['font']['color']['argb']);
580  }
581  $cell2 = $this->workbook->getActiveSheet()->getCellByColumnAndRow($startColumn + 1, $startRow);
582  $this->setCellValue($val, $cell2->getCoordinate());
583  $startRow++;
584  }
585  }
586  } catch (Exception $e) {
587  $this->error = $e->getMessage();
588  return -1;
589  }
590  return 1;
591  }
592 
600  public function enableAutosize($firstColumn, $lastColumn)
601  {
602  foreach (range($firstColumn, $lastColumn) as $columnID) {
603  $this->workbook->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(true);
604  }
605  return 1;
606  }
607 
617  public function setMergeCellValueByLength($val, $startCell, $length, $offset = 0)
618  {
619  try {
620  $startCell = $this->workbook->getActiveSheet()->getCell($startCell);
621  $startColumn = Coordinate::columnIndexFromString($startCell->getColumn());
622  if (!empty($offset)) {
623  $startColumn += $offset;
624  }
625 
626  $startRow = $startCell->getRow();
627  $startCell = $this->workbook->getActiveSheet()->getCellByColumnAndRow($startColumn, $startRow);
628  $startCoordinate = $startCell->getCoordinate();
629  $this->setCellValue($val, $startCell->getCoordinate());
630 
631  $endCell = $this->workbook->getActiveSheet()->getCellByColumnAndRow($startColumn + ($length - 1), $startRow);
632  $endCoordinate = $endCell->getCoordinate();
633  $this->workbook->getActiveSheet()->mergeCells($startCoordinate.':'.$endCoordinate);
634  } catch (Exception $e) {
635  $this->error = $e->getMessage();
636  return -1;
637  }
638  return $endCoordinate;
639  }
640 }
db
$conf db
API class for accounts.
Definition: inc.php:41
ExportExcel2007\__construct
__construct($db)
Constructor.
Definition: export_excel2007.modules.php:77
ExportExcel2007\getDriverExtension
getDriverExtension()
getDriverExtension
Definition: export_excel2007.modules.php:136
ExportExcel2007\open_file
open_file($file, $outputlangs)
Open output file.
Definition: export_excel2007.modules.php:180
ExportExcel2007\getDriverDesc
getDriverDesc()
getDriverDesc
Definition: export_excel2007.modules.php:126
ExportExcel2007\enableAutosize
enableAutosize($firstColumn, $lastColumn)
Enable auto sizing for column range.
Definition: export_excel2007.modules.php:600
dol_print_error
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
Definition: functions.lib.php:4844
ExportExcel2007\setBorderStyle
setBorderStyle($thickness, $color)
Set border style.
Definition: export_excel2007.modules.php:468
ExportExcel2007\setCellValue
setCellValue($val, $startCell, $endCell='')
Set cell value and automatically merge if we give an endcell.
Definition: export_excel2007.modules.php:440
ExportExcel2007\write_record
write_record($array_selected_sorted, $objp, $outputlangs, $array_types)
Output record line into file.
Definition: export_excel2007.modules.php:291
ExportExcel2007\setBlock2Columns
setBlock2Columns($startCell, $TDatas=array(), $boldTitle=false)
Make a 2xN Tab in Sheet.
Definition: export_excel2007.modules.php:565
ExportExcel2007\getDriverVersion
getDriverVersion()
getDriverVersion
Definition: export_excel2007.modules.php:146
Exception
ExportExcel2007\setMergeCellValueByLength
setMergeCellValueByLength($val, $startCell, $length, $offset=0)
Set a value cell and merging it by giving a starting cell and a length.
Definition: export_excel2007.modules.php:617
ExportExcel2007\getLibLabel
getLibLabel()
getLibLabel
Definition: export_excel2007.modules.php:156
ExportExcel2007\close_file
close_file()
Close Excel file.
Definition: export_excel2007.modules.php:378
ExportExcel2007\getLibVersion
getLibVersion()
getLibVersion
Definition: export_excel2007.modules.php:166
ExportExcel2007\getDriverId
getDriverId()
getDriverId
Definition: export_excel2007.modules.php:106
dol_string_nohtmltag
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
Definition: functions.lib.php:6694
ExportExcel2007
Class to build export files with Excel format.
Definition: export_excel2007.modules.php:35
ExportExcel2007\write_header
write_header($outputlangs)
Write header.
Definition: export_excel2007.modules.php:229
dol_syslog
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Definition: functions.lib.php:1603
ExportExcel2007\setAlignmentStyle
setAlignmentStyle($horizontal)
Set alignment style (horizontal, left, right, ...)
Definition: export_excel2007.modules.php:501
ExportExcel2007\write_footer
write_footer($outputlangs)
Write footer.
Definition: export_excel2007.modules.php:365
ExportExcel2007\resetStyle
resetStyle()
Reset Style.
Definition: export_excel2007.modules.php:511
ExportExcel2007\getDriverLabel
getDriverLabel()
getDriverLabel
Definition: export_excel2007.modules.php:116
ExportExcel2007\setFontStyle
setFontStyle($bold, $color)
Set font style.
Definition: export_excel2007.modules.php:486
ExportExcel2007\setBlock
setBlock($startCell, $TDatas=array(), $boldTitle=false)
Make a NxN Block in sheet.
Definition: export_excel2007.modules.php:525
ModeleExports
Parent class for export modules.
Definition: modules_export.php:31
ExportExcel2007\column2Letter
column2Letter($c)
Convert a column to letter (1->A, 0->B, 27->AA, ...)
Definition: export_excel2007.modules.php:415
ExportExcel2007\write_title
write_title($array_export_fields_label, $array_selected_sorted, $outputlangs, $array_types)
Output title line into file.
Definition: export_excel2007.modules.php:248
dol_stringtotime
dol_stringtotime($string, $gm=1)
Convert a string date into a GM Timestamps date Warning: YYYY-MM-DDTHH:MM:SS+02:00 (RFC3339) is not s...
Definition: date.lib.php:383
ExportExcel2007\excel_clean
excel_clean($newvalue)
Clean a cell to respect rules of Excel file cells.
Definition: export_excel2007.modules.php:399