0

I want to generate a CSV file using php. I am able to generate simple CSV file but I want to set font-size and font-color dynamically for headings. I found some libraries but those were not upto the mark.

Here is the code by which I can generate simple CSV file

$fp = fopen(FCPATH .'assets/' . $filename,'w');
$content = "";

foreach ($query_pairs->result() as $pair) {
    $content .= '<th>' . @$users[$pair->uid1]->name . '</th>' . $sep . ' ' . @$users[$pair->uid2]->name . PHP_EOL;
}

fwrite($fp,$content);
fclose($fp);

header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=".$filename);
header("Pragma: no-cache");
header("Expires: 0");

readfile(FCPATH .'assets/' . $filename);

Please help

J. Steen
  • 15,470
  • 15
  • 56
  • 63
kunal
  • 51
  • 7
  • 2
    CSV files by definition do **not** support any kind "styling" – Leigh Oct 17 '12 at 10:00
  • Why are you preparing an HTML output? Why do you set the content type to `application/vnd.ms-excel` but talking about CSV files? Do you know the differences between the proprietary Excel format and a CSV file? – feeela Oct 17 '12 at 10:05
  • @feeela - Doesn't know the the difference between Excel BIFF format and CSV, nor between HTML and CSV.... but it seems a common mistake. Everyone seems to believe in the tooth fairy and in PHP's automagic extension – Mark Baker Oct 17 '12 at 10:09

2 Answers2

3

I'm afraid that's impossible.

CSV, by definition, only contains data. I'm sorry to bear the bad news, but there will never be a way to do what you're trying to do with CSV.

What you can do, with some limits, is export HTML to Excel. This is often done in the absence of Excel libraries.

But for PHP, there are ways to generate Excel files. See for example this: http://code.google.com/p/php-excel/

Hope it helps!

Teekin
  • 12,581
  • 15
  • 55
  • 67
  • Actually I want to create CSV file so that when any user open that file using MS Excel he can see the data with some styling. Thanks – kunal Oct 17 '12 at 10:17
  • 1
    Yeah, I'm afraid that's impossible, mate. Sorry. CSV cannot contain styling. - Your best bet is then exporting HTML. Excel can render certain HTML styling from HTML tables, and others can open the table in a browser. – Teekin Oct 17 '12 at 10:19
3

Why not create a real Excel file (BIFF or OfficeOpenXML format, your choice) using one of the many PHP libraries that can actually generate Excel files rather than simnple HTML markup or CSV masquerading as Excel

Community
  • 1
  • 1
Mark Baker
  • 209,507
  • 32
  • 346
  • 385