Вы находитесь на странице: 1из 20

1 evZone IeadIn and WrItIn Spreadsheets wIth III

07/02/2012 05.18.43 IM http.//devzone.zend.com/27/readIn-and-wrItIn-spreadsheets-wIth-php/


* Link http://devone.end .com*
PEAR * Link http://devone. end.com/tag/pear/*
Reading and Writing Spreadseets wit PHP
Vikram Vaswani * Link http://devone .end. com/author/Vikram Vaswani/* j 16 comments * Link ttp://devz one.z end. com/27/reading-
and-writing- spreadseets- wit- pp/#comments* j November 30th, -0001
Breaking Te Language Barrier
When it comes to playing nice with data in different formats, PHP's pedigree is hard to beat. Not only does the language make it a breee to
deal with SQL resultsets and XML files, but it comes with extensions to deal with formats as diverse as Ogg/Vorbis audio files, ZIP archives and
EXIF headers. So it should come as no surprise that PHP can also read and write Microsoft Excel spreadsheets, albeit with a little help from
PEAR.
In this article , I'll introduce you to two packages that make it surprisingly easy to hook your PHP scripts up to a Microsoft Excel spreadsheet and
extract the data contained therein. I'll also show you how to dynamically create a new spreadsheet from scratch, complete with formulae and
formatting, and import data from a spreadsheet into a database. So come on it, and let's get started !
Putting Te Pieces Togeter
There isn't currently a unified reader/writer package for Excel spreadsheets in PEAR, so this tutorial will make use of two separate packages:
The PHP-ExcelReader package , currently not maintained but available at http://sourceforge. net/projects/phpexcelreader/ * Link http://
sourceforge.net/projects/phpexcelreader/*
The Spreadsheet_Excel_Writer package, maintained by Xavier Noguer and available from http://pear.php.net/package /Spreadsheet_
Excel_Writer * Link http://pear. php.net/package/Spreadsheet_Excel_Writer*
For the latter package , you'll also need to download and install the PEAR OLE package , from http://pear.php.net/package /OLE * Link http://
pear. php.net/package/OLE*
You can install these packages manually, or using the PEAR installer, as below:
she> peaJ 1hs1a SpJeashee1_Exce_WJ11eJ
I should mention at this point certain changes you might need to make to your development environment in order to get the PHP-ExcelReader
package working. As noted above, this package is currently not maintained and so, simply include ()-ing the main class file, 'reader.php', in your
script, as suggested in the package documentation, is insufficient and generates a 'missing file' error.
To get things working, extract the file 'oleread .inc' from the distribution archive and save it to a location in your PHP include path using the
directory structure 'Spreadsheet/Excel/Reader/OLERead .php'. Once you do this, the error should disappear and things should begin working
normally. There's a caveat, though: this procedure works with the version of PHP-ExcelReader dated Jul 3 2007 (the most current version at the
time of writing) but may not work with other versions.
Te Number Game
Now that you have all the pieces installed, let's see them in action. Assume for a moment that you have the following Excel spreadsheet:
2 evZone IeadIn and WrItIn Spreadsheets wIth III
07/02/2012 05.18.43 IM http.//devzone.zend.com/27/readIn-and-wrItIn-spreadsheets-wIth-php/
Now, let's put together a simple PHP script that reads this spreadsheet and displays the number of worksheets, rows and columns in it:
Jea{`Book1.xs`),
// pJ1h1 humbeJ o1 Jows, coumhs ah shee1s
echo "humbeJ o1 shee1s. " . s1zeo1{$exce->shee1s) . "\h",
1oJ {$x=0, $xshee1s), $x++) {
echo "humbeJ o1 Jows 1h shee1 " . {$x+1) . ". " . $exce->shee1s|$x]|"humRows"] . "\h",
echo "humbeJ o1 coumhs 1h shee1 " . {$x+1) . ". " . $exce->shee1s|$x]|"humCos"] . "\h",
}
?>
Here's the output:
3 evZone IeadIn and WrItIn Spreadsheets wIth III
07/02/2012 05.18.43 IM http.//devzone.zend.com/27/readIn-and-wrItIn-spreadsheets-wIth-php/
How did this happen? It's actually not very difficult, because PHP-ExcelReader does most of the heavy lifting for you. The first step is to include
the package file and instantiate a new Spreadsheet_Excel_Reader object. This object exposes a read() method , which accepts the name and
path to the source Excel spreadsheet as input argument and then goes to work reading the spreadsheet data and converting it into PHP-readable
data structures.
Every Excel spreadsheet file contains one or more worksheets, these worksheets are now represented in the Spreadsheet_Excel_Reader's
'sheets' property, as array elements indexed from 0. As a result, worksheet 1 may be accessed using the notation $obj-sheets[0|, worksheet 2
as $obj-sheets[1|, and so on.
For each worksheet, PHP-ExcelReader also creates some special array keys with sheet-level information for example , the 'numRows' key holds
the number of rows in the worksheet, while the 'numCols' holds the number of columns. The script above merely uses this information to iterate
over the array of worksheets and print the number of rows and columns in each.
Off Te Grid
Now, while this is interesting, it's not really all that useful after all, what you're really after is the data within the spreadsheet. PHP-ExcelReader
has you covered there too: the cells of each worksheet are nested inside the corresponding worksheet array, and are accessible via the 'cells'
array key. An individual cell is accessed using its row and column coordinates for example , the cell at row 3 and column C would be
accessed using the notation $obj-sheets[0|[' cells'|[3|[3|. Row and column indexing starts from 1.
With this in mind , consider the next PHP script, which uses the PHP-ExcelReader to represent the example spreadsheet as an HTML table:
<h1m>
<hea>
<s1ye 1ype="1ex1/css">
1abe {
boJeJ-coapse. coapse,
}
1 {
boJeJ. 1px so1 back,
pa1hg. 0 0.5em,
}
</s1ye>
</hea>
<boy>
<1abe>
<?php
// 1hcue cass 11e
1hcue `JeaeJ.php`,

// 1h111a1ze JeaeJ obec1
$exce = hew SpJeashee1_Exce_ReaeJ{),

// Jea spJeashee1 a1a
$exce->Jea{`Book1.xs`),

// 11eJa1e oveJ spJeashee1 ces ah pJ1h1 as hThL 1abe
$x=1,
wh1e{$x<=$exce->shee1s|0]|`humRows`]) {
echo "\1<1J>\h",
$y=1,
wh1e{$y<=$exce->shee1s|0]|`humCos`]) {
$ce = 1sse1{$exce->shee1s|0]|`ces`]|$x]|$y]) ? $exce->shee1s|0]|`ces`]|$x]|$y] . ``,
echo "\1\1<1>$ce</1>\h",
$y++,
}
echo "\1</1J>\h",
$x++,
}
?>
</1abe>
4 evZone IeadIn and WrItIn Spreadsheets wIth III
07/02/2012 05.18.43 IM http.//devzone.zend.com/27/readIn-and-wrItIn-spreadsheets-wIth-php/
</boy>
</h1m>
It's now a simple task to represent the data from a worksheet as an HTML table. All that's needed are two loops, one iterating over the rows and
the other iterating over the columns in each row, and a little bit of PHP code to access the value of the cell at their point of intersection. That's
precisely what the script above does, together with some CSS code to render the table neatly.
Here's what the output looks like:
Interestingly, if your spreadsheet cells contain formulae, PHP-ExcelReader will return the final result of the formulae as the corresponding cell
value (instead of the raw formula string). However, when it comes to cell formatting, PHP-ExcelReader returns the raw value of each cell, rather
than the formatted cell value. To illustrate both these facts, let's revise the spreadsheet so it contains both formulae and formatting:
5 evZone IeadIn and WrItIn Spreadsheets wIth III
07/02/2012 05.18.43 IM http.//devzone.zend.com/27/readIn-and-wrItIn-spreadsheets-wIth-php/
And now, when you re-run the previous script, you should see something like this:
Turning Te Tables
With the power of PHP-ExcelReader at your command , it's also quite easy to transfer data from a spreadsheet into a database , so that you can
run queries on it. Consider the following script, which illustrates the process by bringing together PHP-ExcelReader, PDO and prepared statements
to read data from a spreadsheet and INSERT it into a MySQL table:
<?php
// 1hcue cass 11e
1hcue `JeaeJ.php`,
6 evZone IeadIn and WrItIn Spreadsheets wIth III
07/02/2012 05.18.43 IM http.//devzone.zend.com/27/readIn-and-wrItIn-spreadsheets-wIth-php/
// 1h111a1ze JeaeJ obec1
$exce = hew SpJeashee1_Exce_ReaeJ{),
// Jea spJeashee1 a1a
$exce->Jea{`Book2.xs`),
// a11emp1 a cohhec11oh
1Jy {
$po = hew P00{`mysq.bhame=1es1,hos1=ocahos1`, `useJ`, `pass`),
} ca1ch {P00Excep11oh $e) {
1e{"ERR0R. Cou ho1 cohhec1. " . $e->ge1hessage{)),
}
// 11eJa1e oveJ spJeashee1 Jows ah coumhs
// cohveJ1 1h1o ThSERT queJy
$sq = "ThSERT ThT0 a1a {couh1Jy, saes) vALbES {?, ?)",
11 {$s1m1 = $po->pJepaJe{$sq)) {
$x=2,
wh1e{$x<=$exce->shee1s|0]|`humRows`]) {
$s1m1->b1hPaJam{1, $exce->shee1s|0]|`ces`]|$x]|1]),
$s1m1->b1hPaJam{2, $exce->shee1s|0]|`ces`]|$x]|2]),
11 {!$s1m1->execu1e{)) {
echo "ERR0R. Cou ho1 execu1e queJy. $sq. " . pJ1h1_J{$po->eJJoJTh1o{)),
}
$x++,
}
} ese {
echo "ERR0R. Cou ho1 pJepaJe queJy. $sq. " . pJ1h1_J{$po->eJJoJTh1o{)),
}
// cose cohhec11oh
uhse1{$po),
?>
Given the following spreadsheet,
7 evZone IeadIn and WrItIn Spreadsheets wIth III
07/02/2012 05.18.43 IM http.//devzone.zend.com/27/readIn-and-wrItIn-spreadsheets-wIth-php/
the script above will read the data in the spreadsheet and save each spreadsheet row as a record in the named MySQL table. It begins by
reading the spreadsheet into a Spreadsheet_Excel_Reader object, and then opening a PDO connection to the MySQL database . It then prepares
an INSERT statement with $pdo-prepare() and then iterates over the spreadsheet rows (skipping the first row, which is the table header row),
binding the values in each row to the prepared statement before executing it. This process continues until all the rows in the spreadsheet are
processed.
At the end of the process, you should see the data safely transferred to your MySQL table:
mysq> SELECT * FR0h a1a,
+----------------+-------+
] couh1Jy ] saes ]
+----------------+-------+
] bh11e S1a1es ] 7583 ]
] bh11e K1hgom ] 4359 ]
] FJahce ] 45885 ]
] CeJmahy ] 3833 ]
] Spa1h ] 8738 ]
] T1ay ] 5239 ]
] CJeece ] 38282 ]
+----------------+-------+
7 Jows 1h se1 {0.01 sec)
There's one key thing to remember when performing this kind of spreadsheet-to-database conversion: your spreadsheet data must be correctly
and consistently structured, with all the values lining up neatly, or else your table fields will end up with missing or incorrect values. So it's a
good idea to visually check the source spreadsheet for consistency once before reading it into an SQL database.
Back To Class
So that takes care of reading Excel spreadsheets. Now, how about writing them?
Well, with PEAR's Spreadsheet_Excel_Writer package , this is actually a piece of cake. Consider the following script, which illustrates the
process:
8 evZone IeadIn and WrItIn Spreadsheets wIth III
07/02/2012 05.18.43 IM http.//devzone.zend.com/27/readIn-and-wrItIn-spreadsheets-wIth-php/
<?php
// spJeashee1 a1a
$a1a = aJJay{
aJJay{``, `ha1h`, `L11eJa1uJe`, `Sc1ehce`),
aJJay{`Johh`, 24, 54, 38),
aJJay{`haJk`, 67, 22, 57),
aJJay{`T1m`, 69, 32, 58),
aJJay{`SaJah`, 81, 78, 68),
aJJay{`Susah`, 16, 44, 38),
),
// 1hcue package
1hcue `SpJeashee1/Exce/WJ11eJ.php`,
// cJea1e emp1y 11e
$exce = hew SpJeashee1_Exce_WJ11eJ{`gJaes.xs`),
// a woJkshee1
$shee1 =& $exce->aWoJkshee1{`Cass T`),
// a a1a 1o woJkshee1
$JowCouh1=0,
1oJeach {$a1a as $Jow) {
1oJeach {$Jow as $key => $vaue) {
$shee1->wJ11e{$JowCouh1, $key, $vaue),
}
$JowCouh1++,
}
// save 11e 1o 1sk
11 {$exce->cose{) === 1Jue) {
echo `SpJeashee1 success1uy save!`,
} ese {
echo `ERR0R. Cou ho1 save spJeashee1.`,
}
?>
There's a fairly standard sequence of actions to follow when creating a new Excel spreadsheet. First, include the class file and initialie an
object of the Spreadsheet_Excel_Writer class, passing the name and path of the output spreadsheet file to the object constructor. Once you've
got your empty spreadsheet initialied, add a new, empty worksheet to it with the object's addWorksheet() method , pass the worksheet name to
the method as an additional argument.
At this point, your spreadsheet is ready for some data . Inserting data is a task for the write () method , which accepts three arguments: the row
number, the column number and the value to be inserted. Row and column indexing starts from 0. So, for example, to write the value 'Hello' to
the cell at row 4 and column F, you'd call $obj-write (3, 3,'Hello').
In the previous example, a loop iterates over the array of source data, using write () to add each element to the spreadsheet as a cell. Once
you've finished writing data to the spreadsheet, the close() method wraps things up and saves the output file to disk. You can now read this
spreadsheet in Microsoft Excel open it up, and you'll see something like this:
9 evZone IeadIn and WrItIn Spreadsheets wIth III
07/02/2012 05.18.43 IM http.//devzone.zend.com/27/readIn-and-wrItIn-spreadsheets-wIth-php/
If, instead of writing the output file to disk, you'd prefer to have it sent directly to the user's browser, Spreadsheet_Excel_Writer has you
covered there too! To do this, call the Spreadsheet_Excel_Writer's send() method with the output file name instead of passing it to the object
constructor, as in the following revision of the previous example:
<?php
// spJeashee1 a1a
$a1a = aJJay{
aJJay{``, `ha1h`, `L11eJa1uJe`, `Sc1ehce`),
aJJay{`Johh`, 24, 54, 38),
aJJay{`haJk`, 67, 22, 57),
aJJay{`T1m`, 69, 32, 58),
aJJay{`SaJah`, 81, 78, 68),
aJJay{`Susah`, 16, 44, 38),
),
// 1hcue package
1hcue `SpJeashee1/Exce/WJ11eJ.php`,
// cJea1e emp1y 11e
$exce = hew SpJeashee1_Exce_WJ11eJ{),
// seh c1eh1 heaeJs
$exce->seh{`gJaes.xs`),
// a woJkshee1
$shee1 =& $exce->aWoJkshee1{`Cass T`),
// a a1a 1o woJkshee1
$JowCouh1=0,
1oJeach {$a1a as $Jow) {
1oJeach {$Jow as $key => $vaue) {
$shee1->wJ11e{$JowCouh1, $key, $vaue),
}
$JowCouh1++,
}
10 evZone IeadIn and WrItIn Spreadsheets wIth III
07/02/2012 05.18.43 IM http.//devzone.zend.com/27/readIn-and-wrItIn-spreadsheets-wIth-php/
// cose ah ou1pu1 11e
11 {$exce->cose{) !== 1Jue) {
echo `ERR0R. Cou ho1 save spJeashee1.`,
}
?>
The send() method sends the client browser headers that identify the data that follows as a spreadsheet. The browser should then offer the user
a choice to view the spreadsheet directly in Microsoft Excel, or save the file to disk.
Te Secret Formula
Why stop with just values? It's easy to create cells containing formulae as well simply call the writeFormula() method with the row and column
coordinates of the target cell and the formula to be inserted into that cell. As per normal Excel operation, formulae must be preceded with an
equality symbol (). Consider the following revision of the previous example , which averages the grades of each student across the three
subjects:
<?php
// spJeashee1 a1a
$a1a = aJJay{
aJJay{``, `ha1h`, `L11eJa1uJe`, `Sc1ehce`),
aJJay{`Johh`, 24, 54, 38),
aJJay{`haJk`, 67, 22, 57),
aJJay{`T1m`, 69, 32, 58),
aJJay{`SaJah`, 81, 78, 68),
aJJay{`Susah`, 16, 44, 38),
),
// 1hcue package
1hcue `SpJeashee1/Exce/WJ11eJ.php`,
// cJea1e emp1y 11e
$exce = hew SpJeashee1_Exce_WJ11eJ{`gJaes.xs`),
// a woJkshee1
$shee1 =& $exce->aWoJkshee1{`Cass T`),
// a a1a 1o woJkshee1
$JowCouh1=0,
1oJeach {$a1a as $Jow) {
1oJ{$x=0, $x<s1zeo1{$Jow), $x++) {
$shee1->wJ11e{$JowCouh1, $x, $Jow|$x]),
}
// ge1 ce cooJ1ha1es
$s1aJ1 = SpJeashee1_Exce_WJ11eJ..JowcoToCe{$JowCouh1, 1),
$eh = SpJeashee1_Exce_WJ11eJ..JowcoToCe{$JowCouh1, {s1zeo1{$Jow)-1)),
// a AvERACE{) 1oJmua 1o 1eJm1ha11hg ce o1 each Jow
// excep1 1he 11Js1 {heaeJ) Jow
11 {$JowCouh1 != 0) {
$shee1->wJ11eFoJmua{$JowCouh1, s1zeo1{$Jow), "=AvERACE{$s1aJ1.$eh)"),
}
$JowCouh1++,
}
// save 11e 1o 1sk
11 {$exce->cose{) === 1Jue) {
echo `SpJeashee1 success1uy save!`,
} ese {
echo `ERR0R. Cou ho1 save spJeashee1.`,
}
?>
11 evZone IeadIn and WrItIn Spreadsheets wIth III
07/02/2012 05.18.43 IM http.//devzone.zend.com/27/readIn-and-wrItIn-spreadsheets-wIth-php/
Here, Excel's AVERAGE() formula is used to calculate the average grade of each student, by dynamically generating the formula string and
placing it at the end of each row of grades. Notice the script's use of the rowcolToCell() static method , which accepts a row and column number
and returns an Excel-compliant alphanumeric grid identifier corresponding to that cell.
Here's what the output looks like:
In addition to the writeFormula() method, the Spreadsheet_Excel_Writer also comes with writeNote() and writeUrl() methods, which come in
handy to attach notes or hyperlinks to a cell. The following example illustrates both these in action:
<?php
// 1hcue package
1hcue `SpJeashee1/Exce/WJ11eJ.php`,
// cJea1e emp1y 11e
$exce = hew SpJeashee1_Exce_WJ11eJ{`Book1.xs`),
// a woJkshee1
$shee1 =& $exce->aWoJkshee1{`bh111e`),
// a ho1e
$shee1->wJ11e{0, 0, 647384.65),
$shee1->wJ11eho1e{0, 0, `Th1s assumes g=16`),
// a bRLs as ce vaues
$shee1->wJ11ebJ{1, 0, `h11p.//www.yahoo.com/`, `Yahoo!`),
$shee1->wJ11ebJ{2, 0, `h11p.//www.googe.com/`, `Cooge`),
$shee1->wJ11ebJ{3, 0, `h11p.//www.php.he1/`, `PhP.he1`),
// save 11e 1o 1sk
11 {$exce->cose{) === 1Jue) {
echo `SpJeashee1 success1uy save!`,
} ese {
echo `ERR0R. Cou ho1 save spJeashee1.`,
12 evZone IeadIn and WrItIn Spreadsheets wIth III
07/02/2012 05.18.43 IM http.//devzone.zend.com/27/readIn-and-wrItIn-spreadsheets-wIth-php/
}
?>
Looking Pretty
Spreadsheet_Excel_Writer also offers a large number of methods to format your spreadsheet cells and make them look pretty. There are two
steps to using formats: first, define a new format with the addFormat() method and then, apply the format to a cell by specifying it as an
additional argument to the write () method .
The following example illustrates the process:
<?php
// spJeashee1 a1a
$a1a = aJJay{
aJJay{``, `ha1h`, `L11eJa1uJe`, `Sc1ehce`),
aJJay{`Johh`, 24, 54, 38),
aJJay{`haJk`, 67, 22, 57),
aJJay{`T1m`, 69, 32, 58),
aJJay{`SaJah`, 81, 78, 68),
aJJay{`Susah`, 16, 44, 38),
),
// 1hcue package
1hcue `SpJeashee1/Exce/WJ11eJ.php`,
// cJea1e emp1y 11e
$exce = hew SpJeashee1_Exce_WJ11eJ{`gJaes.xs`),
// a woJkshee1
$shee1 =& $exce->aWoJkshee1{`Cass T`),
// cJea1e 1oJma1 1oJ heaeJ Jow
// bo, Je w11h back oweJ boJeJ
$11Js1Row =& $exce->aFoJma1{),
$11Js1Row->se1Bo{),
$11Js1Row->se1CooJ{`Je`),
$11Js1Row->se1Bo11om{1),
$11Js1Row->se1Bo11omCooJ{`back`),
// cJea1e 1oJma1 1oJ heaeJ coumh
// bue w11h back J1gh1 boJeJ
$11Js1Co =& $exce->aFoJma1{),
$11Js1Co->se1CooJ{`bue`),
$11Js1Co->se1R1gh1{1),
$11Js1Co->se1R1gh1CooJ{`back`),
// cJea1e 1oJma1 1oJ 1op e11 coJheJ
$11Js1RowCo =& $exce->aFoJma1{),
$11Js1RowCo->se1Bo11om{1),
$11Js1RowCo->se1R1gh1{1),
$11Js1RowCo->se1BoJeJCooJ{`back`),
// cJea1e 1oJma1 1oJ humeJ1c ces
$hum =& $exce->aFoJma1{),
$hum->se1humFoJma1{`0`),
// cJea1e 1oJma1 1oJ aveJage vaues
$avg =& $exce->aFoJma1{),
$avg->se1humFoJma1{`0.00`),
// a a1a 1o woJkshee1
$JowCouh1=0,
13 evZone IeadIn and WrItIn Spreadsheets wIth III
07/02/2012 05.18.43 IM http.//devzone.zend.com/27/readIn-and-wrItIn-spreadsheets-wIth-php/
1oJeach {$a1a as $Jow) {
1oJ{$coCouh1=0, $coCouh1<s1zeo1{$Jow), $coCouh1++) {
11 {$JowCouh1 == 0 && $coCouh1 == 0) {
$1oJma1 = `11Js1RowCo`,
} ese 11 {$JowCouh1 == 0) {
$1oJma1 = `11Js1Row`,
} ese 11 {$coCouh1 == 0) {
$1oJma1 = `11Js1Co`,
} ese {
$1oJma1 = `hum`,
}
$shee1->wJ11e{$JowCouh1, $coCouh1, $Jow|$coCouh1], $$1oJma1),
}
// ge1 ce cooJ1ha1es
$s1aJ1 = SpJeashee1_Exce_WJ11eJ..JowcoToCe{$JowCouh1, 1),
$eh = SpJeashee1_Exce_WJ11eJ..JowcoToCe{$JowCouh1, {s1zeo1{$Jow)-1)),
// a aveJage{) 1oJmua 1o 1eJm1ha11hg ce o1 each Jow
// excep1 1he 11Js1 {heaeJ) Jow
11 {$JowCouh1 != 0) {
$shee1->wJ11eFoJmua{$JowCouh1, s1zeo1{$Jow), "=AvERACE{$s1aJ1.$eh)", $avg),
}
$JowCouh1++,
}
// save 11e 1o 1sk
11 {$exce->cose{) === 1Jue) {
echo `SpJeashee1 success1uy save!`,
} ese {
echo `ERR0R. Cou ho1 save spJeashee1.`,
}
?>
This example defines five different formats: $firstRow, which has red text and a bottom border, $firstCol, which has blue text and a right
border, $firstRowCol, which has both a right and bottom border, $num, which formats numbers as integer values, and $avg, which formats
numbers as decimal values. Each of these formats is created by calling the Spreadsheet_Excel_Writer's addFormat() method to create a new
Format object, and then calling methods of this Format object to set various formatting attributes such as color, sie and weight.
So, for example, the Format object's setColor() method sets the text color for the format, while the setBorderColor() method sets the border color.
Similarly, there 's a setSie() method to set text sie, a setAlign() method to set the text alignment, a setTextWrap() method to define text
wrapping, and a setNumFormat() method to define how numeric values are formatted. Some of these methods are used in the previous example .
Once the various Format objects are defined, all that's left is to apply them to the relevant cells. This is accomplished by using the relevant object
when invoking the write () method . Thus, in the script above, all subject names (the first row) are formatted using $firstRow, all student names (the
first column) are formatted using $firstCol, and all grades (the table content) are formatted using $num.
Here's what the output looks like:
14 evZone IeadIn and WrItIn Spreadsheets wIth III
07/02/2012 05.18.43 IM http.//devzone.zend.com/27/readIn-and-wrItIn-spreadsheets-wIth-php/
It should be noted that the Format object exposes many more formatting methods than the few shown in the previous example. To obtain a
complete list, look in the documentation for the Spreadsheet_Excel_Writer package, at http://pear.php.net/manual/en/
package. fileformats.spreadsheet-excel-writer.php * Link http://pear.php.net/manual/en/package .fileformats. spreadsheet-excel-writer. php* ,
there 's also an excellent tutorial on formatting there that you'll undoubtedly find useful!
Around Te World In 80 Rows
Earlier on in this article, I showed you how to read data from an Excel spreadsheet and transfer it to an SQL database . Now it's time to do the
reverse : transform an SQL result set into an Excel spreadsheet. In the following example, I'll use the MySQL example 'world' database , and turn
all the records from the 'country' table into rows of an Excel spreadsheet. Take a look at the code :
<?php
// 1hcue cass 11e
1hcue `SpJeashee1/Exce/WJ11eJ.php`,
// 1h111a1ze JeaeJ obec1
$exce = hew SpJeashee1_Exce_WJ11eJ{),
// seh c1eh1 heaeJs
$exce->seh{`couh1Jy.xs`),
// a woJkshee1
$shee1 =& $exce->aWoJkshee1{`S0L_0u1pu1`),
// a11emp1 a cohhec11oh
1Jy {
$po = hew P00{`mysq.bhame=woJ,hos1=ocahos1`, `useJ`, `pass`),
} ca1ch {P00Excep11oh $e) {
1e{"ERR0R. Cou ho1 cohhec1. " . $e->ge1hessage{)),
}
// Jea a1a 1Jom a1abase
// cohveJ1 1h1o spJeashee1
$JowCouh1 = 0,
15 evZone IeadIn and WrItIn Spreadsheets wIth III
07/02/2012 05.18.43 IM http.//devzone.zend.com/27/readIn-and-wrItIn-spreadsheets-wIth-php/
$sq = "SELECT * FR0h couh1Jy",
11 {$Jesu1 = $po->queJy{$sq)) {
// ge1 heaeJ Jow
1oJ {$x=0, $x<$Jesu1->coumhCouh1{), $x++) {
$me1a = $Jesu1->ge1Coumhhe1a{$x),
$shee1->wJ11e{$JowCouh1, $x, $me1a|`hame`]),
}
// ge1 a1a Jows
$JowCouh1++,
wh1e{$Jow = $Jesu1->1e1ch{)) {
1oJeach {$Jow as $key => $vaue) {
$shee1->wJ11e{$JowCouh1, $key, $vaue),
}
$JowCouh1++,
}
} ese {
echo "ERR0R. Cou ho1 execu1e $sq. " . pJ1h1_J{$po->eJJoJTh1o{)),
}
// cose cohhec11oh
uhse1{$po),
// save 11e 1o 1sk
11 {$exce->cose{) === 1Jue) {
echo `SpJeashee1 success1uy save!`,
} ese {
echo `ERR0R. Cou ho1 save spJeashee1.`,
}
?>
If you've been following along, there shouldn't be any major surprises here. The script begins by initialiing a new spreadsheet and attaching a
blank worksheet to it. It then opens a PDO connection to the 'world ' database and executes a SELECT query to return all the records from the
'country' table.
Having obtained a result set, the script then begins building the spreadsheet. First, it creates the header row by retrieving a list of all the fields in
the result set, obtaining each field's name, and writing this to the spreadsheet as the first row. Then, it iterates over the result set, writing the
contents of each record to the spreadsheet as a new row. This continues until the entire result set is processed, at which time the spreadsheet file
is closed and sent to the user's browser.
If you look inside the resulting output file, here 's a snippet of what you should see:
16 evZone IeadIn and WrItIn Spreadsheets wIth III
07/02/2012 05.18.43 IM http.//devzone.zend.com/27/readIn-and-wrItIn-spreadsheets-wIth-php/
And that's about it for this article. Over the last few pages, I showed you how to read spreadsheet data and insert it into an SQL database,
dynamically create a new spreadsheet, attach formulae, formatting, notes and hyperlinks to spreadsheet cells, and re -render SQL records in
spreadsheet format. You probably wouldn't have thought all of this possible using just PHP code .but it is, and it isn't even very difficult.
I hope you enjoyed this tutorial, and that it will save you some time the next time you sit down to work with spreadsheet data and PHP. Happy
coding!
Copyright Melonfire 2008 * Link http://melonfire.com* . All rights reserved.
Tweet 3
00
4
0
Publised: November 30th, -0001 at 0:00
Categories : Tutorials
Tags : PEAR
16 comments to Reading and Writing Spreadseets wit PHP"
maartenba * Link http://www. dolmen.be*
March 31st, 2008 at 6:32 pm * Link #comment-2331*
Make sure to check out PHPExcel too! (www. phpexcel.net)
Like l8 likes. Sig Up to see what your f rieds like.
Share Share
17 evZone IeadIn and WrItIn Spreadsheets wIth III
07/02/2012 05.18.43 IM http.//devzone.zend.com/27/readIn-and-wrItIn-spreadsheets-wIth-php/
This class writes Excel 2007 AND older Excel BIFF format using the same class interface. It also introduces a calculation engine
(check http://blog.maartenballiauw.be/post/2008/03/Reuse-Excel-business-logic-with-PHPExcel.aspx * Link http://
blog. maartenballiauw.be/post/2008/03/Reuse-Excel-business-logic-with-PHPExcel. aspx* ).
pawarsac
April 7th, 2008 at 2:33 pm * Link #comment-2333*
In my one excell sheet one column contains data is as given below
Bengali/Bengali Non Film/Aamar Bhalobasai Kal Holo
Bengali/Bengali Non Film/Aamar Bhalobasai Kal Holo
Bengali/Bengali Non Film/Aamar Bhalobasai Kal Holo
Bengali/Bengali Non Film/Aamar Bhalobasai Kal Holo
Bengali/Bengali Non Film/Aamar Bhalobasai Kal Holo
Bengali/Bengali Non Film/Aamar Bhalobasai Kal Holo
Bengali/Bengali Non Film/Aamar Bhalobasai Kal Holo
Bengali/Bengali Non Film/Bhajore Kali Naam
Bengali/Bengali Non Film/Bhajore Kali Naam
Bengali/Bengali Non Film/Bhajore Kali Naam
Bengali/Bengali Non Film/Bhajore Kali Naam
Bengali/Bengali Non Film/Bhajore Kali Naam
Bengali/Bengali Non Film/Bhajore Kali Naam
This excell reader is not able to read properly.
Any solution?
primordius
May 3rd, 2008 at 3:40 am * Link #comment-2232*
PHPEXCEL doesn't work for many installations.
The learning curve is fairly high.
Also, requires PHP 3.2 and ZLIB.
Simpler and smaller classes are out there.
Pear has a package, but it is limited to Excel93 features.
http://pear.php.net/package /Spreadsheet_Excel_Writer * Link http://pear.php.net/package /Spreadsheet_Excel_Writer*
SourceForce has an ExcelWriterXML package which is very simple and does not require any additional libraries and works with
any flavor of PHP3.
https://sourceforge.net/projects/excelwriterxml * Link https://sourceforge .net/projects/excelwriterxml*
opurahman
September 13th, 2008 at 10:16 am * Link #comment-1938*
I was looking for this type of solution. Thanks
_____anonymous_____
September 17th, 2008 at 4:33 pm * Link #comment-1934*
In your MySQL import example you showed how to import data into a MySQL database with an Excel spreadsheet that mimiced
your database structure (ie every row was a seperate row in the database . Is it possible to import data from various cells into one
row of the database ? For instance I have a spreadsheet which has the data I want to import in cells C2 C13 this data needs to be
imported into 12 fields in the same row of my database . Is this possible and could your provide an example script?
18 evZone IeadIn and WrItIn Spreadsheets wIth III
07/02/2012 05.18.43 IM http.//devzone.zend.com/27/readIn-and-wrItIn-spreadsheets-wIth-php/
Thank You
_____anonymous_____
December 31st, 2008 at 9:18 am * Link #comment-1730*
Hi,
I was trying to import a file which has 1000 colums. and also as uch rows.How to modify the script in this case?
I am a newbie to php.
Please help!
geshabeliyahoo. com * Link mailto:geshabeliyahoo.com*
bmdennst * Link http://www. bry.net*
May 12th, 2009 at 12:10 pm * Link #comment-1438*
I have an issue where negative numbers anything smaller than say -3000 or so are getting messed up with the free reading program.
they are turning into 10691343.2
Anyway, I've tried messing with the encoding types, but the code is very complicated , anyone else experience this issue and fix it?
yodei
October 11th, 2009 at 4:08 pm * Link #comment-1019*
I may be a bit dense, but I am having trouble figuring out how to read a spreadsheet, edit it, adn write it back. These instructions
only seem to deal with creating a spreadsheet from whole cloth. Is it possible to use these techniques to EDIT, not just write, and
existing spreadsheet?
thewilson
November 20th, 2009 at 12:33 pm * Link #comment-932*
I would like to express my thanks to you for sharing the examples you have on this tutorial. I have had the php Excel writing library
for a year or so but never really understood the how. Now it is much clearer and I think I am one more step closer to never actually
using microsoft excel ever again. I will just generate the reports with php
Thanks!
ioka
April 29th, 2010 at 11:20 am * Link #comment-697*
Typo on this line :
for ($x0, $xsheets), $x)
Nice tutorial.
aldm11r
September 16th, 2010 at 10:04 am * Link #comment-472*
Hi,
19 evZone IeadIn and WrItIn Spreadsheets wIth III
07/02/2012 05.18.43 IM http.//devzone.zend.com/27/readIn-and-wrItIn-spreadsheets-wIth-php/
first thanks for great plugin and tutorial.
Can this plugin be used with xlsx files?
I tried that, and it didn't work.
Thanks in advance ,
Amer
gabrielapavel
November 11th, 2010 at 7:49 am * Link #comment-370*
This is an amaing tutorial. Helped me understand how to use this libs but transforming an SQL result set into an Excel spreadsheet
does not work properly. The first column is always filled in with the rows from the last one. I could use some help.
Thanks,
Gabriela
suctreit
November 22nd , 2010 at 3:43 am * Link #comment-333*
First, I thank your useful post!
I use it for file XLS have 3 column and more , but it don't show UTF-8 for data of column 3 and more ??
Pl help me show data UTF-8
Thank you very much!
rati392
December 7th, 2010 at 2:09 am * Link #comment-340*
I want to read and write a date field to database from the excelsheet. Please any one help me?
iadmannan
February 18th, 2011 at 6:36 pm * Link #comment-269*
Hi,
Thanks for this post. It seems that the Excel Reader class on SF is quite popular as there are a number of blogs posts/articles out on
the web recommending it as a Excel data reading solution but I'm having some trouble with it. I'm using the latest version available
as I just downloaded it today. Firstly there seems to be some errors in the require_once statements but I fixed those. The
example.php script still wouldn't run and when I tried to open the jxlrwtest.xls in Excel I got an error (This is not a WinWord97 file)
so I tried to use my own simple xls file but I get a timeout error with the following message . Any pointers?
Thanks
Ziad

Fatal error: Maximum execution time of 30 seconds exceeded in /home /iad/public _html/phpExcelReader/Excel/Reader/oleread. inc
on line 172 Call Stack: 0.0001 627836 1. main() /home/iad/public _html/phpExcelReader/example .php:0 0.0071 634088 2.
Spreadsheet_Excel_Reader-read() /home/iad /public_html/phpExcelReader/example .php:39 0.0071 634088 3. OLERead -read() /
20 evZone IeadIn and WrItIn Spreadsheets wIth III
07/02/2012 05.18.43 IM http.//devzone.zend.com/27/readIn-and-wrItIn-spreadsheets-wIth-php/
home/iad /public_html/phpExcelReader/Excel/reader.php:382 0.0138 704128 4. OLERead -__readData() /home/iad/public_html/
phpExcelReader/Excel/Reader/oleread.inc :131
iadmannan
February 21st, 2011 at 10:30 am * Link #comment-267*
The ExcelReader project is available on Google Code and seems more active . The example script from Google worked whereas the
Source Forge one didn't.
http://code. google.com/p/php-excel-reader/ * Link http://code.google .com/p/php-excel-reader/*
Copyrigt 1999 - 2011 by Zend Tecnologies Ltd. All rigts reserved.
Zend is a trademark of Zend Technologies Ltd . j Contact Us * Link https://www. end.com/en/contact*

Вам также может понравиться