Categories
PHP / MySQL

How to generate excel from the array using PHPExcel

This tutorial will describe the usage of the PHPExcel library to generate an Excel file from a PHP array. Usage of PHPExcel library is very simple and easy. Just follow the below steps.

Similar Posts
CodeIgniter 4 – Export data to excel in CodeIgniter using PhpSpreadsheet
How to use PHPExcel with CodeIgniter?

1. First thing first – Download PHPExcel from – http://phpexcel.codeplex.com/

2. After downloading files Unzip the PHPExcel.zip files and we only need files and directories under the class directory. So just copy past the file from the class folder to your project folder. The below image shows that my folder structure.

3. Now include the PHPExcel.php file and create an object, just follow the comments.

How to generate excel from array using PHPExcel
setActiveSheetIndex(0);

// read data to active sheet
$doc->getActiveSheet()->fromArray($dataArray);

//save our workbook as this file name
$filename = 'just_some_random_name.xls';
//mime type
header('Content-Type: application/vnd.ms-excel');
//tell browser what's the file name
header('Content-Disposition: attachment;filename="' . $filename . '"');

header('Cache-Control: max-age=0'); //no cache
//save it to Excel5 format (excel 2003 .XLS file), change this to 'Excel2007' (and adjust the filename extension, also the header mime type)
//if you want to save it as .XLSX Excel 2007 format

$objWriter = PHPExcel_IOFactory::createWriter($doc, 'Excel5');

//force user to download the Excel file without writing it to server's HD
$objWriter->save('php://output');
?>

By Praveen Anaparthi

11+ years of IT industry experience holding a wide range of skill sets and roles with significant work on PHP, Node.js, Python, Ruby, Docker, React.js, Microsoft Azure, Azure DevOps, Windows PowerShell, Shell script, Jenkins, MongoDB, SQL, MySQL, Apache, Nginx. etc. It is my passion to learn new things and implement them as a practice. Aside from work, I like gardening and spending time with pets.

2 replies on “How to generate excel from the array using PHPExcel”

Hi Arjun,

I worked with PHPExcel and facing an issue with a new row which is created by the library automaticall.

I have a master excel file and i’m trying to delete few rows from it and rewriting that using $objWriter = PHPExcel_IOFactory::createWriter($doc, ‘Excel5’); function.

But there is a empty row inserting after the actual data row.

Can you please help me out.

Leave a Reply

Your email address will not be published.