473,387 Members | 1,812 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

PHP to create CSV that Excel can read

I am using PHP 4.3.2 to create a CSV file, however, Excel constantly
views it as a single-column spreadsheet with everything in quotes,
whereas OpenOffice Calc views it as a legitimate spreadsheet in
separate columns/cells.

[PHP]
class ReportGenerator {

/**
* Generate content based upon type
*
* @access private
* @param mixed $type type of content (e.g. Excel, CSV, Word, etc)
* @return mixed formatted content
*/
function &generateContent($type) { // STATIC STRING METHOD
$result = $this->getResult();

switch (strtolower($type)) {
case 'excel':
$delimiter = '</td><td valign="top">';
$lb = "\n</tr>\n<tr>";
break;
case 'csv':
$delimiter = ',';
$lb = "\n";
break;
default: // DO NOTHING
break;
}

if ($result && strcmp(strtolower($type), 'csv') != 0) $content =
'<table><tr>';
if ($result) $content .= $this->generateHeaders($type) . $lb;

$isFirstRow = true; $isEndOfFirstRow = true;

for ($i = 0; $i < @sizeof($result); $i++) {
$header = @array_keys(get_object_vars($result[$i]));
if (strcmp(strtolower($type), 'csv') != 0 && $isFirstRow) {
$isFirstRow = false;
$field = '<td valign="top">';
}
for ($j = 0; $j < @sizeof($header); $j++) {
if (strcmp(strtolower($type), 'csv') == 0) {
$field .= '"' . nl2br(preg_replace('/\r/', "\n",
preg_replace('/[\t]/', ' ', str_replace('"', '"',
$result[$i]->$header[$j])))) . '"';
} else {
$field .= nl2br(preg_replace('/\r/', "\n", preg_replace('/[\t]/',
' ', $result[$i]->$header[$j])));
}
$content .= $field . $delimiter;
$field = '';
}
if (strcmp(strtolower($type), 'csv') != 0 && $isEndOfFirstRow) {
$isEndOfFirstRow = false;
$content = preg_replace('/<td valign="top">$/', '', $content);
}
$content .= $lb;
$field = '';
$isFirstRow = true; $isEndOfFirstRow = true;
}

if ($result && strcmp(strtolower($type), 'csv') != 0) $content =
preg_replace('/<tr>$/', '', $content) . '</table>';

return $content;

}

}
[/PHP]

This class contains a method that will generate the CSV-formatted
content, however, it again fails to produce legitimate content in
Excel while producing just-fine content in OpenOffice.

Help!

Thanx
Phil
Jul 17 '05 #1
9 21808
Phil Powell wrote:
I am using PHP 4.3.2 to create a CSV file, however, Excel constantly
views it as a single-column spreadsheet with everything in quotes,
whereas OpenOffice Calc views it as a legitimate spreadsheet in
separate columns/cells.
*snip* This class contains a method that will generate the CSV-formatted
content, however, it again fails to produce legitimate content in
Excel while producing just-fine content in OpenOffice.

Help!

Thanx
Phil


Are you sending the appropriate http headers? I've used:

header ("Content-Type: application/msexcel");
header ("Content-Disposition: attachment; filename=\"filename.csv\"");

followed by a stream of comma separated text and it just works, in both
excel and oo.o

Be aware that you DONT want the first bytes in the csv to be "ID", Excel
treats the file as a .slk no matter what you tell it it really is. (THAT
took me a while to figure out! Doh!)

Sacs

Jul 17 '05 #2
.oO(Sacs)
Are you sending the appropriate http headers? I've used:

header ("Content-Type: application/msexcel");


Shouldn't that be application/vnd.ms-excel instead?

According to <http://www.iana.org/assignments/media-types/application/>
application/msexcel is not a registered MIME type.

Micha
Jul 17 '05 #3
Michael Fesser wrote:
.oO(Sacs)

Are you sending the appropriate http headers? I've used:

header ("Content-Type: application/msexcel");

Shouldn't that be application/vnd.ms-excel instead?

According to <http://www.iana.org/assignments/media-types/application/>
application/msexcel is not a registered MIME type.

Micha


Err, yes, it probably should be vnd.ms-excel :-)

application/msexcel does work though, for oo.o too, and thats the only
requirement I had at the time...

Thanks for pointing that out!

Sacs

Jul 17 '05 #4
In article <df********************************@4ax.com>,
Michael Fesser <ne*****@gmx.net> wrote:
Are you sending the appropriate http headers? I've used:

header ("Content-Type: application/msexcel");


Shouldn't that be application/vnd.ms-excel instead?

According to <http://www.iana.org/assignments/media-types/application/>
application/msexcel is not a registered MIME type.


THANK YOU for this URL! It's a great mystery to me if I'm using the
right mime type when I download things. This cleared up a lot. I do
note that Macintosh IE tends to use "octetstream" while all the other
browsers use "octet-stream". Anyone know why?

--
DeeDee, don't press that button! DeeDee! NO! Dee...

Jul 17 '05 #5
ph**************@gmail.com (Phil Powell) wrote in message news:<b5*************************@posting.google.c om>...
I am using PHP 4.3.2 to create a CSV file, however, Excel constantly
views it as a single-column spreadsheet with everything in quotes,
whereas OpenOffice Calc views it as a legitimate spreadsheet in
separate columns/cells.

