Those who want to save html data to excel file and facing cross browser issue due to server side scripting (As they don’t support in all browser). It will be better if you try PHPExcel library for this. PHPExcel is a php library which writes to excel file from the server returned data. The main features of the library is that is supports styling and many more options to make an excel file with an attractive layout. Using PHPExcel is not a difficult task at all. But when I faced same problem I did not get a very good solution for it. So today I am sharing some common use of it.
How to use it
Download the plugin from this link https://phpexcel.codeplex.com/ and keep it on the directory and call it by adding the file and create excel object.
require get_template_directory() . ' /phpexcel/PHPExcel.php';
require get_template_directory() . ' /phpexcel/PHPExcel/IOFactory.php';
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set document properties
$objPHPExcel->getProperties()->setCreator("")
->setLastModifiedBy("")
->setTitle("")
->setSubject("")
->setDescription("")
->setKeywords("")
->setCategory("");
// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle($quotation_id);
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
Some Basic Methods
To add an image to your excel file use code below.
$gdImage = imagecreatefromjpeg($image_url);
$objDrawing = new PHPExcel_Worksheet_MemoryDrawing();
$objDrawing->setName('Park Logo');
$objDrawing->setDescription('Park Logo');
$objDrawing->setImageResource($gdImage);
$objDrawing->setRenderingFunction(PHPExcel_Worksheet_MemoryDrawing::RENDERING_JPEG);
$objDrawing->setMimeType(PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_DEFAULT);
$objDrawing->setHeight(100);
$objDrawing->setWidth(134);
$objDrawing->setCoordinates('A1');
$objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
For writing into cell directly use code below.
$objPHPExcel->getActiveSheet()->setCellValue('E1', 'Hello World !');
For merging cells and apply style to it use code below
$style = array(
'font' => array('bold' => true, 'size' => 20,),
'alignment' => array('horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,),
);
$objPHPExcel->getActiveSheet()->mergeCells('a10:e10');
$objPHPExcel->getActiveSheet()->getStyle('a10')->applyFromArray($style);
To set autosize to a cell
$objPHPExcel->getActiveSheet()->getColumnDimension('a')->setAutoSize(true);
Working with loop is easier. Just increment the cell values.
for ($x = 0; $x <= 10; $x++) { $objPHPExcel->getActiveSheet()->setCellValue('a'.$x, 'hello world');
}
Set Output directory and save the file.
$outputdir = ABSPATH . 'uploads/excel/';
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save(str_replace('.php', '.xlsx', $outputdir.'/'.str_replace( basename(__FILE__), "$file_name.xlsx", basename(__FILE__) )));
Hope this code helps you a little bit.