I can't figure out how to export a php table to an existing Excel file.
I'm new in php and until now I didn't understand how can I do that.
From my search I saw that it's needed a while and foreach statement.
<?php
$sql_data = date('d.m.Y', strtotime('-1days'));
require(realpath(dirname(__FILE__)."/PHPExcel-1.8/Classes/PHPExcel.php"));
$conn = oci_connect('USER', 'PASS', 'dark:1521/DAR');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
Else {echo 'Connection successfully !';
}
$parametri = oci_parse($conn, "SELECT * FROM TABLE_1 WHERE TO_DATE('${sql_data}','DD.MM.YYYY') BETWEEN T_FROM AND T_TILL");
oci_execute($parametri);
echo "<table border='1'>\n";
while ($row = oci_fetch_array($parametri, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->SetCellValue('A1', 'UD_NAME');
$objPHPExcel->getActiveSheet()->SetCellValue('B1', 'UD_CODE');
$objPHPExcel->getActiveSheet()->SetCellValue('C1', 'TECH_TYPE');
$objPHPExcel->getActiveSheet()->SetCellValue('D1', 'PPE_NAME');
$H_col = $objPHPExcel -> setActiveSheetIndex(0)->getHighestColumn();
$nr_col = PHPExcel_Cell::columnIndexFromString($H_col);
$nr_row = $objPHPExcel -> setActiveSheetIndex(0)->getHighestRow();
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
?>
function saveExcelFile($objPHPExcel, $file){
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: ' . $file . ';filename="01simple.xls"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0
$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
}
try this instead of
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
try to run phpexcel, "header was sent error" you can't use "echo" before headers
require(realpath(dirname(__FILE__)."/PHPExcel-1.8/Classes/PHPExcel.php"));
function saveExcelFile($objPHPExcel, $file){
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: ' . $file . ';filename="01simple.xls"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0
$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
}
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$objWorksheet = $objPHPExcel->getActiveSheet();
$objWorksheet->SetCellValue('A1', 'UD_NAME');
$objWorksheet->SetCellValue('B1', 'UD_CODE');
$objWorksheet->SetCellValue('C1', 'TECH_TYPE');
$objWorksheet->SetCellValue('D1', 'PPE_NAME');
saveExcelFile($objPHPExcel, 'attachment');
i don't know how this code below works, but test it separate
$sql_data = date('d.m.Y', strtotime('-1days'));
$conn = oci_connect('USER', 'PASS', 'dark:1521/DAR');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
Else {echo 'Connection successfully !';
}
$parametri = oci_parse($conn, "SELECT * FROM TABLE_1 WHERE TO_DATE('${sql_data}','DD.MM.YYYY') BETWEEN T_FROM AND T_TILL"
oci_execute($parametri);
echo "<table border='1'>\n";
while ($row = oci_fetch_array($parametri, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
Related
Hello everyone in my project, I am trying to export data from database to an xlsx file but I am not getting correct data.I have attached image of data.
I am using the following code.
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Writer\Xls;
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$exportArray = array();
$query = mysqli_query($conn, "select * from table");
if(mysqli_num_rows($query) > 0){
while ($row = mysqli_fetch_assoc($query)) {
$exportArray[$exp]['id'] = $row['id'];
$exportArray[$exp]['name'] = $row['name'];
$exportArray[$exp]['address'] = $row['address'];
$exp++;
}
}
$array = array();
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'id');
$sheet->setCellValue('B1', 'name');
$sheet->setCellValue('C1', 'address');
$rowCount = 2;
foreach ($exportArray as $value) {
$sheet->setCellValue('A' . $rowCount, $value['id']);
$sheet->setCellValue('B' . $rowCount, $value['name']);
$sheet->setCellValue('C' . $rowCount, $value['address']);
$rowCount++;
}
$fileName = 'test123.xls';
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'. $fileName .'.xlsx"');
header('Cache-Control: max-age=0');
$writer->save('php://output');
exit();
When I see the sheet data using below code
$sheetData = $sheet->toArray(null, true, true, true);
print_r($sheetData);
I am getting the right output. Everything looks fine but I don't understand, why am I getting data in wrong format in sheet?
Try This:
<?php
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Helper\Sample;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$conn = new mysqli("localhost","root","root","test");
$sql = "SELECT * FROM customers";
$result = $conn->query($sql);
$write_array = array();
$fileName = "excel.xlsx";
$write_array[] = array("id","name","address");
if($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
$write_array[] = array($row["id"],$row["name"],$row["address"]);
}
}
$conn->close();
$spreadsheet = new Spreadsheet();
$spreadsheet->setActiveSheetIndex(0);
$spreadsheet->getActiveSheet()->fromArray($write_array,NULL,'A1');
$spreadsheet->getActiveSheet()->setTitle("My Excel");
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$fileName.'"');
header('Cache-Control: max-age=0');
header('Cache-Control: max-age=1');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: cache, must-revalidate');
header('Pragma: public');
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
Add this use PhpOffice\PhpSpreadsheet\IOFactory;
Now use the following code to export data in Xlsx format
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="test.xlsx"');
header('Cache-Control: max-age=0');
header('Cache-Control: max-age=1');
header('Cache-Control: cache, must-revalidate');
header('Pragma: public');
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
in my case none of the above solutions worked.
I finally managed to solve it by adding this line: ob_end_clean();
just before: $writer->save('php://output');
ob_end_clean();
$writer->save('php://output');
//query fetching data from database
if (!$query)
return false; //if there is no data in query return false
// Starting the PHPExcel library
$this->load->library('PHPExcel');//loading library
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setTitle("export")->setDescription("none");
$objPHPExcel->setActiveSheetIndex(0);
// Field names in the first row
$fields = $query->list_fields();
$col = 0;
//add data into cells
foreach ($fields as $field) {
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $field);
$col++;
}
// Fetching the table data
$row = 2;
foreach ($query->result() as $data) {
$col = 0;
foreach ($fields as $field) {
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $data->$field);
$col++;
}
$row++;
}
$objPHPExcel->setActiveSheetIndex(0);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'csv');
//creating excel sheet
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="subscribers_sheet.csv"');
header('Cache-Control: max-age=0');
header('Cache-Control: max-age=1');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header('Pragma: public'); // HTTP/1.0
$objWriter->save('php://output');// inserting data into excel sheet
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header('Content-Type: application/vnd.openxmlformats officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="subscribers_sheet.csv"');
$objWriter->save("php://output");
DevelopersI am using Yii1 and I want to generate a report using PHPExcel extension but my file is not ready to download, instead it appears in console. I also set headers but still file is not ready for download. I can't find exact answer. please resolve my problem
public function GenerateReport($dataProvider)
{
$phpExcelPath = Yii::getPathOfAlias('ext.phpexcel.Classes');
include($phpExcelPath . DIRECTORY_SEPARATOR . 'PHPExcel.php');
$objPHPExcel = new PHPExcel();
$fileName = 'report-'.uniqid().'.xlsx';
$objPHPExcel->getProperties()->setCreator("Palash Gupta");
$objPHPExcel->getProperties()->setTitle($fileName);
$objPHPExcel->getProperties()->setSubject("Placement Student List");
$objPHPExcel->getProperties()->setDescription("Placement Student List");
$objPHPExcel->setActiveSheetIndex(0);
$rowCount = 1;
$objPHPExcel->getActiveSheet()->SetCellValue('A' . $rowCount, 'Name');
$objPHPExcel->getActiveSheet()->SetCellValue('B' . $rowCount, 'Course');
$rowCount = 2;
foreach ($dataProvider->getData() as $data)
{
$objPHPExcel->getActiveSheet()->SetCellValue('A' . $rowCount, $data['sd_fname']);
$objPHPExcel->getActiveSheet()->SetCellValue('B' . $rowCount, $data['fk_mc_id']);
$rowCount++;
}
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$fileName.'"');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
}
Try this:
// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'. $fileName .'"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;
Ref: https://github.com/PHPOffice/PHPExcel/blob/1.8/Examples/01simple-download-xls.php
i am writing values from a while loop into an excel sheet using PHPEXCEL. in doing this i need to write a title for each of the rows . what i only get now is the result from the database , how can i add a custom title
e.g
Premier League
EVENTID STARTDATE STATUS
1022 17-09-2013 Won
Premier League
EVENTID STARTDATE STATUS
3421 22-10-2012 lost
Here is my code
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("test2");
$sql=mysql_query("select * from event");
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Europe/London');
require_once '../Classes/PHPExcel.php';
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$rowCount = 1;
while($row = mysql_fetch_array($sql)){
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $row['EventID']);
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $row['StartDate']);
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowCount, $row['Status']);
$rowCount++;
}
// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="01simple.xls"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
something like this:
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$rowCount = 1;
$customTitle = array ('test a','test b','test c');
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $customTitle[0]);
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $customTitle[1]);
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowCount, $customTitle[2]);
$rowCount++;
while($row = mysql_fetch_array($sql)){
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $row['EventID']);
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $row['StartDate']);
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowCount, $row['Status']);
$rowCount++;
}
I am using php excel export the data in database to Excel format.
I can retrieve all the data from database to Excel ady. But if i wanna to retrieve the column name of the table, how i going to do. Anyone can help?
Here's my code:
<?php
header("Content-Type:application/vnd.ms-excel");
header("Content-Disposition:attachment;filename=product.xls");
header("Pragma:no-cache");
header("Expires:0");
header('Content-Type: text/html; charset=UTF-8');
header("Content-type: application/octetstream");
header('Content-Disposition: attachment; filename="export.csv"');
/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Europe/London');
if (PHP_SAPI == 'cli')
die('This example should only be run from a Web Browser');
/** Include PHPExcel */
require_once '../Classes/PHPExcel.php';
require_once '../Classes/PHPExcel/Writer/Excel2007.php';
require_once '../Classes/PHPExcel/IOFactory.php';
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("litako", $con);
$objPHPExcel = new PHPExcel();
$res= mysql_query("SELECT * FROM vendorlist ");
/** Error reporting */
error_reporting(E_ALL);
date_default_timezone_set('Europe/London');
$objPHPExcel = new PHPExcel();
if(!$res){
die("Error");
}
$col = 0;
$row = 3;
while($mrow = mysql_fetch_assoc($res)) {
$col = 0;
foreach($mrow as $key=>$value) {
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
$col++;
}
$row++;
}
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
// Save Excel 2007 file
$objPHPExcel->setActiveSheetIndex(0);
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="report.xls"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
You already have the column name in your while loop where you call mysql_fetch_assoc. The $key value is the column name. So here is an updated portion of your code:
while($mrow = mysql_fetch_assoc($res)) {
$col = 0;
foreach($mrow as $key=>$value) {
// TODO: Do Something With the Column Name like set the row header. Note this crude code sets it every time. You really just want to do it the first time only.
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, 0, $key);
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row + 1, $value);
$col++;
}
$row++;
}