dolibarr 25.0.0-alpha
import_xlsx.modules.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2006-2012 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2009-2012 Regis Houssin <regis.houssin@inodbox.com>
4 * Copyright (C) 2012 Christophe Battarel <christophe.battarel@altairis.fr>
5 * Copyright (C) 2012-2016 Juanjo Menent <jmenent@2byte.es>
6 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
7 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 * or see https://www.gnu.org/
22 */
23
30use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
31use PhpOffice\PhpSpreadsheet\Spreadsheet;
32use PhpOffice\PhpSpreadsheet\Style\Alignment;
33use PhpOffice\PhpSpreadsheet\Shared\Date;
34
35require_once DOL_DOCUMENT_ROOT . '/core/modules/import/modules_import.class.php';
36
37
42{
46 public $db;
47
51 public $id;
52
57 public $version = 'dolibarr';
58
62 public $label_lib; // Label of external lib used by driver
63
67 public $version_lib; // Version of external lib used by driver
68
72 public $separator;
73
77 public $file; // Path of file
78
82 public $handle; // Handle fichier
83
84 public $cacheconvert = array(); // Array to cache list of value found after a conversion
85
86 public $cachefieldtable = array(); // Array to cache list of value found into fields@tables
87
88 public $nbinsert = 0; // # of insert done during the import
89
90 public $nbupdate = 0; // # of update done during the import
91
95 public $workbook; // temporary import file
96
100 public $record; // current record
101
105 public $headers;
106
110 public $countcolumns = 0; // cached column count to avoid re-parsing the file on each row
111
112
119 public function __construct($db, $datatoimport)
120 {
121 global $langs;
122
123 parent::__construct();
124 $this->db = $db;
125
126 // this is used as an extension from the example file code, so we have to put xlsx here !!!
127 $this->id = 'xlsx'; // Same value as xxx in file name export_xxx.modules.php
128 $this->label = 'Excel 2007'; // Label of driver
129 $this->desc = $langs->trans("Excel2007FormatDesc");
130 $this->extension = 'xlsx'; // Extension for generated file by this driver
131 $this->picto = 'mime/xls'; // Picto (This is not used by the example file code as Mime type, too bad ...)
132 $this->version = '1.0'; // Driver version
133 $this->phpmin = array(7, 1); // Minimum version of PHP required by module
134
135 require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
136 if (versioncompare($this->phpmin, versionphparray()) > 0) {
137 dol_syslog("Module need a higher PHP version");
138 $this->error = "Module need a higher PHP version";
139 return;
140 }
141
142 // If driver use an external library, put its name here
143 require_once DOL_DOCUMENT_ROOT.'/includes/phpoffice/phpspreadsheet/src/autoloader.php';
144 require_once DOL_DOCUMENT_ROOT.'/includes/Psr/autoloader.php';
145 require_once PHPEXCELNEW_PATH.'Spreadsheet.php';
146 $this->workbook = new Spreadsheet();
147
148 // If driver use an external library, put its name here
149 if (!class_exists('ZipArchive')) { // For Excel2007
150 $langs->load("errors");
151 $this->error = $langs->trans('ErrorPHPNeedModule', 'zip');
152 return;
153 }
154 $this->label_lib = 'PhpSpreadSheet';
155 $this->version_lib = '1.8.0';
156
157 $arrayofstreams = stream_get_wrappers();
158 if (!in_array('zip', $arrayofstreams)) {
159 $langs->load("errors");
160 $this->error = $langs->trans('ErrorStreamMustBeEnabled', 'zip');
161 return;
162 }
163
164 $this->datatoimport = $datatoimport;
165 if (preg_match('/^societe_/', $datatoimport)) {
166 $this->thirdpartyobject = new Societe($this->db);
167 }
168 }
169
170
171 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
178 public function write_header_example($outputlangs)
179 {
180 // phpcs:enable
181 global $user, $conf, $langs, $file;
182 // create a temporary object, the final output will be generated in footer
183 $this->workbook->getProperties()->setCreator($user->getFullName($outputlangs) . ' - Dolibarr ' . DOL_VERSION);
184 $this->workbook->getProperties()->setTitle($outputlangs->trans("Import") . ' - ' . $file);
185 $this->workbook->getProperties()->setSubject($outputlangs->trans("Import") . ' - ' . $file);
186 $this->workbook->getProperties()->setDescription($outputlangs->trans("Import") . ' - ' . $file);
187
188 $this->workbook->setActiveSheetIndex(0);
189 $this->workbook->getActiveSheet()->setTitle($outputlangs->trans("Sheet"));
190 $this->workbook->getActiveSheet()->getDefaultRowDimension()->setRowHeight(16);
191
192 return '';
193 }
194
195 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
203 public function write_title_example($outputlangs, $headerlinefields)
204 {
205 // phpcs:enable
206 global $conf;
207 $this->workbook->getActiveSheet()->getStyle('1')->getFont()->setBold(true);
208 $this->workbook->getActiveSheet()->getStyle('1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
209
210 $col = 1;
211 foreach ($headerlinefields as $field) {
212 $this->workbook->getActiveSheet()->SetCellValueByColumnAndRow($col, 1, $outputlangs->transnoentities($field));
213 // set autowidth
214 //$this->workbook->getActiveSheet()->getColumnDimension($this->column2Letter($col + 1))->setAutoSize(true);
215 $col++;
216 }
217
218 return ''; // final output will be generated in footer
219 }
220
221 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
229 public function write_record_example($outputlangs, $contentlinevalues)
230 {
231 // phpcs:enable
232 $col = 1;
233 $row = 2;
234 foreach ($contentlinevalues as $cell) {
235 $this->workbook->getActiveSheet()->SetCellValueByColumnAndRow($col, $row, $cell);
236 $col++;
237 }
238
239 return ''; // final output will be generated in footer
240 }
241
242 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
249 public function write_footer_example($outputlangs)
250 {
251 // phpcs:enable
252 // return the file content as a string
253 $tempfile = tempnam(sys_get_temp_dir(), 'dol');
254 $objWriter = new PhpOffice\PhpSpreadsheet\Writer\Xlsx($this->workbook);
255 $objWriter->save($tempfile);
256 $this->workbook->disconnectWorksheets();
257 unset($this->workbook);
258
259 $content = file_get_contents($tempfile);
260 unlink($tempfile);
261 return $content;
262 }
263
264
265
266 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
273 public function import_open_file($file)
274 {
275 // phpcs:enable
276 $ret = 1;
277
278 dol_syslog(get_class($this) . "::open_file file=" . $file);
279
280 $reader = new Xlsx();
281 $this->workbook = $reader->load($file);
282 $this->record = 1;
283 $this->file = $file;
284
285 return $ret;
286 }
287
288
289 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
296 public function import_get_nb_of_lines($file)
297 {
298 // phpcs:enable
299 $reader = new Xlsx();
300 $this->workbook = $reader->load($file);
301
302 $rowcount = $this->workbook->getActiveSheet()->getHighestDataRow();
303
304 $this->workbook->disconnectWorksheets();
305 unset($this->workbook);
306
307 return $rowcount;
308 }
309
310
311 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
317 public function import_read_header()
318 {
319 // phpcs:enable
320 // This is not called by the import code !!!
321 $this->headers = array();
322 $xlsx = new Xlsx();
323 $info = $xlsx->listWorksheetinfo($this->file);
324 $countcolumns = $info[0]['totalColumns'];
325 for ($col = 1; $col <= $countcolumns; $col++) {
326 $this->headers[$col] = $this->workbook->getActiveSheet()->getCellByColumnAndRow($col, 1)->getValue();
327 }
328 return 0;
329 }
330
331
332 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
338 public function import_read_record()
339 {
340 // phpcs:enable
341 $rowcount = $this->workbook->getActiveSheet()->getHighestDataRow();
342 if ($this->record > $rowcount) {
343 return false;
344 }
345 $array = array();
346
347 if (empty($this->countcolumns)) {
348 $xlsx = new Xlsx();
349 $info = $xlsx->listWorksheetinfo($this->file);
350 $this->countcolumns = $info[0]['totalColumns'];
351 unset($xlsx);
352 }
353 $countcolumns = $this->countcolumns;
354
355 for ($col = 1; $col <= $countcolumns; $col++) {
356 $tmpcell = $this->workbook->getActiveSheet()->getCellByColumnAndRow($col, $this->record);
357
358 $val = $tmpcell->getValue();
359
360 if (Date::isDateTime($tmpcell)) {
361 // For date field, we use the standard date format string.
362 $dateValue = Date::excelToDateTimeObject($val);
363 $val = $dateValue->format('Y-m-d H:i:s');
364 }
365
366 $array[$col]['val'] = trim($val);
367 $array[$col]['type'] = (dol_strlen($val) ? 1 : -1); // If empty we consider it null
368 }
369 $this->record++;
370
371 return $array;
372 }
373
374 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
380 public function import_close_file()
381 {
382 // phpcs:enable
383 $this->workbook->disconnectWorksheets();
384 unset($this->workbook);
385 return 0;
386 }
387
388 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
400 public function import_insert($arrayrecord, $array_match_file_to_database, $objimport, $maxfields, $importid, $updatekeys)
401 {
402 // phpcs:enable
403 return $this->commonImportInsert($arrayrecord, $array_match_file_to_database, $objimport, $maxfields, $importid, $updatekeys, 1);
404 }
405}
versionphparray()
Return version PHP.
versioncompare($versionarray1, $versionarray2)
Compare 2 versions (stored into 2 arrays), to know if a version (a,b,c) is lower than (x,...
Definition admin.lib.php:72
Class to import Excel files.
__construct($db, $datatoimport)
Constructor.
write_record_example($outputlangs, $contentlinevalues)
Output record of an example file for this format.
import_open_file($file)
Open input file.
import_insert($arrayrecord, $array_match_file_to_database, $objimport, $maxfields, $importid, $updatekeys)
Insert a record into database.
write_footer_example($outputlangs)
Output footer of an example file for this format.
import_read_header()
Input header line from file.
write_header_example($outputlangs)
Output header of an example file for this format.
import_read_record()
Return array of next record in input file.
write_title_example($outputlangs, $headerlinefields)
Output title line of an example file for this format.
import_get_nb_of_lines($file)
Return nb of records.
import_close_file()
Close file handle.
Parent class for import file readers.
commonImportInsert($arrayrecord, $array_match_file_to_database, $objimport, $maxfields, $importid, $updatekeys, $recordpositionbase=0)
Shared implementation of import_insert for CSV/XLSX.
Class to manage third parties objects (customers, suppliers, prospects...)
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.