dolibarr 24.0.0-beta
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
107
114 public function __construct($db, $datatoimport)
115 {
116 global $langs;
117
118 parent::__construct();
119 $this->db = $db;
120
121 // this is used as an extension from the example file code, so we have to put xlsx here !!!
122 $this->id = 'xlsx'; // Same value as xxx in file name export_xxx.modules.php
123 $this->label = 'Excel 2007'; // Label of driver
124 $this->desc = $langs->trans("Excel2007FormatDesc");
125 $this->extension = 'xlsx'; // Extension for generated file by this driver
126 $this->picto = 'mime/xls'; // Picto (This is not used by the example file code as Mime type, too bad ...)
127 $this->version = '1.0'; // Driver version
128 $this->phpmin = array(7, 1); // Minimum version of PHP required by module
129
130 require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
131 if (versioncompare($this->phpmin, versionphparray()) > 0) {
132 dol_syslog("Module need a higher PHP version");
133 $this->error = "Module need a higher PHP version";
134 return;
135 }
136
137 // If driver use an external library, put its name here
138 require_once DOL_DOCUMENT_ROOT.'/includes/phpoffice/phpspreadsheet/src/autoloader.php';
139 require_once DOL_DOCUMENT_ROOT.'/includes/Psr/autoloader.php';
140 require_once PHPEXCELNEW_PATH.'Spreadsheet.php';
141 $this->workbook = new Spreadsheet();
142
143 // If driver use an external library, put its name here
144 if (!class_exists('ZipArchive')) { // For Excel2007
145 $langs->load("errors");
146 $this->error = $langs->trans('ErrorPHPNeedModule', 'zip');
147 return;
148 }
149 $this->label_lib = 'PhpSpreadSheet';
150 $this->version_lib = '1.8.0';
151
152 $arrayofstreams = stream_get_wrappers();
153 if (!in_array('zip', $arrayofstreams)) {
154 $langs->load("errors");
155 $this->error = $langs->trans('ErrorStreamMustBeEnabled', 'zip');
156 return;
157 }
158
159 $this->datatoimport = $datatoimport;
160 if (preg_match('/^societe_/', $datatoimport)) {
161 $this->thirdpartyobject = new Societe($this->db);
162 }
163 }
164
165
166 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
173 public function write_header_example($outputlangs)
174 {
175 // phpcs:enable
176 global $user, $conf, $langs, $file;
177 // create a temporary object, the final output will be generated in footer
178 $this->workbook->getProperties()->setCreator($user->getFullName($outputlangs) . ' - Dolibarr ' . DOL_VERSION);
179 $this->workbook->getProperties()->setTitle($outputlangs->trans("Import") . ' - ' . $file);
180 $this->workbook->getProperties()->setSubject($outputlangs->trans("Import") . ' - ' . $file);
181 $this->workbook->getProperties()->setDescription($outputlangs->trans("Import") . ' - ' . $file);
182
183 $this->workbook->setActiveSheetIndex(0);
184 $this->workbook->getActiveSheet()->setTitle($outputlangs->trans("Sheet"));
185 $this->workbook->getActiveSheet()->getDefaultRowDimension()->setRowHeight(16);
186
187 return '';
188 }
189
190 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
198 public function write_title_example($outputlangs, $headerlinefields)
199 {
200 // phpcs:enable
201 global $conf;
202 $this->workbook->getActiveSheet()->getStyle('1')->getFont()->setBold(true);
203 $this->workbook->getActiveSheet()->getStyle('1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
204
205 $col = 1;
206 foreach ($headerlinefields as $field) {
207 $this->workbook->getActiveSheet()->SetCellValueByColumnAndRow($col, 1, $outputlangs->transnoentities($field));
208 // set autowidth
209 //$this->workbook->getActiveSheet()->getColumnDimension($this->column2Letter($col + 1))->setAutoSize(true);
210 $col++;
211 }
212
213 return ''; // final output will be generated in footer
214 }
215
216 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
224 public function write_record_example($outputlangs, $contentlinevalues)
225 {
226 // phpcs:enable
227 $col = 1;
228 $row = 2;
229 foreach ($contentlinevalues as $cell) {
230 $this->workbook->getActiveSheet()->SetCellValueByColumnAndRow($col, $row, $cell);
231 $col++;
232 }
233
234 return ''; // final output will be generated in footer
235 }
236
237 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
244 public function write_footer_example($outputlangs)
245 {
246 // phpcs:enable
247 // return the file content as a string
248 $tempfile = tempnam(sys_get_temp_dir(), 'dol');
249 $objWriter = new PhpOffice\PhpSpreadsheet\Writer\Xlsx($this->workbook);
250 $objWriter->save($tempfile);
251 $this->workbook->disconnectWorksheets();
252 unset($this->workbook);
253
254 $content = file_get_contents($tempfile);
255 unlink($tempfile);
256 return $content;
257 }
258
259
260
261 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
268 public function import_open_file($file)
269 {
270 // phpcs:enable
271 $ret = 1;
272
273 dol_syslog(get_class($this) . "::open_file file=" . $file);
274
275 $reader = new Xlsx();
276 $this->workbook = $reader->load($file);
277 $this->record = 1;
278 $this->file = $file;
279
280 return $ret;
281 }
282
283
284 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
291 public function import_get_nb_of_lines($file)
292 {
293 // phpcs:enable
294 $reader = new Xlsx();
295 $this->workbook = $reader->load($file);
296
297 $rowcount = $this->workbook->getActiveSheet()->getHighestDataRow();
298
299 $this->workbook->disconnectWorksheets();
300 unset($this->workbook);
301
302 return $rowcount;
303 }
304
305
306 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
312 public function import_read_header()
313 {
314 // phpcs:enable
315 // This is not called by the import code !!!
316 $this->headers = array();
317 $xlsx = new Xlsx();
318 $info = $xlsx->listWorksheetinfo($this->file);
319 $countcolumns = $info[0]['totalColumns'];
320 for ($col = 1; $col <= $countcolumns; $col++) {
321 $this->headers[$col] = $this->workbook->getActiveSheet()->getCellByColumnAndRow($col, 1)->getValue();
322 }
323 return 0;
324 }
325
326
327 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
333 public function import_read_record()
334 {
335 // phpcs:enable
336 $rowcount = $this->workbook->getActiveSheet()->getHighestDataRow();
337 if ($this->record > $rowcount) {
338 return false;
339 }
340 $array = array();
341
342 $xlsx = new Xlsx();
343 $info = $xlsx->listWorksheetinfo($this->file);
344 $countcolumns = $info[0]['totalColumns'];
345
346 for ($col = 1; $col <= $countcolumns; $col++) {
347 $tmpcell = $this->workbook->getActiveSheet()->getCellByColumnAndRow($col, $this->record);
348
349 $val = $tmpcell->getValue();
350
351 if (Date::isDateTime($tmpcell)) {
352 // For date field, we use the standard date format string.
353 $dateValue = Date::excelToDateTimeObject($val);
354 $val = $dateValue->format('Y-m-d H:i:s');
355 }
356
357 $array[$col]['val'] = trim($val);
358 $array[$col]['type'] = (dol_strlen($val) ? 1 : -1); // If empty we consider it null
359 }
360 $this->record++;
361
362 unset($xlsx);
363
364 return $array;
365 }
366
367 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
373 public function import_close_file()
374 {
375 // phpcs:enable
376 $this->workbook->disconnectWorksheets();
377 unset($this->workbook);
378 return 0;
379 }
380
381 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
393 public function import_insert($arrayrecord, $array_match_file_to_database, $objimport, $maxfields, $importid, $updatekeys)
394 {
395 // phpcs:enable
396 return $this->commonImportInsert($arrayrecord, $array_match_file_to_database, $objimport, $maxfields, $importid, $updatekeys, 1);
397 }
398}
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.