How to Format XLS File From PHP
PHP is a programming language used by some dynamic websites to create specialized content. You can use it can be used to access user input, SQL databases and files on the server. PHP can be used to create an excel spreadsheet either on the web browser or save it to the server. The special PHP extension package Pear has a convenient class specifically for making excel files.
Instructions
-
-
1
Open the PHP file with wordpad and located where in the code you wish to process the XLS file.
-
2
Include the 'Writer.php' file of the Pear Spreadsheet/Excel extension. This can be at the start of the file, or specifically where you are processing the XLS file. Insert the following code:
require_once 'Spreadsheet/Excel/Writer.php';
-
-
3
Create a new object. I have used "$workbook" for the object's name, though it can be anything.
Insert the following code:
$workbook = new Spreadsheet_Excel_Writer();A file name can be included in the object's constructor to save the file to the server. In this case the file is "test.xls."
Insert the following code:
$workbook = new Spreadsheet_Excel_Writer('test.xls'); -
4
If you are going to display the spreadsheet in the web browser, the http headers must be set. The filename needs to be passed to the send function. It is "test.xls" in this case.
Insert the following code:
$workbook->send('test.xls'); -
5
Create a worksheet in the workbook using the addWorksheet() function.
Insert the following code:
$worksheet =& $workbook->addWorksheet('Worksheet1');'Worksheet1' is the name of the worksheet. It is a string, passed directly or as a variable.
-
6
Content can be written to the file using the write() function. It is performed on the worksheet, not the workbook object.
Insert the following code:
$worksheet->write('row', 'col', 'content');'row' and 'col' must be integers. 'content' must be a string. They can be passed directly or as variables. This line of code should be repeated for each cell containing content.
-
7
Close the file.
Insert the following code:
$workbook->close();
-
1
Tips & Warnings
Specific formatting of individual cells in the spreadsheet is accomplished using the Format class of functions. Each line of code should be on a separate line.