I am trying to generate an XLS file from a table in a MySQL DB, but the Excel file is not properly formatted & given error when the Excel file generated "The file which you are trying to open is in different format than one specified". When the file is opened the data is not properly formatted.
Any ideas what I am missing?
<?php
$host = 'XXXXXXX';
$dbname = 'XXXXXXXX';
$username = 'XXXXXXXX';
$password = 'XXXXXXXX';
function xlsBOF() {
echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
return;
}
function xlsEOF() {
echo pack("ss", 0x0A, 0x00);
return;
}
function xlsWriteLabel($Row, $Col, $Value ) {
$L = strlen($Value);
echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L);
echo $Value;
return;
}
function xlsWriteNumber($Row, $Col, $Value) {
echo pack("sssss", 0x203, 14, $Row, $Col, 0x0);
echo pack("d", $Value);
return;
}
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
echo "Connected to $dbname at $host successfully.";
$conn = null;
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
$q = "SELECT * FROM tablename";
$qr = mysql_query( $q ) or die( mysql_error() );
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment;filename=export_".$dbtable.".xls ");
header("Content-Transfer-Encoding: binary ");
xlsBOF();
$col = 0;
$row = 0;
$first = true;
while( $qrow = mysql_fetch_assoc( $qr ) )
{
if( $first )
{
foreach( $qrow as $k => $v )
{
xlsWriteLabel( $row, $col, strtoupper( ereg_replace( "_" , " " , $k ) ) );
$col++;
}
$col = 0;
$row++;
$first = false;
}
// go through the data
foreach( $qrow as $k => $v )
{
// write it out
xlsWriteLabel( $row, $col, $v );
$col++;
}
// reset col and goto next row
$col = 0;
$row++;
}
xlsEOF();
exit();
I'm not sure about .xls but for outputting a MySQL result as a CSV table the fputcsv function does it without much fuss:
// Clear any previous output
ob_end_clean();
// I assume you already have your $result
$num_fields = mysql_num_fields($result);
// Fetch MySQL result headers
$headers = array();
$headers[] = "[Row]";
for ($i = 0; $i < $num_fields; $i++) {
$headers[] = strtoupper(mysql_field_name($result , $i));
}
// Filename with current date
$current_date = date("y/m/d");
$filename = "MyFileName" . $current_date . ".csv";
// Open php output stream and write headers
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename='.$filename);
header('Pragma: no-cache');
header('Expires: 0');
echo "Title of Your CSV File\n\n";
// Write mysql headers to csv
fputcsv($fp, $headers);
$row_tally = 0;
// Write mysql rows to csv
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$row_tally = $row_tally + 1;
echo $row_tally.",";
fputcsv($fp, array_values($row));
}
die;
}
use http://phpexcel.codeplex.com/
C'est la meilleur solution pour générer un fichier excel
Vous pouvez même créer plusieurs feuilles dans le fichier et formater les cellules (couleur, police, bordure, ...)
Google translate:
This is the best solution to generate an excel file You can even create multiple sheets in the file and format the cells (color, font, border, ...)
<?php
//download.php page code
//THIS PROGRAM WILL FETCH THE RESULT OF SQL QUERY AND WILL DOWNLOAD IT. (IF YOU HAVE ANY QUERY CONTACT:rahulpatel541#gmail.com)
//include the database file connection
include_once('database.php');
//will work if the link is set in the indx.php page
if(isset($_GET['name']))
{
$name=$_GET['name']; //to rename the file
header('Content-Disposition: attachment; filename='.$name.'.xls');
header('Cache-Control: no-cache, no-store, must-revalidate, post-check=0, pre-check=0');
header('Pragma: no-cache');
header('Content-Type: application/x-msexcel; charset=windows-1251; format=attachment;');
$msg="";
$var="";
//write your query
$sql="select * from tablename";
$res = mysql_query($sql);
$numcolumn = mysql_num_fields($res); //will fetch number of field in table
$msg="<table><tr><td>Sl No</td>";
for ( $i = 0; $i < $numcolumn; $i++ ) {
$msg.="<td>";
$msg.= mysql_field_name($res, $i); //will store column name of the table to msg variable
$msg.="</td>";
}
$msg.="</tr>";
$i=0;
$count=1; //used to print sl.no
while($row=mysql_fetch_array($res)) //fetch all the row as array
{
$msg.="<tr><td>".$count."</td>";
for($i=0;$i< $numcolumn;$i++)
{
$var=$row[$i]; //will store all the values of row
$msg.="<td>".$var."</td>";
}
$count=$count+1;
$msg.="</tr>";
}
$msg.="</table>";
echo $msg; //will print the content in the exel page
}
?>
<?php
//index.php page
$name="any file name";
echo "<a href='download.php?name=".$name."'>Click to download</a>"; //link to download file
?>
Here is simple Excel file generation function, very fast and exactly .xls file.
$filename = "sample_php_excel.xls";
$data = array(
array("User Name" => "Abid Ali", "Q1" => "$32055", "Q2" => "$31067", "Q3" => 32045, "Q4" => 39043),
array("User Name" => "Sajid Ali", "Q1" => "$25080", "Q2" => "$20677", "Q3" => 32025, "Q4" => 34010),
array("User Name" => "Wajid Ali", "Q1" => "$93067", "Q2" => "$98075", "Q3" => 95404, "Q4" => 102055),
);
to_xls($data, $filename);
function to_xls($data, $filename){
$fp = fopen($filename, "w+");
$str = pack(str_repeat("s", 6), 0x809, 0x8, 0x0, 0x10, 0x0, 0x0); // s | v
fwrite($fp, $str);
if (is_array($data) && !empty($data)){
$row = 0;
foreach (array_values($data) as $_data){
if (is_array($_data) && !empty($_data)){
if ($row == 0){
foreach (array_keys($_data) as $col => $val){
_xlsWriteCell($row, $col, $val, $fp);
}
$row++;
}
foreach (array_values($_data) as $col => $val){
_xlsWriteCell($row, $col, $val, $fp);
}
$row++;
}
}
}
$str = pack(str_repeat("s", 2), 0x0A, 0x00);
fwrite($fp, $str);
fclose($fp);
}
function _xlsWriteCell($row, $col, $val, $fp){
if (is_float($val) || is_int($val)){
$str = pack(str_repeat("s", 5), 0x203, 14, $row, $col, 0x0);
$str .= pack("d", $val);
} else {
$l = strlen($val);
$str = pack(str_repeat("s", 6), 0x204, 8 + $l, $row, $col, 0x0, $l);
$str .= $val;
}
fwrite($fp, $str);
}
<?php
ob_end_clean();
$num_fields = mysql_num_fields($result);
$headers = array();
$headers[] = "[Row]";
for ($i = 0; $i < $num_fields; $i++)
$headers[] = strtoupper(mysql_field_name($result , $i));
$current_date = date("y/m/d");
$filename = "MyFileName" . $current_date . ".csv";
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename='.$filename);
header('Pragma: no-cache');
header('Expires: 0');
echo "Title of Your CSV File\n\n";
fputcsv($fp, $headers);
$row_tally = 0;
// Write mysql rows to csv
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$row_tally = $row_tally + 1;
echo $row_tally.",";
fputcsv($fp, array_values($row));
}
die;
}
?>
Related
Im working on 2 json data which I need to transfer the data to separate excel files. What I did is, I made 2 function so that I can choose what file to be downloaded. The problem is when I tried to call both, the data is merged on a single excel. What I expect is it will be downloaded separately.
I tried adding sleep after the first function but didn't work, still the same output. I tried also using die after both function but only the first one is working.
Hope you help me.
SAMPLE CODE
function.php
<?php
function bjpk(){
$json = 'api link...';
$arr = json_decode(file_get_contents($json), true);
$name = $arr['code'];
header("Content-Disposition: attachment; filename=\"$name.xls\"");
header("Content-Type: application/vnd.ms-excel;");
header("Pragma: no-cache");
header("Expires: 0");
$out = fopen("php://output", 'w');
$data = array();
foreach ($arr['data'] as $key => $value) {
$data['date'] = substr($value['opentime'], 0, -9);
$data['num'] = substr($value['expect'], 4);
$codes = explode(',', $value['opencode']);
foreach ($codes as $key => $code) {
$data[$key] = $code;
}
fputcsv($out, $data,"\t");
}
fclose($out);
}
function cqssc(){
$json = 'api link..';
$arr = json_decode(file_get_contents($json), true);
$name = $arr['code'];
header("Content-Disposition: attachment; filename=\"$name.xls\"");
header("Content-Type: application/vnd.ms-excel;");
header("Pragma: no-cache");
header("Expires: 0");
$out = fopen("php://output", 'w');
$data = array();
foreach ($arr['data'] as $key => $value) {
$date = DateTime::createFromFormat('Ymd', substr($value['expect'], 0, -3));
$data['date'] = $date->format('Y-m-d');
$data['num'] = substr($value['expect'], 8);
$codes = explode(',', $value['opencode']);
foreach ($codes as $key => $code) {
$data[$key] = $code;
}
fputcsv($out, $data,"\t");
}
fclose($out);
}
index.php
<?php
require_once ('function.php');
bjpk();
cqssc();
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
What is the most efficient way to convert a MySQL query to CSV in PHP please?
It would be best to avoid temp files as this reduces portability (dir paths and setting file-system permissions required).
The CSV should also include one top line of field names.
SELECT * INTO OUTFILE "c:/mydata.csv"
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY "\n"
FROM my_table;
(the documentation for this is here: http://dev.mysql.com/doc/refman/5.0/en/select.html)
or:
$select = "SELECT * FROM table_name";
$export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) );
$fields = mysql_num_fields ( $export );
for ( $i = 0; $i < $fields; $i++ )
{
$header .= mysql_field_name( $export , $i ) . "\t";
}
while( $row = mysql_fetch_row( $export ) )
{
$line = '';
foreach( $row as $value )
{
if ( ( !isset( $value ) ) || ( $value == "" ) )
{
$value = "\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );
if ( $data == "" )
{
$data = "\n(0) Records Found!\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=your_desired_name.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
Check out this question / answer. It's more concise than #Geoff's, and also uses the builtin fputcsv function.
$result = $db_con->query('SELECT * FROM `some_table`');
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++) {
$headers[] = mysql_field_name($result , $i);
}
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = $result->fetch_array(MYSQLI_NUM)) {
fputcsv($fp, array_values($row));
}
die;
}
Look at the documentation regarding the SELECT ... INTO OUTFILE syntax.
SELECT a,b,a+b INTO OUTFILE '/tmp/result.txt'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM test_table;
An update to #jrgns (with some slight syntax differences) solution.
$result = mysql_query('SELECT * FROM `some_table`');
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++)
{
$headers[] = mysql_field_name($result , $i);
}
$fp = fopen('php://output', 'w');
if ($fp && $result)
{
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = mysql_fetch_row($result))
{
fputcsv($fp, array_values($row));
}
die;
}
If you'd like the download to be offered as a download that can be opened directly in Excel, this may work for you: (copied from an old unreleased project of mine)
These functions setup the headers:
function setExcelContentType() {
if(headers_sent())
return false;
header('Content-type: application/vnd.ms-excel');
return true;
}
function setDownloadAsHeader($filename) {
if(headers_sent())
return false;
header('Content-disposition: attachment; filename=' . $filename);
return true;
}
This one sends a CSV to a stream using a mysql result
function csvFromResult($stream, $result, $showColumnHeaders = true) {
if($showColumnHeaders) {
$columnHeaders = array();
$nfields = mysql_num_fields($result);
for($i = 0; $i < $nfields; $i++) {
$field = mysql_fetch_field($result, $i);
$columnHeaders[] = $field->name;
}
fputcsv($stream, $columnHeaders);
}
$nrows = 0;
while($row = mysql_fetch_row($result)) {
fputcsv($stream, $row);
$nrows++;
}
return $nrows;
}
This one uses the above function to write a CSV to a file, given by $filename
function csvFileFromResult($filename, $result, $showColumnHeaders = true) {
$fp = fopen($filename, 'w');
$rc = csvFromResult($fp, $result, $showColumnHeaders);
fclose($fp);
return $rc;
}
And this is where the magic happens ;)
function csvToExcelDownloadFromResult($result, $showColumnHeaders = true, $asFilename = 'data.csv') {
setExcelContentType();
setDownloadAsHeader($asFilename);
return csvFileFromResult('php://output', $result, $showColumnHeaders);
}
For example:
$result = mysql_query("SELECT foo, bar, shazbot FROM baz WHERE boo = 'foo'");
csvToExcelDownloadFromResult($result);
// Export to CSV
if($_GET['action'] == 'export') {
$rsSearchResults = mysql_query($sql, $db) or die(mysql_error());
$out = '';
$fields = mysql_list_fields('database','table',$db);
$columns = mysql_num_fields($fields);
// Put the name of all fields
for ($i = 0; $i < $columns; $i++) {
$l=mysql_field_name($fields, $i);
$out .= '"'.$l.'",';
}
$out .="\n";
// Add all values in the table
while ($l = mysql_fetch_array($rsSearchResults)) {
for ($i = 0; $i < $columns; $i++) {
$out .='"'.$l["$i"].'",';
}
$out .="\n";
}
// Output to browser with appropriate mime type, you choose ;)
header("Content-type: text/x-csv");
//header("Content-type: text/csv");
//header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=search_results.csv");
echo $out;
exit;
}
I am trying to develop a function for exporting the report contents to a xls file and giving users an option to have an xls file downloaded for the results they are seeing on webpage. Below is the code i have tried:
<?php
class export
{
public function exportxls($cols,$values)
{
function xlsBOF() {
echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
}
function xlsEOF() {
echo pack("ss", 0x0A, 0x00);
}
function xlsWriteNumber($Row, $Col, $Value) {
echo pack("sssss", 0x203, 14, $Row, $Col, 0x0);
echo pack("d", $Value);
}
function xlsWriteLabel($Row, $Col, $Value) {
$L = strlen($Value);
echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L);
echo $Value;
}
// prepare headers information
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment; filename=\"export_".date("Y-m-d").".xls\"");
header("Content-Transfer-Encoding: binary");
header("Pragma: no-cache");
header("Expires: 0");
// start exporting
xlsBOF();
$j=1;
$ret = array_map (
function ($_) {return explode (',', $_);},
explode (';', $values)
);
$colarray=explode(',',$cols);
$number=count($colarray);
for($i=0;$i<$number;$i++)
{
xlsWriteLabel(0,$i,$colarray[$i]);
}
foreach($ret as $key->$value)
{
xlsWriteLabel($j,$key,$value[$key]);
$j=$j+1;
}
xlsEOF();
}
}
?>
and here is the index file from which function is called:
<?php
include 'newxls.php';
$obj=new export();
$obj->exportxls("id,name,class","1,var,btech;2,man,mtech");
?>
Please do help me; I am not getting the required output in excel file.
Thanks in advance
Your code looking good except few changes needed
Change this code
foreach($ret as $key->$value)
{
xlsWriteLabel($j,$key,$value[$key]);
$j=$j+1;
}
Replace with this
foreach ($ret as $key => $value) {
foreach($value as $k=>$v){
xlsWriteLabel($j, $k, $v);
}
$j = $j + 1;
}
All remaining code looking fine.
Try This,
$filename ="excelreport";
function exportexcel($fields = array(), $values = array()){
foreach($fields as $field){
$contents .= $field." \t";
}
$contents. = " \n";
foreach($values as $value){
$contents.= $value[0]. " \t";
$contents.= $value[1]. " \t";
$contents.= $value[2]. " \n";
}
return $contents;
}
header('Content-type: application/ms-excel');
header("Content-Disposition: attachment; filename=". $filename . date("Y-m-d-H-i") .".xls");
header("Cache-Control: no-cache, must-revalidate");
$contents = exportexcel(array("id,name,class"),array(array('1','test','btech'),array('2','man','mtech')));
echo $contents;
I have got problem with encoding while I transferring data from MySQL to .XLS file. Table is in "utf8_czech_ci" and PHP script in UTF-8. I always get characters like "ěščřžýáíé" in bad form like "ěšÄřžýáÃé". There is my script
<?php
mb_http_input("utf-8");
mb_http_output("utf-8");
$dbhost = "XXXXXXXXXXX";
$dbuser = "XXXXXXXXXXX";
$dbpass = "XXXXXXXXXXX";
$dbname = "XXXXXXXXXXX";
$dbtable = $_GET['table'];
function xlsBOF() {
echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
return;
}
function xlsEOF() {
echo pack("ss", 0x0A, 0x00);
return;
}
function xlsWriteLabel($Row, $Col, $Value ) {
$L = strlen($Value);
echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L);
echo $Value;
return;
}
$dbc = mysql_connect( $dbhost , $dbuser , $dbpass ) or die( mysql_error() );
mysql_query("set names utf8;");
mysql_select_db( $dbname );
$q = "SELECT * FROM ".$dbtable."";
$qr = mysql_query( $q ) or die( mysql_error() );
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-type: application/vnd.ms-excel; charset=utf-8");
header("Content-Disposition: attachment;filename=export_".$dbtable.".xls ");
header("Content-Transfer-Encoding: binary ");
xlsBOF();
$col = 0;
$row = 0;
$first = true;
while( $qrow = mysql_fetch_assoc( $qr ) )
{
if( $first )
{
foreach( $qrow as $k => $v )
{
xlsWriteLabel( $row, $col, strtoupper( ereg_replace( "_" , " " , $k ) ) );
$col++;
}
$col = 0;
$row++;
$first = false;
}
foreach( $qrow as $k => $v )
{
xlsWriteLabel( $row, $col, $v );
$col++;
}
$col = 0;
$row++;
}
xlsEOF();
exit();
Thanks for responses ...
An Excel file uses a codepage block to identify the character set being used within the file, but by default it will use the locale codepage. If you want to force UTF-8, then you'll need to write a UTF-8 codepage block as well
$record = 0x0042; // Record identifier
$length = 0x0002; // Number of bytes to follow
$cv = 0x04B0; // The UTF-8 code page
$header = pack('vv', $record, $length);
$data = pack('v', $cv);
I found a little script that will export information to an xls file, but I can't seem to get it working. The original code is found here: http://www.appservnetwork.com/modules.php?name=News&file=article&sid=8
And here's my code:
// Query Database
$query = 'SELECT * FROM #__db_clients WHERE published = '1' AND companyid IN (1,2) AND country = 'Africa' ORDER BY state ASC';
$db->setQuery($query);
$rows = $db->loadObjectList();
if ($rows) {
function xlsBOF() {
echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
return;
};
function xlsEOF() {
echo pack("ss", 0x0A, 0x00);
return;
};
function xlsWriteNumber($Row, $Col, $Value) {
echo pack("sssss", 0x203, 14, $Row, $Col, 0x0);
echo pack("d", $Value);
return;
};
function xlsWriteLabel($Row, $Col, $Value ) {
$L = strlen($Value);
echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L);
echo $Value;
return;
};
// Send Header
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");;
header("Content-Disposition: attachment;filename=export.xls ");
header("Content-Transfer-Encoding: binary ");
// XLS Data Cell
xlsBOF();
xlsWriteLabel(1,0,"Company ID");
xlsWriteLabel(1,1,"Company Name");
xlsWriteLabel(1,2,"Address");
xlsWriteLabel(1,3,"Address 2");
xlsWriteLabel(1,4,"Suburb");
xlsWriteLabel(1,5,"City");
xlsWriteLabel(1,6,"State");
xlsWriteLabel(1,7,"Post Code");
xlsWriteLabel(1,8,"Country");
xlsWriteLabel(1,9,"Date");
xlsWriteLabel(1,10,"Phone Business");
xlsWriteLabel(1,11,"Phone Direct");
xlsWriteLabel(1,12,"Fax");
xlsWriteLabel(1,13,"Phone Mobile");
xlsWriteLabel(1,14,"Phone Personal");
xlsWriteLabel(1,15,"Discount");
xlsWriteLabel(1,16,"Title");
xlsWriteLabel(1,17,"Name");
xlsWriteLabel(1,18,"Surname");
xlsWriteLabel(1,19,"Position");
xlsWriteLabel(1,20,"Email");
xlsWriteLabel(1,21,"Contact");
xlsWriteLabel(1,22,"Introduced");
xlsWriteLabel(1,23,"Comments");
xlsWriteLabel(1,24,"Type");
xlsWriteLabel(1,25,"Status");
xlsWriteLabel(1,26,"Rating");
xlsWriteLabel(1,27,"Credit Terms");
xlsWriteLabel(1,28,"Classifications");
$xlsRow = 2;
$i = 0;
foreach ($rows as $item) {
$companyid = $rows[$i]->companyid;
$company = $rows[$i]->company;
$address = $rows[$i]->address;
$address2 = $rows[$i]->address2;
$suburb = $rows[$i]->suburb;
$city = $rows[$i]->city;
$state = $rows[$i]->state;
$pcode = $rows[$i]->pcode;
$country = $rows[$i]->country;
$date = $rows[$i]->date;
$phone_b = $rows[$i]->phone_b;
$phone_d = $rows[$i]->phone_d;
$phone_f = $rows[$i]->phone_f;
$phone_m = $rows[$i]->phone_m;
$phone_p = $rows[$i]->phone_p;
$discount = $rows[$i]->discount;
$title = $rows[$i]->title;
$name = $rows[$i]->name;
$surname = $rows[$i]->surname;
$position = $rows[$i]->position;
$email = $rows[$i]->email;
$contact = $rows[$i]->contact;
$introduced = $rows[$i]->introduced;
$comments = $rows[$i]->comments;
$type = $rows[$i]->type;
$status = $rows[$i]->status;
$rating = $rows[$i]->rating;
$cterms = $rows[$i]->cterms;
$classifactions = $rows[$i]->classifactions;
xlsWriteNumber($xlsRow,0,"$companyid");
xlsWriteNumber($xlsRow,1,"$company");
xlsWriteNumber($xlsRow,2,"$address");
xlsWriteNumber($xlsRow,3,"$address2");
xlsWriteNumber($xlsRow,4,"$suburb");
xlsWriteNumber($xlsRow,5,"$city");
xlsWriteNumber($xlsRow,6,"$state");
xlsWriteNumber($xlsRow,7,"$pcode");
xlsWriteNumber($xlsRow,8,"$country");
xlsWriteNumber($xlsRow,9,"$date");
xlsWriteNumber($xlsRow,10,"$phone_b");
xlsWriteNumber($xlsRow,11,"$phone_d");
xlsWriteNumber($xlsRow,12,"$phone_f");
xlsWriteNumber($xlsRow,13,"$phone_m");
xlsWriteNumber($xlsRow,14,"$phone_p");
xlsWriteNumber($xlsRow,15,"$discount");
xlsWriteNumber($xlsRow,16,"$title");
xlsWriteNumber($xlsRow,17,"$name");
xlsWriteNumber($xlsRow,18,"$surname");
xlsWriteNumber($xlsRow,19,"$position");
xlsWriteNumber($xlsRow,20,"$email");
xlsWriteNumber($xlsRow,21,"$contact");
xlsWriteNumber($xlsRow,22,"$introduced");
xlsWriteNumber($xlsRow,23,"$comments");
xlsWriteNumber($xlsRow,24,"$type");
xlsWriteNumber($xlsRow,25,"$rating");
xlsWriteNumber($xlsRow,26,"$status");
xlsWriteNumber($xlsRow,27,"$cterms");
xlsWriteNumber($xlsRow,28,"$classifactions");
$xlsRow++;
$i++;
};
xlsEOF();
exit();
};
I echoed out each row to make sure data is being passed through, which is ok, but for some reason, the xls file is spitting out like this:
Company ID Company Name Address
1 0 2
2 0 0
And so on, it seems to be somehow passing through a number, but not the actual information.. Can anyone help me out? Or point me to a decent export to excel (xls).. :)
EDIT:
If anyone can figure out how to set xlsWriteLabel to be bold, that would be fantastic :)
If the actual information is strings, this won't work. Pack("d" is trying to cast it as a Double instead of a String.
You need to create a xlsWriteString function.
Looks like there's one here: http://hunter.forumotion.com/forum-f9/topic-t98.htm
function xlsWriteString( $Row , $Col , $Value )
{
$L = strlen( $Value );
echo pack( "ssssss" , 0x204 , 8 + $L , $Row , $Col , 0x0 , $L );
echo $Value;
return;
}
I think if you client are using Office 2007, you have better to look into the Open Document.
there is an implementation in php there. Also the Excel 2007 viewer is free so.