Generating microsoft office documents (word, excel) on your webserver using php

Actually, this is much easier than you might think. The trick is to use the capability of excel and word to read html files

So just generate normal html, but use a content-type header line to force the browser to see this as a word or excel file: (using php)

header (“Content-type: application/msword”); or
header (“Content-type: application/vnd.ms-word”);
for word and
header (“Content-type: application/msexcel”); or
header (“Content-type: application/vnd.ms-excel”);

I have never seen any difference between msword and vnd.ms-word, so if anybody knows the difference, please respond.

Then you might want to define the local filename. This can be done using the content-disposition header:

header(“Content-Disposition: filename=\”invoice_$invoicenr.xls\””);

For excel, just start generating a html table. The full table is used as excel sheet with its rows and columns.
For word, just start generating html code. It is interpreted by word. Make sure to use a FULL url path if you want to include images.

Here is an example to generate a word document:

Click here to test it.


  • Priyaly Mohapatra

    The demo you have provided is working perfectly. But, the code you have shown above is not working. i ll be glad if you correct the code and update the same.