views:

531

answers:

4

Hi,

I am creating an excel file using php like this:

header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=invoice.xls");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
echo "<table><tr><th>Test</th></tr><tr><td>...</td></tr></table>";

When I try open the file, excel gives a warning that the file type is not correct. However, the file is displayed correctly and exactly like I want it to...

Is there a way to prevent this error message showing up?

+1  A: 

The best way is to create an Excel file for yourself and save it as HTML, then open it in some text editor and take a look at the garbage. You'll eventually find out what to output in your PHP script so that Excel won't complain about file types and extensions.

Ionuț G. Stan
Thanks, I will try that... Unless someone else can tell me what 'garbage' I should include in my php file...
Fortega
The easiest format to replicate is the Excel XML file - so if you're going to take this approach, I'd recommend copying that.
BrynJ
A: 

The file output you are generating is not really in excel format, so excel is right to complain about it. There are several php packages for making excel files out there, like phpexcel.net. The other option would be to offer the file as a 'normal' .html file and instructing your users to open it in excel.

Hope this helps!

ylebre
So you are actually saying that the solution proposed by lonut G. Stan above is not going to work?
Fortega
@Fortega, how about giving it a try? I tried with your code and it complained. I then saved a spreadsheet as an HTML file and didn't complain when opening it.
Ionuț G. Stan
I'm pretty sure it will work, but you'd have to serve the file as an HTML file still (ie with a .html extension). If that is the case, the end user will probably still open the file in an application for HTML files (like a webbrowser) instead of excel.
ylebre
@ylebre: and that is not what I want...@lonut: it doesn't complain because it is an html file, and it should be a .xls
Fortega
@Fortega - Excel does complain because of the file extension...even if it is able to process an html file as a valid spreadsheet, by giving the file an xls extension you are telling Excel it is native file, when it is not.
BrynJ
A: 

I posted a similar question here that has some useful answers.

I've actually resolved this myself by creating a class that outputs XML Excel files with no warnings etc. I hope to package it properly when I get the chance, so I can share with others.

BrynJ
A: 

you could try tab delimited format i am not sure if it would complain about loading it or not eg echo "$col\t$col\t$col\t$col\n"

i have also used the pear excel generation libraries they generate BIFF format excel files, it is quite simple to use and you get control of the formatting of cells as well eg font, size, colour, etc

bumperbox