Reading and generating Excel files using the PHP Excel class

Source: Internet
Author: User
Tags php excel

There are a number of ways to build Excel using PHP, such as using the simplest carriage returns, tabs to generate, or directly using the HTML table format, but these methods are not compatible. Tested the Phpexce class, found that too strong, can output very complex Excel tables, and also can read Excel files. Gossip less, release the brief code:


<?php
Require_once './classes/phpexcel.php ';

$objExcel = new Phpexcel ();
$objWriter = new Phpexcel_writer_excel5 ($objExcel); For other version formats
$objExcel->setactivesheetindex (0);
$objActSheet = $objExcel->getactivesheet ();
Sets the name of the current active sheet

$objActSheet->settitle (' Sheet1 ');

$objActSheet->setcellvalue (' A2 ', ' China 11 '); Set the content A2 in Excel to represent coordinates

//Build Excel to File   
//$objWriter->save ('./test.xls ');  
//or direct browser download    ( Optional)
$outputFileName = "Output.xls";
Header ("Content-type:application/octet-stream;charset=utf-8");
Header (' Content-disposition:attachment filename= '. $outputFileName);
$objWriter->save (' php://output ');
?
You can also read Excel files, sample code
<?php
$xlsPath = './test.xls ';//specify Exls path to read
//$type = ' Excel2007 '; Set the type of Excel to resolve Excel5 (2003 or below) or Excel2007
$type = ' Excel5 ';
///Import Excel Class
include ' classes/phpexcel.php ';            
include ' classes/phpexcel/iofactory.php ';
$xlsReader = Phpexcel_iofactory::createreader ($type); 
$xlsReader->setreaddataonly (TRUE);
$ Xlsreader->setloadsheetsonly (TRUE);
$Sheets = $xlsReader->load ($xlsPath);
//start reading
$Sheet = $Sheets->getsheet (0)->toarray ()//Read the first worksheet (note that numbering starts at 0) if read multiple can do a loop 0,1,2,3 ...

//Get a two-dimensional array, where each decimal group is a row of the contents of the Excel table containing data for each column of this row  
Echo ' <pre> ';
Print_r ($Sheet);
?

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.