You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

reading-files.md 26 KiB

4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  1. # Reading Files
  2. ## Security
  3. XML-based formats such as OfficeOpen XML, Excel2003 XML, OASIS and
  4. Gnumeric are susceptible to XML External Entity Processing (XXE)
  5. injection attacks when reading spreadsheet files. This can lead to:
  6. - Disclosure whether a file is existent
  7. - Server Side Request Forgery
  8. - Command Execution (depending on the installed PHP wrappers)
  9. To prevent this, by default every XML-based Reader looks for XML
  10. entities declared inside the DOCTYPE and if any is found an exception
  11. is raised.
  12. Read more [about of XXE injection](https://websec.io/2012/08/27/Preventing-XXE-in-PHP.html).
  13. ## Loading a Spreadsheet File
  14. The simplest way to load a workbook file is to let PhpSpreadsheet's IO
  15. Factory identify the file type and load it, calling the static `load()`
  16. method of the `\PhpOffice\PhpSpreadsheet\IOFactory` class.
  17. ``` php
  18. $inputFileName = './sampleData/example1.xls';
  19. /** Load $inputFileName to a Spreadsheet Object **/
  20. $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($inputFileName);
  21. ```
  22. See `samples/Reader/01_Simple_file_reader_using_IOFactory.php` for a working
  23. example of this code.
  24. The `load()` method will attempt to identify the file type, and
  25. instantiate a loader for that file type; using it to load the file and
  26. store the data and any formatting in a `Spreadsheet` object.
  27. The method makes an initial guess at the loader to instantiate based on
  28. the file extension; but will test the file before actually executing the
  29. load: so if (for example) the file is actually a CSV file or contains
  30. HTML markup, but that has been given a .xls extension (quite a common
  31. practise), it will reject the Xls loader that it would normally use for
  32. a .xls file; and test the file using the other loaders until it finds
  33. the appropriate loader, and then use that to read the file.
  34. While easy to implement in your code, and you don't need to worry about
  35. the file type; this isn't the most efficient method to load a file; and
  36. it lacks the flexibility to configure the loader in any way before
  37. actually reading the file into a `Spreadsheet` object.
  38. ## Creating a Reader and Loading a Spreadsheet File
  39. If you know the file type of the spreadsheet file that you need to load,
  40. you can instantiate a new reader object for that file type, then use the
  41. reader's `load()` method to read the file to a `Spreadsheet` object. It is
  42. possible to instantiate the reader objects for each of the different
  43. supported filetype by name. However, you may get unpredictable results
  44. if the file isn't of the right type (e.g. it is a CSV with an extension
  45. of .xls), although this type of exception should normally be trapped.
  46. ``` php
  47. $inputFileName = './sampleData/example1.xls';
  48. /** Create a new Xls Reader **/
  49. $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
  50. // $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
  51. // $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xml();
  52. // $reader = new \PhpOffice\PhpSpreadsheet\Reader\Ods();
  53. // $reader = new \PhpOffice\PhpSpreadsheet\Reader\Slk();
  54. // $reader = new \PhpOffice\PhpSpreadsheet\Reader\Gnumeric();
  55. // $reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv();
  56. /** Load $inputFileName to a Spreadsheet Object **/
  57. $spreadsheet = $reader->load($inputFileName);
  58. ```
  59. See `samples/Reader/02_Simple_file_reader_using_a_specified_reader.php`
  60. for a working example of this code.
  61. Alternatively, you can use the IO Factory's `createReader()` method to
  62. instantiate the reader object for you, simply telling it the file type
  63. of the reader that you want instantiating.
  64. ``` php
  65. $inputFileType = 'Xls';
  66. // $inputFileType = 'Xlsx';
  67. // $inputFileType = 'Xml';
  68. // $inputFileType = 'Ods';
  69. // $inputFileType = 'Slk';
  70. // $inputFileType = 'Gnumeric';
  71. // $inputFileType = 'Csv';
  72. $inputFileName = './sampleData/example1.xls';
  73. /** Create a new Reader of the type defined in $inputFileType **/
  74. $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
  75. /** Load $inputFileName to a Spreadsheet Object **/
  76. $spreadsheet = $reader->load($inputFileName);
  77. ```
  78. See `samples/Reader/03_Simple_file_reader_using_the_IOFactory_to_return_a_reader.php`
  79. for a working example of this code.
  80. If you're uncertain of the filetype, you can use the `IOFactory::identify()`
  81. method to identify the reader that you need, before using the
  82. `createReader()` method to instantiate the reader object.
  83. ``` php
  84. $inputFileName = './sampleData/example1.xls';
  85. /** Identify the type of $inputFileName **/
  86. $inputFileType = \PhpOffice\PhpSpreadsheet\IOFactory::identify($inputFileName);
  87. /** Create a new Reader of the type that has been identified **/
  88. $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
  89. /** Load $inputFileName to a Spreadsheet Object **/
  90. $spreadsheet = $reader->load($inputFileName);
  91. ```
  92. See `samples/Reader/04_Simple_file_reader_using_the_IOFactory_to_identify_a_reader_to_use.php`
  93. for a working example of this code.
  94. ## Spreadsheet Reader Options
  95. Once you have created a reader object for the workbook that you want to
  96. load, you have the opportunity to set additional options before
  97. executing the `load()` method.
  98. ### Reading Only Data from a Spreadsheet File
  99. If you're only interested in the cell values in a workbook, but don't
  100. need any of the cell formatting information, then you can set the reader
  101. to read only the data values and any formulae from each cell using the
  102. `setReadDataOnly()` method.
  103. ``` php
  104. $inputFileType = 'Xls';
  105. $inputFileName = './sampleData/example1.xls';
  106. /** Create a new Reader of the type defined in $inputFileType **/
  107. $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
  108. /** Advise the Reader that we only want to load cell data **/
  109. $reader->setReadDataOnly(true);
  110. /** Load $inputFileName to a Spreadsheet Object **/
  111. $spreadsheet = $reader->load($inputFileName);
  112. ```
  113. See `samples/Reader/05_Simple_file_reader_using_the_read_data_only_option.php`
  114. for a working example of this code.
  115. It is important to note that Workbooks (and PhpSpreadsheet) store dates
  116. and times as simple numeric values: they can only be distinguished from
  117. other numeric values by the format mask that is applied to that cell.
  118. When setting read data only to true, PhpSpreadsheet doesn't read the
  119. cell format masks, so it is not possible to differentiate between
  120. dates/times and numbers.
  121. The Gnumeric loader has been written to read the format masks for date
  122. values even when read data only has been set to true, so it can
  123. differentiate between dates/times and numbers; but this change hasn't
  124. yet been implemented for the other readers.
  125. Reading Only Data from a Spreadsheet File applies to Readers:
  126. Reader | Y/N |Reader | Y/N |Reader | Y/N |
  127. ----------|:---:|--------|:---:|--------------|:---:|
  128. Xlsx | YES | Xls | YES | Xml | YES |
  129. Ods | YES | SYLK | NO | Gnumeric | YES |
  130. CSV | NO | HTML | NO
  131. ### Reading Only Named WorkSheets from a File
  132. If your workbook contains a number of worksheets, but you are only
  133. interested in reading some of those, then you can use the
  134. `setLoadSheetsOnly()` method to identify those sheets you are interested
  135. in reading.
  136. To read a single sheet, you can pass that sheet name as a parameter to
  137. the `setLoadSheetsOnly()` method.
  138. ``` php
  139. $inputFileType = 'Xls';
  140. $inputFileName = './sampleData/example1.xls';
  141. $sheetname = 'Data Sheet #2';
  142. /** Create a new Reader of the type defined in $inputFileType **/
  143. $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
  144. /** Advise the Reader of which WorkSheets we want to load **/
  145. $reader->setLoadSheetsOnly($sheetname);
  146. /** Load $inputFileName to a Spreadsheet Object **/
  147. $spreadsheet = $reader->load($inputFileName);
  148. ```
  149. See `samples/Reader/07_Simple_file_reader_loading_a_single_named_worksheet.php`
  150. for a working example of this code.
  151. If you want to read more than just a single sheet, you can pass a list
  152. of sheet names as an array parameter to the `setLoadSheetsOnly()` method.
  153. ``` php
  154. $inputFileType = 'Xls';
  155. $inputFileName = './sampleData/example1.xls';
  156. $sheetnames = ['Data Sheet #1','Data Sheet #3'];
  157. /** Create a new Reader of the type defined in $inputFileType **/
  158. $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
  159. /** Advise the Reader of which WorkSheets we want to load **/
  160. $reader->setLoadSheetsOnly($sheetnames);
  161. /** Load $inputFileName to a Spreadsheet Object **/
  162. $spreadsheet = $reader->load($inputFileName);
  163. ```
  164. See `samples/Reader/08_Simple_file_reader_loading_several_named_worksheets.php`
  165. for a working example of this code.
  166. To reset this option to the default, you can call the `setLoadAllSheets()`
  167. method.
  168. ``` php
  169. $inputFileType = 'Xls';
  170. $inputFileName = './sampleData/example1.xls';
  171. /** Create a new Reader of the type defined in $inputFileType **/
  172. $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
  173. /** Advise the Reader to load all Worksheets **/
  174. $reader->setLoadAllSheets();
  175. /** Load $inputFileName to a Spreadsheet Object **/
  176. $spreadsheet = $reader->load($inputFileName);
  177. ```
  178. See `samples/Reader/06_Simple_file_reader_loading_all_worksheets.php` for a
  179. working example of this code.
  180. Reading Only Named WorkSheets from a File applies to Readers:
  181. Reader | Y/N |Reader | Y/N |Reader | Y/N |
  182. ----------|:---:|--------|:---:|--------------|:---:|
  183. Xlsx | YES | Xls | YES | Xml | YES |
  184. Ods | YES | SYLK | NO | Gnumeric | YES |
  185. CSV | NO | HTML | NO
  186. ### Reading Only Specific Columns and Rows from a File (Read Filters)
  187. If you are only interested in reading part of a worksheet, then you can
  188. write a filter class that identifies whether or not individual cells
  189. should be read by the loader. A read filter must implement the
  190. `\PhpOffice\PhpSpreadsheet\Reader\IReadFilter` interface, and contain a
  191. `readCell()` method that accepts arguments of `$column`, `$row` and
  192. `$worksheetName`, and return a boolean true or false that indicates
  193. whether a workbook cell identified by those arguments should be read or
  194. not.
  195. ``` php
  196. $inputFileType = 'Xls';
  197. $inputFileName = './sampleData/example1.xls';
  198. $sheetname = 'Data Sheet #3';
  199. /** Define a Read Filter class implementing \PhpOffice\PhpSpreadsheet\Reader\IReadFilter */
  200. class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter
  201. {
  202. public function readCell($column, $row, $worksheetName = '') {
  203. // Read rows 1 to 7 and columns A to E only
  204. if ($row >= 1 && $row <= 7) {
  205. if (in_array($column,range('A','E'))) {
  206. return true;
  207. }
  208. }
  209. return false;
  210. }
  211. }
  212. /** Create an Instance of our Read Filter **/
  213. $filterSubset = new MyReadFilter();
  214. /** Create a new Reader of the type defined in $inputFileType **/
  215. $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
  216. /** Tell the Reader that we want to use the Read Filter **/
  217. $reader->setReadFilter($filterSubset);
  218. /** Load only the rows and columns that match our filter to Spreadsheet **/
  219. $spreadsheet = $reader->load($inputFileName);
  220. ```
  221. See `samples/Reader/09_Simple_file_reader_using_a_read_filter.php` for a
  222. working example of this code.
  223. This example is not particularly useful, because it can only be used in
  224. a very specific circumstance (when you only want cells in the range
  225. A1:E7 from your worksheet. A generic Read Filter would probably be more
  226. useful:
  227. ``` php
  228. /** Define a Read Filter class implementing \PhpOffice\PhpSpreadsheet\Reader\IReadFilter */
  229. class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter
  230. {
  231. private $startRow = 0;
  232. private $endRow = 0;
  233. private $columns = [];
  234. /** Get the list of rows and columns to read */
  235. public function __construct($startRow, $endRow, $columns) {
  236. $this->startRow = $startRow;
  237. $this->endRow = $endRow;
  238. $this->columns = $columns;
  239. }
  240. public function readCell($column, $row, $worksheetName = '') {
  241. // Only read the rows and columns that were configured
  242. if ($row >= $this->startRow && $row <= $this->endRow) {
  243. if (in_array($column,$this->columns)) {
  244. return true;
  245. }
  246. }
  247. return false;
  248. }
  249. }
  250. /** Create an Instance of our Read Filter, passing in the cell range **/
  251. $filterSubset = new MyReadFilter(9,15,range('G','K'));
  252. ```
  253. See `samples/Reader/10_Simple_file_reader_using_a_configurable_read_filter.php`
  254. for a working example of this code.
  255. This can be particularly useful for conserving memory, by allowing you
  256. to read and process a large workbook in "chunks": an example of this
  257. usage might be when transferring data from an Excel worksheet to a
  258. database.
  259. ``` php
  260. $inputFileType = 'Xls';
  261. $inputFileName = './sampleData/example2.xls';
  262. /** Define a Read Filter class implementing \PhpOffice\PhpSpreadsheet\Reader\IReadFilter */
  263. class ChunkReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter
  264. {
  265. private $startRow = 0;
  266. private $endRow = 0;
  267. /** Set the list of rows that we want to read */
  268. public function setRows($startRow, $chunkSize) {
  269. $this->startRow = $startRow;
  270. $this->endRow = $startRow + $chunkSize;
  271. }
  272. public function readCell($column, $row, $worksheetName = '') {
  273. // Only read the heading row, and the configured rows
  274. if (($row == 1) || ($row >= $this->startRow && $row < $this->endRow)) {
  275. return true;
  276. }
  277. return false;
  278. }
  279. }
  280. /** Create a new Reader of the type defined in $inputFileType **/
  281. $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
  282. /** Define how many rows we want to read for each "chunk" **/
  283. $chunkSize = 2048;
  284. /** Create a new Instance of our Read Filter **/
  285. $chunkFilter = new ChunkReadFilter();
  286. /** Tell the Reader that we want to use the Read Filter **/
  287. $reader->setReadFilter($chunkFilter);
  288. /** Loop to read our worksheet in "chunk size" blocks **/
  289. for ($startRow = 2; $startRow <= 65536; $startRow += $chunkSize) {
  290. /** Tell the Read Filter which rows we want this iteration **/
  291. $chunkFilter->setRows($startRow,$chunkSize);
  292. /** Load only the rows that match our filter **/
  293. $spreadsheet = $reader->load($inputFileName);
  294. // Do some processing here
  295. }
  296. ```
  297. See `samples/Reader/12_Reading_a_workbook_in_chunks_using_a_configurable_read_filter_`
  298. for a working example of this code.
  299. Using Read Filters applies to:
  300. Reader | Y/N |Reader | Y/N |Reader | Y/N |
  301. ----------|:---:|--------|:---:|--------------|:---:|
  302. Xlsx | YES | Xls | YES | Xml | YES |
  303. Ods | YES | SYLK | NO | Gnumeric | YES |
  304. CSV | YES | HTML | NO | | |
  305. ### Combining Multiple Files into a Single Spreadsheet Object
  306. While you can limit the number of worksheets that are read from a
  307. workbook file using the `setLoadSheetsOnly()` method, certain readers also
  308. allow you to combine several individual "sheets" from different files
  309. into a single `Spreadsheet` object, where each individual file is a
  310. single worksheet within that workbook. For each file that you read, you
  311. need to indicate which worksheet index it should be loaded into using
  312. the `setSheetIndex()` method of the `$reader`, then use the
  313. `loadIntoExisting()` method rather than the `load()` method to actually read
  314. the file into that worksheet.
  315. ``` php
  316. $inputFileType = 'Csv';
  317. $inputFileNames = [
  318. './sampleData/example1.csv',
  319. './sampleData/example2.csv'
  320. './sampleData/example3.csv'
  321. ];
  322. /** Create a new Reader of the type defined in $inputFileType **/
  323. $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
  324. /** Extract the first named file from the array list **/
  325. $inputFileName = array_shift($inputFileNames);
  326. /** Load the initial file to the first worksheet in a `Spreadsheet` Object **/
  327. $spreadsheet = $reader->load($inputFileName);
  328. /** Set the worksheet title (to the filename that we've loaded) **/
  329. $spreadsheet->getActiveSheet()
  330. ->setTitle(pathinfo($inputFileName,PATHINFO_BASENAME));
  331. /** Loop through all the remaining files in the list **/
  332. foreach($inputFileNames as $sheet => $inputFileName) {
  333. /** Increment the worksheet index pointer for the Reader **/
  334. $reader->setSheetIndex($sheet+1);
  335. /** Load the current file into a new worksheet in Spreadsheet **/
  336. $reader->loadIntoExisting($inputFileName,$spreadsheet);
  337. /** Set the worksheet title (to the filename that we've loaded) **/
  338. $spreadsheet->getActiveSheet()
  339. ->setTitle(pathinfo($inputFileName,PATHINFO_BASENAME));
  340. }
  341. ```
  342. See `samples/Reader/13_Simple_file_reader_for_multiple_CSV_files.php` for a
  343. working example of this code.
  344. Note that using the same sheet index for multiple sheets won't append
  345. files into the same sheet, but overwrite the results of the previous
  346. load. You cannot load multiple CSV files into the same worksheet.
  347. Combining Multiple Files into a Single Spreadsheet Object applies to:
  348. Reader | Y/N |Reader | Y/N |Reader | Y/N |
  349. ----------|:---:|--------|:---:|--------------|:---:|
  350. Xlsx | NO | Xls | NO | Xml | NO |
  351. Ods | NO | SYLK | YES | Gnumeric | NO |
  352. CSV | YES | HTML | NO
  353. ### Combining Read Filters with the `setSheetIndex()` method to split a large CSV file across multiple Worksheets
  354. An Xls BIFF .xls file is limited to 65536 rows in a worksheet, while the
  355. Xlsx Microsoft Office Open XML SpreadsheetML .xlsx file is limited to
  356. 1,048,576 rows in a worksheet; but a CSV file is not limited other than
  357. by available disk space. This means that we wouldn’t ordinarily be able
  358. to read all the rows from a very large CSV file that exceeded those
  359. limits, and save it as an Xls or Xlsx file. However, by using Read
  360. Filters to read the CSV file in "chunks" (using the ChunkReadFilter
  361. Class that we defined in [the above section](#reading-only-specific-columns-and-rows-from-a-file-read-filters),
  362. and the `setSheetIndex()` method of the `$reader`, we can split the CSV
  363. file across several individual worksheets.
  364. ``` php
  365. $inputFileType = 'Csv';
  366. $inputFileName = './sampleData/example2.csv';
  367. echo 'Loading file ',pathinfo($inputFileName,PATHINFO_BASENAME),' using IOFactory with a defined reader type of ',$inputFileType,'<br />';
  368. /** Create a new Reader of the type defined in $inputFileType **/
  369. $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
  370. /** Define how many rows we want to read for each "chunk" **/
  371. $chunkSize = 65530;
  372. /** Create a new Instance of our Read Filter **/
  373. $chunkFilter = new ChunkReadFilter();
  374. /** Tell the Reader that we want to use the Read Filter **/
  375. /** and that we want to store it in contiguous rows/columns **/
  376. $reader->setReadFilter($chunkFilter)
  377. ->setContiguous(true);
  378. /** Instantiate a new Spreadsheet object manually **/
  379. $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
  380. /** Set a sheet index **/
  381. $sheet = 0;
  382. /** Loop to read our worksheet in "chunk size" blocks **/
  383. /** $startRow is set to 2 initially because we always read the headings in row #1 **/
  384. for ($startRow = 2; $startRow <= 1000000; $startRow += $chunkSize) {
  385. /** Tell the Read Filter which rows we want to read this loop **/
  386. $chunkFilter->setRows($startRow,$chunkSize);
  387. /** Increment the worksheet index pointer for the Reader **/
  388. $reader->setSheetIndex($sheet);
  389. /** Load only the rows that match our filter into a new worksheet **/
  390. $reader->loadIntoExisting($inputFileName,$spreadsheet);
  391. /** Set the worksheet title for the sheet that we've justloaded) **/
  392. /** and increment the sheet index as well **/
  393. $spreadsheet->getActiveSheet()->setTitle('Country Data #'.(++$sheet));
  394. }
  395. ```
  396. See `samples/Reader/14_Reading_a_large_CSV_file_in_chunks_to_split_across_multiple_worksheets.php`
  397. for a working example of this code.
  398. This code will read 65,530 rows at a time from the CSV file that we’re
  399. loading, and store each "chunk" in a new worksheet.
  400. The `setContiguous()` method for the Reader is important here. It is
  401. applicable only when working with a Read Filter, and identifies whether
  402. or not the cells should be stored by their position within the CSV file,
  403. or their position relative to the filter.
  404. For example, if the filter returned true for cells in the range B2:C3,
  405. then with setContiguous set to false (the default) these would be loaded
  406. as B2:C3 in the `Spreadsheet` object; but with setContiguous set to
  407. true, they would be loaded as A1:B2.
  408. Splitting a single loaded file across multiple worksheets applies to:
  409. Reader | Y/N |Reader | Y/N |Reader | Y/N |
  410. ----------|:---:|--------|:---:|--------------|:---:|
  411. Xlsx | NO | Xls | NO | Xml | NO |
  412. Ods | NO | SYLK | NO | Gnumeric | NO |
  413. CSV | YES | HTML | NO
  414. ### Pipe or Tab Separated Value Files
  415. The CSV loader will attempt to auto-detect the separator used in the file. If it
  416. cannot auto-detect, it will default to the comma. If this does not fit your
  417. use-case, you can manually specify a separator by using the `setDelimiter()`
  418. method.
  419. ``` php
  420. $inputFileType = 'Csv';
  421. $inputFileName = './sampleData/example1.tsv';
  422. /** Create a new Reader of the type defined in $inputFileType **/
  423. $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
  424. /** Set the delimiter to a TAB character **/
  425. $reader->setDelimiter("\t");
  426. // $reader->setDelimiter('|');
  427. /** Load the file to a Spreadsheet Object **/
  428. $spreadsheet = $reader->load($inputFileName);
  429. ```
  430. See `samples/Reader/15_Simple_file_reader_for_tab_separated_value_file_using_the_Advanced_Value_Binder.php`
  431. for a working example of this code.
  432. In addition to the delimiter, you can also use the following methods to
  433. set other attributes for the data load:
  434. Method | Default
  435. -------------------|----------
  436. setEnclosure() | `"`
  437. setInputEncoding() | `UTF-8`
  438. Setting CSV delimiter applies to:
  439. Reader | Y/N |Reader | Y/N |Reader | Y/N |
  440. ----------|:---:|--------|:---:|--------------|:---:|
  441. Xlsx | NO | Xls | NO | Xml | NO |
  442. Ods | NO | SYLK | NO | Gnumeric | NO |
  443. CSV | YES | HTML | NO
  444. ### A Brief Word about the Advanced Value Binder
  445. When loading data from a file that contains no formatting information,
  446. such as a CSV file, then data is read either as strings or numbers
  447. (float or integer). This means that PhpSpreadsheet does not
  448. automatically recognise dates/times (such as `16-Apr-2009` or `13:30`),
  449. booleans (`true` or `false`), percentages (`75%`), hyperlinks
  450. (`https://www.example.com`), etc as anything other than simple strings.
  451. However, you can apply additional processing that is executed against
  452. these values during the load process within a Value Binder.
  453. A Value Binder is a class that implement the
  454. `\PhpOffice\PhpSpreadsheet\Cell\IValueBinder` interface. It must contain a
  455. `bindValue()` method that accepts a `\PhpOffice\PhpSpreadsheet\Cell\Cell` and a
  456. value as arguments, and return a boolean `true` or `false` that indicates
  457. whether the workbook cell has been populated with the value or not. The
  458. Advanced Value Binder implements such a class: amongst other tests, it
  459. identifies a string comprising "TRUE" or "FALSE" (based on locale
  460. settings) and sets it to a boolean; or a number in scientific format
  461. (e.g. "1.234e-5") and converts it to a float; or dates and times,
  462. converting them to their Excel timestamp value – before storing the
  463. value in the cell object. It also sets formatting for strings that are
  464. identified as dates, times or percentages. It could easily be extended
  465. to provide additional handling (including text or cell formatting) when
  466. it encountered a hyperlink, or HTML markup within a CSV file.
  467. So using a Value Binder allows a great deal more flexibility in the
  468. loader logic when reading unformatted text files.
  469. ``` php
  470. /** Tell PhpSpreadsheet that we want to use the Advanced Value Binder **/
  471. \PhpOffice\PhpSpreadsheet\Cell\Cell::setValueBinder( new \PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder() );
  472. $inputFileType = 'Csv';
  473. $inputFileName = './sampleData/example1.tsv';
  474. $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
  475. $reader->setDelimiter("\t");
  476. $spreadsheet = $reader->load($inputFileName);
  477. ```
  478. See `samples/Reader/15_Simple_file_reader_for_tab_separated_value_file_using_the_Advanced_Value_Binder.php`
  479. for a working example of this code.
  480. Loading using a Value Binder applies to:
  481. Reader | Y/N |Reader | Y/N |Reader | Y/N
  482. ----------|:---:|--------|:---:|--------------|:---:
  483. Xlsx | NO | Xls | NO | Xml | NO
  484. Ods | NO | SYLK | NO | Gnumeric | NO
  485. CSV | YES | HTML | YES
  486. ## Error Handling
  487. Of course, you should always apply some error handling to your scripts
  488. as well. PhpSpreadsheet throws exceptions, so you can wrap all your code
  489. that accesses the library methods within Try/Catch blocks to trap for
  490. any problems that are encountered, and deal with them in an appropriate
  491. manner.
  492. The PhpSpreadsheet Readers throw a
  493. `\PhpOffice\PhpSpreadsheet\Reader\Exception`.
  494. ``` php
  495. $inputFileName = './sampleData/example-1.xls';
  496. try {
  497. /** Load $inputFileName to a Spreadsheet Object **/
  498. $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($inputFileName);
  499. } catch(\PhpOffice\PhpSpreadsheet\Reader\Exception $e) {
  500. die('Error loading file: '.$e->getMessage());
  501. }
  502. ```
  503. See `samples/Reader/16_Handling_loader_exceptions_using_TryCatch.php` for a
  504. working example of this code.
  505. ## Helper Methods
  506. You can retrieve a list of worksheet names contained in a file without
  507. loading the whole file by using the Reader’s `listWorksheetNames()`
  508. method; similarly, a `listWorksheetInfo()` method will retrieve the
  509. dimensions of worksheet in a file without needing to load and parse the
  510. whole file.
  511. ### listWorksheetNames
  512. The `listWorksheetNames()` method returns a simple array listing each
  513. worksheet name within the workbook:
  514. ``` php
  515. $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
  516. $worksheetNames = $reader->listWorksheetNames($inputFileName);
  517. echo '<h3>Worksheet Names</h3>';
  518. echo '<ol>';
  519. foreach ($worksheetNames as $worksheetName) {
  520. echo '<li>', $worksheetName, '</li>';
  521. }
  522. echo '</ol>';
  523. ```
  524. See `samples/Reader/18_Reading_list_of_worksheets_without_loading_entire_file.php`
  525. for a working example of this code.
  526. ### listWorksheetInfo
  527. The `listWorksheetInfo()` method returns a nested array, with each entry
  528. listing the name and dimensions for a worksheet:
  529. ``` php
  530. $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
  531. $worksheetData = $reader->listWorksheetInfo($inputFileName);
  532. echo '<h3>Worksheet Information</h3>';
  533. echo '<ol>';
  534. foreach ($worksheetData as $worksheet) {
  535. echo '<li>', $worksheet['worksheetName'], '<br />';
  536. echo 'Rows: ', $worksheet['totalRows'],
  537. ' Columns: ', $worksheet['totalColumns'], '<br />';
  538. echo 'Cell Range: A1:',
  539. $worksheet['lastColumnLetter'], $worksheet['totalRows'];
  540. echo '</li>';
  541. }
  542. echo '</ol>';
  543. ```
  544. See `samples/Reader/19_Reading_worksheet_information_without_loading_entire_file.php`
  545. for a working example of this code.