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-and-writing-to-file.md 27 KiB

4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928
  1. # Reading and writing to file
  2. As you already know from the [architecture](./architecture.md#readers-and-writers),
  3. reading and writing to a
  4. persisted storage is not possible using the base PhpSpreadsheet classes.
  5. For this purpose, PhpSpreadsheet provides readers and writers, which are
  6. implementations of `\PhpOffice\PhpSpreadsheet\Reader\IReader` and
  7. `\PhpOffice\PhpSpreadsheet\Writer\IWriter`.
  8. ## \PhpOffice\PhpSpreadsheet\IOFactory
  9. The PhpSpreadsheet API offers multiple methods to create a
  10. `\PhpOffice\PhpSpreadsheet\Reader\IReader` or
  11. `\PhpOffice\PhpSpreadsheet\Writer\IWriter` instance:
  12. Direct creation via `\PhpOffice\PhpSpreadsheet\IOFactory`. All examples
  13. underneath demonstrate the direct creation method. Note that you can
  14. also use the `\PhpOffice\PhpSpreadsheet\IOFactory` class to do this.
  15. ### Creating `\PhpOffice\PhpSpreadsheet\Reader\IReader` using `\PhpOffice\PhpSpreadsheet\IOFactory`
  16. There are 2 methods for reading in a file into PhpSpreadsheet: using
  17. automatic file type resolving or explicitly.
  18. Automatic file type resolving checks the different
  19. `\PhpOffice\PhpSpreadsheet\Reader\IReader` distributed with
  20. PhpSpreadsheet. If one of them can load the specified file name, the
  21. file is loaded using that `\PhpOffice\PhpSpreadsheet\Reader\IReader`.
  22. Explicit mode requires you to specify which
  23. `\PhpOffice\PhpSpreadsheet\Reader\IReader` should be used.
  24. You can create a `\PhpOffice\PhpSpreadsheet\Reader\IReader` instance using
  25. `\PhpOffice\PhpSpreadsheet\IOFactory` in automatic file type resolving
  26. mode using the following code sample:
  27. ``` php
  28. $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load("05featuredemo.xlsx");
  29. ```
  30. A typical use of this feature is when you need to read files uploaded by
  31. your users, and you don’t know whether they are uploading xls or xlsx
  32. files.
  33. If you need to set some properties on the reader, (e.g. to only read
  34. data, see more about this later), then you may instead want to use this
  35. variant:
  36. ``` php
  37. $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReaderForFile("05featuredemo.xlsx");
  38. $reader->setReadDataOnly(true);
  39. $reader->load("05featuredemo.xlsx");
  40. ```
  41. You can create a `\PhpOffice\PhpSpreadsheet\Reader\IReader` instance using
  42. `\PhpOffice\PhpSpreadsheet\IOFactory` in explicit mode using the following
  43. code sample:
  44. ``` php
  45. $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader("Xlsx");
  46. $spreadsheet = $reader->load("05featuredemo.xlsx");
  47. ```
  48. Note that automatic type resolving mode is slightly slower than explicit
  49. mode.
  50. ### Creating `\PhpOffice\PhpSpreadsheet\Writer\IWriter` using `\PhpOffice\PhpSpreadsheet\IOFactory`
  51. You can create a `\PhpOffice\PhpSpreadsheet\Writer\IWriter` instance using
  52. `\PhpOffice\PhpSpreadsheet\IOFactory`:
  53. ``` php
  54. $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, "Xlsx");
  55. $writer->save("05featuredemo.xlsx");
  56. ```
  57. ## Excel 2007 (SpreadsheetML) file format
  58. Xlsx file format is the main file format of PhpSpreadsheet. It allows
  59. outputting the in-memory spreadsheet to a .xlsx file.
  60. ### \PhpOffice\PhpSpreadsheet\Reader\Xlsx
  61. #### Reading a spreadsheet
  62. You can read an .xlsx file using the following code:
  63. ``` php
  64. $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
  65. $spreadsheet = $reader->load("05featuredemo.xlsx");
  66. ```
  67. #### Read data only
  68. You can set the option setReadDataOnly on the reader, to instruct the
  69. reader to ignore styling, data validation, … and just read cell data:
  70. ``` php
  71. $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
  72. $reader->setReadDataOnly(true);
  73. $spreadsheet = $reader->load("05featuredemo.xlsx");
  74. ```
  75. #### Read specific sheets only
  76. You can set the option setLoadSheetsOnly on the reader, to instruct the
  77. reader to only load the sheets with a given name:
  78. ``` php
  79. $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
  80. $reader->setLoadSheetsOnly(["Sheet 1", "My special sheet"]);
  81. $spreadsheet = $reader->load("05featuredemo.xlsx");
  82. ```
  83. #### Read specific cells only
  84. You can set the option setReadFilter on the reader, to instruct the
  85. reader to only load the cells which match a given rule. A read filter
  86. can be any class which implements
  87. `\PhpOffice\PhpSpreadsheet\Reader\IReadFilter`. By default, all cells are
  88. read using the `\PhpOffice\PhpSpreadsheet\Reader\DefaultReadFilter`.
  89. The following code will only read row 1 and rows 20 – 30 of any sheet in
  90. the Excel file:
  91. ``` php
  92. class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter {
  93. public function readCell($column, $row, $worksheetName = '') {
  94. // Read title row and rows 20 - 30
  95. if ($row == 1 || ($row >= 20 && $row <= 30)) {
  96. return true;
  97. }
  98. return false;
  99. }
  100. }
  101. $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
  102. $reader->setReadFilter( new MyReadFilter() );
  103. $spreadsheet = $reader->load("06largescale.xlsx");
  104. ```
  105. ### \PhpOffice\PhpSpreadsheet\Writer\Xlsx
  106. #### Writing a spreadsheet
  107. You can write an .xlsx file using the following code:
  108. ``` php
  109. $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
  110. $writer->save("05featuredemo.xlsx");
  111. ```
  112. #### Formula pre-calculation
  113. By default, this writer pre-calculates all formulas in the spreadsheet.
  114. This can be slow on large spreadsheets, and maybe even unwanted. You can
  115. however disable formula pre-calculation:
  116. ``` php
  117. $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
  118. $writer->setPreCalculateFormulas(false);
  119. $writer->save("05featuredemo.xlsx");
  120. ```
  121. #### Office 2003 compatibility pack
  122. Because of a bug in the Office2003 compatibility pack, there can be some
  123. small issues when opening Xlsx spreadsheets (mostly related to formula
  124. calculation). You can enable Office2003 compatibility with the following
  125. code:
  126. $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
  127. $writer->setOffice2003Compatibility(true);
  128. $writer->save("05featuredemo.xlsx");
  129. **Office2003 compatibility option should only be used when needed** because
  130. it disables several Office2007 file format options, resulting in a
  131. lower-featured Office2007 spreadsheet.
  132. ## Excel 5 (BIFF) file format
  133. Xls file format is the old Excel file format, implemented in
  134. PhpSpreadsheet to provide a uniform manner to create both .xlsx and .xls
  135. files. It is basically a modified version of [PEAR
  136. Spreadsheet\_Excel\_Writer](https://pear.php.net/package/Spreadsheet_Excel_Writer),
  137. although it has been extended and has fewer limitations and more
  138. features than the old PEAR library. This can read all BIFF versions that
  139. use OLE2: BIFF5 (introduced with office 95) through BIFF8, but cannot
  140. read earlier versions.
  141. Xls file format will not be developed any further, it just provides an
  142. additional file format for PhpSpreadsheet.
  143. **Excel5 (BIFF) limitations** Please note that BIFF file format has some
  144. limits regarding to styling cells and handling large spreadsheets via
  145. PHP.
  146. ### \PhpOffice\PhpSpreadsheet\Reader\Xls
  147. #### Reading a spreadsheet
  148. You can read an .xls file using the following code:
  149. ``` php
  150. $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
  151. $spreadsheet = $reader->load("05featuredemo.xls");
  152. ```
  153. #### Read data only
  154. You can set the option setReadDataOnly on the reader, to instruct the
  155. reader to ignore styling, data validation, … and just read cell data:
  156. ``` php
  157. $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
  158. $reader->setReadDataOnly(true);
  159. $spreadsheet = $reader->load("05featuredemo.xls");
  160. ```
  161. #### Read specific sheets only
  162. You can set the option setLoadSheetsOnly on the reader, to instruct the
  163. reader to only load the sheets with a given name:
  164. ``` php
  165. $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
  166. $reader->setLoadSheetsOnly(["Sheet 1", "My special sheet"]);
  167. $spreadsheet = $reader->load("05featuredemo.xls");
  168. ```
  169. #### Read specific cells only
  170. You can set the option setReadFilter on the reader, to instruct the
  171. reader to only load the cells which match a given rule. A read filter
  172. can be any class which implements
  173. `\PhpOffice\PhpSpreadsheet\Reader\IReadFilter`. By default, all cells are
  174. read using the `\PhpOffice\PhpSpreadsheet\Reader\DefaultReadFilter`.
  175. The following code will only read row 1 and rows 20 to 30 of any sheet
  176. in the Excel file:
  177. ``` php
  178. class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter {
  179. public function readCell($column, $row, $worksheetName = '') {
  180. // Read title row and rows 20 - 30
  181. if ($row == 1 || ($row >= 20 && $row <= 30)) {
  182. return true;
  183. }
  184. return false;
  185. }
  186. }
  187. $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
  188. $reader->setReadFilter( new MyReadFilter() );
  189. $spreadsheet = $reader->load("06largescale.xls");
  190. ```
  191. ### \PhpOffice\PhpSpreadsheet\Writer\Xls
  192. #### Writing a spreadsheet
  193. You can write an .xls file using the following code:
  194. ``` php
  195. $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xls($spreadsheet);
  196. $writer->save("05featuredemo.xls");
  197. ```
  198. ## Excel 2003 XML file format
  199. Excel 2003 XML file format is a file format which can be used in older
  200. versions of Microsoft Excel.
  201. **Excel 2003 XML limitations** Please note that Excel 2003 XML format
  202. has some limits regarding to styling cells and handling large
  203. spreadsheets via PHP.
  204. ### \PhpOffice\PhpSpreadsheet\Reader\Xml
  205. #### Reading a spreadsheet
  206. You can read an Excel 2003 .xml file using the following code:
  207. ``` php
  208. $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xml();
  209. $spreadsheet = $reader->load("05featuredemo.xml");
  210. ```
  211. #### Read specific cells only
  212. You can set the option setReadFilter on the reader, to instruct the
  213. reader to only load the cells which match a given rule. A read filter
  214. can be any class which implements
  215. `\PhpOffice\PhpSpreadsheet\Reader\IReadFilter`. By default, all cells are
  216. read using the `\PhpOffice\PhpSpreadsheet\Reader\DefaultReadFilter`.
  217. The following code will only read row 1 and rows 20 to 30 of any sheet
  218. in the Excel file:
  219. ``` php
  220. class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter {
  221. public function readCell($column, $row, $worksheetName = '') {
  222. // Read title row and rows 20 - 30
  223. if ($row == 1 || ($row >= 20 && $row <= 30)) {
  224. return true;
  225. }
  226. return false;
  227. }
  228. }
  229. $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xml();
  230. $reader->setReadFilter( new MyReadFilter() );
  231. $spreadsheet = $reader->load("06largescale.xml");
  232. ```
  233. ## Symbolic LinK (SYLK)
  234. Symbolic Link (SYLK) is a Microsoft file format typically used to
  235. exchange data between applications, specifically spreadsheets. SYLK
  236. files conventionally have a .slk suffix. Composed of only displayable
  237. ANSI characters, it can be easily created and processed by other
  238. applications, such as databases.
  239. **SYLK limitations** Please note that SYLK file format has some limits
  240. regarding to styling cells and handling large spreadsheets via PHP.
  241. ### \PhpOffice\PhpSpreadsheet\Reader\Slk
  242. #### Reading a spreadsheet
  243. You can read an .slk file using the following code:
  244. ``` php
  245. $reader = new \PhpOffice\PhpSpreadsheet\Reader\Slk();
  246. $spreadsheet = $reader->load("05featuredemo.slk");
  247. ```
  248. #### Read specific cells only
  249. You can set the option setReadFilter on the reader, to instruct the
  250. reader to only load the cells which match a given rule. A read filter
  251. can be any class which implements
  252. `\PhpOffice\PhpSpreadsheet\Reader\IReadFilter`. By default, all cells are
  253. read using the `\PhpOffice\PhpSpreadsheet\Reader\DefaultReadFilter`.
  254. The following code will only read row 1 and rows 20 to 30 of any sheet
  255. in the SYLK file:
  256. ``` php
  257. class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter {
  258. public function readCell($column, $row, $worksheetName = '') {
  259. // Read title row and rows 20 - 30
  260. if ($row == 1 || ($row >= 20 && $row <= 30)) {
  261. return true;
  262. }
  263. return false;
  264. }
  265. }
  266. $reader = new \PhpOffice\PhpSpreadsheet\Reader\Slk();
  267. $reader->setReadFilter( new MyReadFilter() );
  268. $spreadsheet = $reader->load("06largescale.slk");
  269. ```
  270. ## Open/Libre Office (.ods)
  271. Open Office or Libre Office .ods files are the standard file format for
  272. Open Office or Libre Office Calc files.
  273. ### \PhpOffice\PhpSpreadsheet\Reader\Ods
  274. #### Reading a spreadsheet
  275. You can read an .ods file using the following code:
  276. ``` php
  277. $reader = new \PhpOffice\PhpSpreadsheet\Reader\Ods();
  278. $spreadsheet = $reader->load("05featuredemo.ods");
  279. ```
  280. #### Read specific cells only
  281. You can set the option setReadFilter on the reader, to instruct the
  282. reader to only load the cells which match a given rule. A read filter
  283. can be any class which implements
  284. `\PhpOffice\PhpSpreadsheet\Reader\IReadFilter`. By default, all cells are
  285. read using the `\PhpOffice\PhpSpreadsheet\Reader\DefaultReadFilter`.
  286. The following code will only read row 1 and rows 20 to 30 of any sheet
  287. in the Calc file:
  288. ``` php
  289. class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter {
  290. public function readCell($column, $row, $worksheetName = '') {
  291. // Read title row and rows 20 - 30
  292. if ($row == 1 || ($row >= 20 && $row <= 30)) {
  293. return true;
  294. }
  295. return false;
  296. }
  297. }
  298. $reader = new PhpOffice\PhpSpreadsheet\Reader\Ods();
  299. $reader->setReadFilter( new MyReadFilter() );
  300. $spreadsheet = $reader->load("06largescale.ods");
  301. ```
  302. ## CSV (Comma Separated Values)
  303. CSV (Comma Separated Values) are often used as an import/export file
  304. format with other systems. PhpSpreadsheet allows reading and writing to
  305. CSV files.
  306. **CSV limitations** Please note that CSV file format has some limits
  307. regarding to styling cells, number formatting, ...
  308. ### \PhpOffice\PhpSpreadsheet\Reader\Csv
  309. #### Reading a CSV file
  310. You can read a .csv file using the following code:
  311. ``` php
  312. $reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv();
  313. $spreadsheet = $reader->load("sample.csv");
  314. ```
  315. #### Setting CSV options
  316. Often, CSV files are not really "comma separated", or use semicolon (`;`)
  317. as a separator. You can instruct
  318. `\PhpOffice\PhpSpreadsheet\Reader\Csv` some options before reading a CSV
  319. file.
  320. The separator will be auto-detected, so in most cases it should not be necessary
  321. to specify it. But in cases where auto-detection does not fit the use-case, then
  322. it can be set manually.
  323. Note that `\PhpOffice\PhpSpreadsheet\Reader\Csv` by default assumes that
  324. the loaded CSV file is UTF-8 encoded. If you are reading CSV files that
  325. were created in Microsoft Office Excel the correct input encoding may
  326. rather be Windows-1252 (CP1252). Always make sure that the input
  327. encoding is set appropriately.
  328. ``` php
  329. $reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv();
  330. $reader->setInputEncoding('CP1252');
  331. $reader->setDelimiter(';');
  332. $reader->setEnclosure('');
  333. $reader->setSheetIndex(0);
  334. $spreadsheet = $reader->load("sample.csv");
  335. ```
  336. #### Read a specific worksheet
  337. CSV files can only contain one worksheet. Therefore, you can specify
  338. which sheet to read from CSV:
  339. ``` php
  340. $reader->setSheetIndex(0);
  341. ```
  342. #### Read into existing spreadsheet
  343. When working with CSV files, it might occur that you want to import CSV
  344. data into an existing `Spreadsheet` object. The following code loads a
  345. CSV file into an existing `$spreadsheet` containing some sheets, and
  346. imports onto the 6th sheet:
  347. ``` php
  348. $reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv();
  349. $reader->setDelimiter(';');
  350. $reader->setEnclosure('');
  351. $reader->setSheetIndex(5);
  352. $reader->loadIntoExisting("05featuredemo.csv", $spreadsheet);
  353. ```
  354. ### \PhpOffice\PhpSpreadsheet\Writer\Csv
  355. #### Writing a CSV file
  356. You can write a .csv file using the following code:
  357. ``` php
  358. $writer = new \PhpOffice\PhpSpreadsheet\Writer\Csv($spreadsheet);
  359. $writer->save("05featuredemo.csv");
  360. ```
  361. #### Setting CSV options
  362. Often, CSV files are not really "comma separated", or use semicolon (`;`)
  363. as a separator. You can instruct
  364. `\PhpOffice\PhpSpreadsheet\Writer\Csv` some options before writing a CSV
  365. file:
  366. ``` php
  367. $writer = new \PhpOffice\PhpSpreadsheet\Writer\Csv($spreadsheet);
  368. $writer->setDelimiter(';');
  369. $writer->setEnclosure('');
  370. $writer->setLineEnding("\r\n");
  371. $writer->setSheetIndex(0);
  372. $writer->save("05featuredemo.csv");
  373. ```
  374. #### Write a specific worksheet
  375. CSV files can only contain one worksheet. Therefore, you can specify
  376. which sheet to write to CSV:
  377. ``` php
  378. $writer->setSheetIndex(0);
  379. ```
  380. #### Formula pre-calculation
  381. By default, this writer pre-calculates all formulas in the spreadsheet.
  382. This can be slow on large spreadsheets, and maybe even unwanted. You can
  383. however disable formula pre-calculation:
  384. ``` php
  385. $writer = new \PhpOffice\PhpSpreadsheet\Writer\Csv($spreadsheet);
  386. $writer->setPreCalculateFormulas(false);
  387. $writer->save("05featuredemo.csv");
  388. ```
  389. #### Writing UTF-8 CSV files
  390. A CSV file can be marked as UTF-8 by writing a BOM file header. This can
  391. be enabled by using the following code:
  392. ``` php
  393. $writer = new \PhpOffice\PhpSpreadsheet\Writer\Csv($spreadsheet);
  394. $writer->setUseBOM(true);
  395. $writer->save("05featuredemo.csv");
  396. ```
  397. #### Decimal and thousands separators
  398. If the worksheet you are exporting contains numbers with decimal or
  399. thousands separators then you should think about what characters you
  400. want to use for those before doing the export.
  401. By default PhpSpreadsheet looks up in the server's locale settings to
  402. decide what characters to use. But to avoid problems it is recommended
  403. to set the characters explicitly as shown below.
  404. English users will want to use this before doing the export:
  405. ``` php
  406. \PhpOffice\PhpSpreadsheet\Shared\StringHelper::setDecimalSeparator('.');
  407. \PhpOffice\PhpSpreadsheet\Shared\StringHelper::setThousandsSeparator(',');
  408. ```
  409. German users will want to use the opposite values.
  410. ``` php
  411. \PhpOffice\PhpSpreadsheet\Shared\StringHelper::setDecimalSeparator(',');
  412. \PhpOffice\PhpSpreadsheet\Shared\StringHelper::setThousandsSeparator('.');
  413. ```
  414. Note that the above code sets decimal and thousand separators as global
  415. options. This also affects how HTML and PDF is exported.
  416. ## HTML
  417. PhpSpreadsheet allows you to read or write a spreadsheet as HTML format,
  418. for quick representation of the data in it to anyone who does not have a
  419. spreadsheet application on their PC, or loading files saved by other
  420. scripts that simply create HTML markup and give it a .xls file
  421. extension.
  422. **HTML limitations** Please note that HTML file format has some limits
  423. regarding to styling cells, number formatting, ...
  424. ### \PhpOffice\PhpSpreadsheet\Reader\Html
  425. #### Reading a spreadsheet
  426. You can read an .html or .htm file using the following code:
  427. ``` php
  428. $reader = new \PhpOffice\PhpSpreadsheet\Reader\Html();
  429. $spreadsheet = $reader->load("05featuredemo.html");
  430. ```
  431. **HTML limitations** Please note that HTML reader is still experimental
  432. and does not yet support merged cells or nested tables cleanly
  433. ### \PhpOffice\PhpSpreadsheet\Writer\Html
  434. Please note that `\PhpOffice\PhpSpreadsheet\Writer\Html` only outputs the
  435. first worksheet by default.
  436. #### Writing a spreadsheet
  437. You can write a .htm file using the following code:
  438. ``` php
  439. $writer = new \PhpOffice\PhpSpreadsheet\Writer\Html($spreadsheet);
  440. $writer->save("05featuredemo.htm");
  441. ```
  442. #### Write all worksheets
  443. HTML files can contain one or more worksheets. If you want to write all
  444. sheets into a single HTML file, use the following code:
  445. ``` php
  446. $writer->writeAllSheets();
  447. ```
  448. #### Write a specific worksheet
  449. HTML files can contain one or more worksheets. Therefore, you can
  450. specify which sheet to write to HTML:
  451. ``` php
  452. $writer->setSheetIndex(0);
  453. ```
  454. #### Setting the images root of the HTML file
  455. There might be situations where you want to explicitly set the included
  456. images root. For example, instead of:
  457. ``` html
  458. <img src="./images/logo.jpg">
  459. ```
  460. You might want to see:
  461. ``` html
  462. <img src="http://www.domain.com/images/logo.jpg">
  463. ```
  464. You can use the following code to achieve this result:
  465. ``` php
  466. $writer->setImagesRoot('http://www.example.com');
  467. ```
  468. #### Formula pre-calculation
  469. By default, this writer pre-calculates all formulas in the spreadsheet.
  470. This can be slow on large spreadsheets, and maybe even unwanted. You can
  471. however disable formula pre-calculation:
  472. ``` php
  473. $writer = new \PhpOffice\PhpSpreadsheet\Writer\Html($spreadsheet);
  474. $writer->setPreCalculateFormulas(false);
  475. $writer->save("05featuredemo.htm");
  476. ```
  477. #### Embedding generated HTML in a web page
  478. There might be a situation where you want to embed the generated HTML in
  479. an existing website. \PhpOffice\PhpSpreadsheet\Writer\Html provides
  480. support to generate only specific parts of the HTML code, which allows
  481. you to use these parts in your website.
  482. Supported methods:
  483. - `generateHTMLHeader()`
  484. - `generateStyles()`
  485. - `generateSheetData()`
  486. - `generateHTMLFooter()`
  487. Here's an example which retrieves all parts independently and merges
  488. them into a resulting HTML page:
  489. ``` php
  490. <?php
  491. $writer = new \PhpOffice\PhpSpreadsheet\Writer\Html($spreadsheet);
  492. echo $writer->generateHTMLHeader();
  493. ?>
  494. <style>
  495. <!--
  496. html {
  497. font-family: Times New Roman;
  498. font-size: 9pt;
  499. background-color: white;
  500. }
  501. <?php
  502. echo $writer->generateStyles(false); // do not write <style> and </style>
  503. ?>
  504. -->
  505. </style>
  506. <?php
  507. echo $writer->generateSheetData();
  508. echo $writer->generateHTMLFooter();
  509. ?>
  510. ```
  511. #### Writing UTF-8 HTML files
  512. A HTML file can be marked as UTF-8 by writing a BOM file header. This
  513. can be enabled by using the following code:
  514. ``` php
  515. $writer = new \PhpOffice\PhpSpreadsheet\Writer\Html($spreadsheet);
  516. $writer->setUseBOM(true);
  517. $writer->save("05featuredemo.htm");
  518. ```
  519. #### Decimal and thousands separators
  520. See section `\PhpOffice\PhpSpreadsheet\Writer\Csv` how to control the
  521. appearance of these.
  522. ## PDF
  523. PhpSpreadsheet allows you to write a spreadsheet into PDF format, for
  524. fast distribution of represented data.
  525. **PDF limitations** Please note that PDF file format has some limits
  526. regarding to styling cells, number formatting, ...
  527. ### \PhpOffice\PhpSpreadsheet\Writer\Pdf
  528. PhpSpreadsheet’s PDF Writer is a wrapper for a 3rd-Party PDF Rendering
  529. library such as TCPDF, mPDF or Dompdf. You must now install a PDF
  530. rendering library yourself; but PhpSpreadsheet will work with a number
  531. of different libraries.
  532. Currently, the following libraries are supported:
  533. Library | Downloadable from | PhpSpreadsheet writer
  534. --------|-------------------------------------|----------------------
  535. TCPDF | https://github.com/tecnickcom/tcpdf | Tcpdf
  536. mPDF | https://github.com/mpdf/mpdf | Mpdf
  537. Dompdf | https://github.com/dompdf/dompdf | Dompdf
  538. The different libraries have different strengths and weaknesses. Some
  539. generate better formatted output than others, some are faster or use
  540. less memory than others, while some generate smaller .pdf files. It is
  541. the developers choice which one they wish to use, appropriate to their
  542. own circumstances.
  543. You can instantiate a writer with its specific name, like so:
  544. ``` php
  545. $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Mpdf');
  546. ```
  547. Or you can register which writer you are using with a more generic name,
  548. so you don't need to remember which library you chose, only that you want
  549. to write PDF files:
  550. ``` php
  551. $class = \PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf::class;
  552. \PhpOffice\PhpSpreadsheet\IOFactory::registerWriter('Pdf', $class);
  553. $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Pdf');
  554. ```
  555. Or you can instantiate directly the writer of your choice like so:
  556. ``` php
  557. $writer = \PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf($spreadsheet);
  558. ```
  559. #### Custom implementation or configuration
  560. If you need a custom implementation, or custom configuration, of a supported
  561. PDF library. You can extends the PDF library, and the PDF writer like so:
  562. ``` php
  563. class My_Custom_TCPDF extends TCPDF
  564. {
  565. // ...
  566. }
  567. class My_Custom_TCPDF_Writer extends \PhpOffice\PhpSpreadsheet\Writer\Pdf\Tcpdf
  568. {
  569. protected function createExternalWriterInstance($orientation, $unit, $paperSize)
  570. {
  571. $instance = new My_Custom_TCPDF($orientation, $unit, $paperSize);
  572. // more configuration of $instance
  573. return $instance;
  574. }
  575. }
  576. \PhpOffice\PhpSpreadsheet\IOFactory::registerWriter('Pdf', MY_TCPDF_WRITER::class);
  577. ```
  578. #### Writing a spreadsheet
  579. Once you have identified the Renderer that you wish to use for PDF
  580. generation, you can write a .pdf file using the following code:
  581. ``` php
  582. $writer = new \PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf($spreadsheet);
  583. $writer->save("05featuredemo.pdf");
  584. ```
  585. Please note that `\PhpOffice\PhpSpreadsheet\Writer\Pdf` only outputs the
  586. first worksheet by default.
  587. #### Write all worksheets
  588. PDF files can contain one or more worksheets. If you want to write all
  589. sheets into a single PDF file, use the following code:
  590. ``` php
  591. $writer->writeAllSheets();
  592. ```
  593. #### Write a specific worksheet
  594. PDF files can contain one or more worksheets. Therefore, you can specify
  595. which sheet to write to PDF:
  596. ``` php
  597. $writer->setSheetIndex(0);
  598. ```
  599. #### Formula pre-calculation
  600. By default, this writer pre-calculates all formulas in the spreadsheet.
  601. This can be slow on large spreadsheets, and maybe even unwanted. You can
  602. however disable formula pre-calculation:
  603. ``` php
  604. $writer = new \PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf($spreadsheet);
  605. $writer->setPreCalculateFormulas(false);
  606. $writer->save("05featuredemo.pdf");
  607. ```
  608. #### Decimal and thousands separators
  609. See section `\PhpOffice\PhpSpreadsheet\Writer\Csv` how to control the
  610. appearance of these.
  611. ## Generating Excel files from templates (read, modify, write)
  612. Readers and writers are the tools that allow you to generate Excel files
  613. from templates. This requires less coding effort than generating the
  614. Excel file from scratch, especially if your template has many styles,
  615. page setup properties, headers etc.
  616. Here is an example how to open a template file, fill in a couple of
  617. fields and save it again:
  618. ``` php
  619. $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load('template.xlsx');
  620. $worksheet = $spreadsheet->getActiveSheet();
  621. $worksheet->getCell('A1')->setValue('John');
  622. $worksheet->getCell('A2')->setValue('Smith');
  623. $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
  624. $writer->save('write.xls');
  625. ```
  626. Notice that it is ok to load an xlsx file and generate an xls file.
  627. ## Generating Excel files from HTML content
  628. If you are generating an Excel file from pre-rendered HTML content you can do so
  629. automatically using the HTML Reader. This is most useful when you are generating
  630. Excel files from web application content that would be downloaded/sent to a user.
  631. For example:
  632. ```php
  633. $htmlString = '<table>
  634. <tr>
  635. <td>Hello World</td>
  636. </tr>
  637. <tr>
  638. <td>Hello<br />World</td>
  639. </tr>
  640. <tr>
  641. <td>Hello<br>World</td>
  642. </tr>
  643. </table>';
  644. $reader = new \PhpOffice\PhpSpreadsheet\Reader\Html();
  645. $spreadsheet = $reader->loadFromString($htmlString);
  646. $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
  647. $writer->save('write.xls');
  648. ```
  649. Suppose you have multiple worksheets you'd like created from html. This can be
  650. accomplished as follows.
  651. ```php
  652. $firstHtmlString = '<table>
  653. <tr>
  654. <td>Hello World</td>
  655. </tr>
  656. </table>';
  657. $secondHtmlString = '<table>
  658. <tr>
  659. <td>Hello World</td>
  660. </tr>
  661. </table>';
  662. $reader = new \PhpOffice\PhpSpreadsheet\Reader\Html();
  663. $spreadsheet = $reader->loadFromString($firstHtmlString);
  664. $reader->setSheetIndex(1);
  665. $spreadhseet = $reader->loadFromString($secondHtmlString, $spreadsheet);
  666. $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
  667. $writer->save('write.xls');
  668. ```