[PHP] <snip> if (strcmp(strtolower($type), 'csv') == 0) {
$field .= '"' . nl2br(preg_replace('/\r/', "\n",
preg_replace('/[\t]/', ' ', str_replace('"', '"',
$result[$i]->$header[$j])))) . '"';

I have no clue, why you use nl2br() here. Also, what's the point in
str_replace('"', '"',..) ??

Perhaps you may want to try <http://in2.php.net/fputcsv> (CVS?) or
<http://in2.php.net/fgetcsv#14788>. The later worked very well for me
in many cases.

--
| Just another PHP saint |
Email: rrjanbiah-at-Y!com
Jul 17 '05 #6
Michael Vilain wrote:
I do note that Macintosh IE tends to use "octetstream" while
all the other browsers use "octet-stream". Anyone know why?


'Octetstream' is an unregistered subtype of the application
top-level type, and should therefore be prefixed with 'x-';
'octet-stream' is the registered subtype. The former is
more likely to cause the browser to ask its user what to do.

Note that browsers use whatever MIME media type they're
given, unless they're trying to guess the media type of a
file to be uploaded.

--
Jock
Jul 17 '05 #7
ng**********@rediffmail.com (R. Rajesh Jeba Anbiah) wrote in message news:<ab**************************@posting.google. com>...
ph**************@gmail.com (Phil Powell) wrote in message news:<b5*************************@posting.google.c om>...
I am using PHP 4.3.2 to create a CSV file, however, Excel constantly
views it as a single-column spreadsheet with everything in quotes,
whereas OpenOffice Calc views it as a legitimate spreadsheet in
separate columns/cells.

[PHP]

<snip>
if (strcmp(strtolower($type), 'csv') == 0) {
$field .= '"' . nl2br(preg_replace('/\r/', "\n",
preg_replace('/[\t]/', ' ', str_replace('"', '"',
$result[$i]->$header[$j])))) . '"';

I have no clue, why you use nl2br() here. Also, what's the point in
str_replace('"', '"',..) ??

Perhaps you may want to try <http://in2.php.net/fputcsv> (CVS?) or
<http://in2.php.net/fgetcsv#14788>. The later worked very well for me
in many cases.


Because. according to http://www.php.net, "fputcsv" is still in CVS,
and fgetcsv is useless to me since I'm doing a conversion to csv.

This works just fine again when opened in OpenOffice, but comes across
formatted incorrectly in Excel XP. I was told, however, you could
import the CSV instead.

Phil
Jul 17 '05 #8
Just maybe a stupid remark, but if you go to:
start => settings => control panel => regional options => numbers =>
list eperator and add ; (semicolon)you get it right

"John Dunlop" <us*********@john.dunlop.name> wrote in message
news:MP************************@News.Individual.NE T...
Michael Vilain wrote:
I do note that Macintosh IE tends to use "octetstream" while
all the other browsers use "octet-stream". Anyone know why?


'Octetstream' is an unregistered subtype of the application
top-level type, and should therefore be prefixed with 'x-';
'octet-stream' is the registered subtype. The former is
more likely to cause the browser to ask its user what to do.

Note that browsers use whatever MIME media type they're
given, unless they're trying to guess the media type of a
file to be uploaded.

--
Jock

Jul 17 '05 #9
ph**************@gmail.com (Phil Powell) wrote in message news:<b5*************************@posting.google.c om>...
<snip>
I have no clue, why you use nl2br() here. Also, what's the point in
str_replace('"', '"',..) ??

Perhaps you may want to try <http://in2.php.net/fputcsv> (CVS?) or
<http://in2.php.net/fgetcsv#14788>. The later worked very well for me
in many cases.


Because. according to http://www.php.net, "fputcsv" is still in CVS,
and fgetcsv is useless to me since I'm doing a conversion to csv.


Did you click both the links? *Read* the contents of the links?

--
<?php echo 'Just another PHP saint'; ?>
Email: rrjanbiah-at-Y!com
Jul 17 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: I Decker | last post by:
Hi all, Hope this is the right group. I am writing a program in c# to open create an excel document, enter some data, save it and then email it as an attachment. I have successfully created...
6
by: Steve Richter | last post by:
I am getting error in a vbscript: ActiveX component cant create object: Excel.Application. The vbscript code is: Dim objExcel Set objExcel = CreateObject("Excel.Application") I am pretty...
0
by: Johnny Fugazzi | last post by:
Basic question. I am working on an app that needs to open an excel file an read out data. Have posted a little about this before. The excel file is secured and the user cannot acces it. I...
27
by: jeniffer | last post by:
I need to create an excel file through a C program and then to populate it.How can it be done?
4
by: =?Utf-8?B?UHJpeWE=?= | last post by:
Hi, I'm developing a webservice whicg reads data from a database and exports to a excel sheet. This applciation works if i have MS Office installed in my system . Since i'm unable to install MS...
1
by: TG | last post by:
Hi! I have an application in which I have some checkboxes and depending which ones are checked those columns will show in the datagridview from sql server or no. After that I have 2 buttons:...
11
by: =?Utf-8?B?UGV0ZXIgSw==?= | last post by:
I am working with Visual Studio or alternately with Expression Web. I need to create about 50 aspx pages with about 1200 thumbnali images, typically arranged in three to four groups per page,...
4
by: =?Utf-8?B?Sm9zaW4gSm9obg==?= | last post by:
I could create MS Excel sheet using ASP.NET 2.0 with C# but it is not being created in some systems, following error occurs when the program compiles : Microsoft Office Excel cannot open or...
15
by: patf | last post by:
Hi - experienced programmer but this is my first Python program. This URL will retrieve an excel spreadsheet containing (that day's) msci stock index returns. ...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.