Php generates excel xls documents

Source: Internet
Author: User

Php tutorial to generate excel xls document

Method 1-use the HTTP Header

As described in MS Word, You Need To Format HTML/PHP pages using Excel-friendly CSS and header information

Add to your PHP script.
<? Php
Header ("Content-type: application/vnd. ms-excel ");
Header ("Content-Disposition: attachment?filename=document_name.xls ");

Echo "Echo "<meta http-equiv =" Content-Type "content =" text/html;

Charset = Windows-1252 "> ";
Echo "<body> ";
Echo "<B> testdata1 </B> t <u> testdata2 </u> t n ";
Echo "</body> ";
Echo "?>

Method 2-Use a COM Object

Note that the code described in MS Excel must be installed after running on the server.

We use a file to save to the temporary directory first, as the same practice of MS Word.

// Create new COM object-excel. application
$ Xl = new COM ("excel. application ");

// Hide MS Excel application window
$ Xl-> Visible = 0;

// Create new document
$ XlBook = $ xl-> Workbooks-> Add ();

// Create Sheet 1
$ XlBook-> Worksheets (1)-> Name = "Worksheet 1 ";
$ XlBook-> Worksheets (1)-> Select;

// Set Width & Height
$ Xl-> ActiveSheet-> Range ("A1: A1")-> ColumnWidth = 10.0;
$ Xl-> ActiveSheet-> Range ("B1: B1")-> ColumnWidth = 13.0;

// Add text
$ Xl-> ActiveSheet-> Cells (1, 1)-> Value = "TEXT ";
$ Xl-> ActiveSheet-> Cells (1, 1)-> Font-> Bold = True;

// Save document
$ Filename = tempnam (sys_get_temp_dir (), "excel ");
$ XlBook-> SaveAs ($ filename );

// Close and quit
Unset ($ xlBook );
$ Xl-> ActiveWorkBook-> Close ();
$ Xl-> Quit ();
Unset ($ xl );

Header ("Content-type: application/vnd. ms-excel ");
Header ("Content-Disposition: attachment?filename=document_name.xls ");

// Send file to browser
Readfile ($ filename );
Unlink ($ filename );


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.