PHP operation excel files are based on phpexcel

  • 2020-03-31 20:50:53
  • OfStack

So the first step is to get the data out of excel. Here I use an open source PHP processing excel categories: phpexcel. The detailed information on http://phpexcel.codeplex.com/.
I am currently using version 1.7.3 of PHPExcel, which has a PHPExcel and phpexcel.php file unzipped.
We're mainly using that PHP file. See the following file directory structure
< img border = 0 SRC = "http://files.jb51.net/upload/201007/20100702000556665.jpg" border = 0 >

This version is said to be able to support excel2007, but I can't get this library support using XLSX edited in 2007. So I converted it to 2003. It feels supportive.
Here's how to use it:
 
require_once('./phpexcel1.7.3/PHPExcel.php'); 
$php_excel_obj = new PHPExcel(); 
$php_reader = newPHPExcel_Reader_Excel2007(); 

if(!$php_reader->canRead($file_name)) 
{ 
$php_reader= new PHPExcel_Reader_Excel5(); 
if(!$php_reader->canRead($file_name)) 
{ 
echo'NO Excel!'; 
} 
} 
$php_excel_obj = $php_reader->load($file_name); 
$current_sheet =$php_excel_obj->getSheet(0); 

The main function above is to initialize the relevant excel class and load the first sheet of excel

$all_column = $current_sheet - > GetHighestColumn ();
$all_row = $current_sheet - > GetHighestRow ();

Get the maximum column value of the table (letter for example: 'G') and the maximum number of rows (numeric for example)

Now I'm going to use loops to talk about the data in excel and read it into excel:
 
$all_arr = array(); 
$c_arr = array(); 

//Character comparison table
for($r_i = 1; $r_i<=$all_row; $r_i++) 
{ 
$c_arr= array(); 
for($c_i= 'A'; $c_i<= 'B'; $c_i++) 
{ 
$adr= $c_i . $r_i; 

$value= $current_sheet->getCell($adr)->getValue(); 

if($c_i== 'A' && empty($value) ) 
break; 
if(is_object($value)) 
$value= $value->__toString(); 
$c_arr[$c_i]= $value; 
} 

$c_arr&& $all_arr[] = $c_arr; 
} 



Here's a quick look at the phpexcel write operation, which is often used to import data from a database into excel for presentation and aesthetic purposes.
 
require_once('./phpexcel1.7.3/PHPExcel.php'); 

$excel_obj = new PHPExcel(); 
$objWriter = newPHPExcel_Writer_Excel5($excel_obj); 
$excel_obj->setActiveSheetIndex(0); 
$act_sheet_obj=$excel_obj->getActiveSheet(); 

$act_sheet_obj->setTitle('sheet'); 
$act_sheet_obj->setCellValue('A1', ' String content '); 
$act_sheet_obj->setCellValue('A2', 26); 

$file_name = "output.xls"; 
$objWriter->save($file_name); 

The code is as simple as initializing the relevant excel write class, writing the data, and saving it as an XLS file.
The output effect is shown in the figure
< img border = 0 SRC = "http://files.jb51.net/upload/201007/20100702000622151.jpg" border = 0 >

Related articles: