How to set correct indent phpword - php

I am using codeigniter and phpword I am trying to get the spacing like in this image below.
How ever my when I export the document out put is like
Question: In PHPWord how can I set the correct spacing I would like to make my out put the same as the first image.
public function export() {
$phpWord = new \PhpOffice\PhpWord\PhpWord();
$section = $phpWord->addSection();
$results = $this->get_events_for_export();
foreach ($results as $result) {
$date = strtotime($result['event_date']);
$line = date('M', $date) .' '. date('d', $date) .' '. date('D', $date) .' '. htmlentities($result['event_title']);
$section->addText($line . "\n");
}
// Saving the document as OOXML file...
$filename = 'date1.docx';
header("Content-Description: File Transfer");
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save("php://output");
exit();
}

After a couple of hours reading through some examples problem solved now using addParagraphStyle()
public function export() {
$phpWord = new \PhpOffice\PhpWord\PhpWord();
$leftTabStyleName = 'centerTab';
$phpWord->addParagraphStyle($leftTabStyleName, array('tabs' => array(new \PhpOffice\PhpWord\Style\Tab('center', 4680))));
$section->addTextBreak();
// New portrait section
$section = $phpWord->addSection();
// Add listitem elements
$fontStyle = new \PhpOffice\PhpWord\Style\Font();
$fontStyle->setBold(false);
$fontStyle->setName('Tahoma');
$fontStyle->setSize(16);
$section->addText("\tClub Program " . date('Y') .' / ' . date('Y', strtotime('+1 year')), $fontStyle, $leftTabStyleName);
$multipleTabsStyleName = 'multipleTab';
$phpWord->addParagraphStyle(
$multipleTabsStyleName,
array(
'tabs' => array(
new \PhpOffice\PhpWord\Style\Tab('left', 1000),
new \PhpOffice\PhpWord\Style\Tab('center', 1000),
new \PhpOffice\PhpWord\Style\Tab('right', 1000),
)
)
);
$results = $this->get_events_for_export();
foreach ($results as $result) {
$date = strtotime($result['event_date']);
$section->addText(date('M', $date) ."\t". date('d', $date) ."\t". date('D', $date) ."\t". htmlentities($result['event_title']), null, $multipleTabsStyleName);
}
$filename = 'club_program-' . time() . '.docx';
header("Content-Description: File Transfer");
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save("php://output");
exit();
}

Related

PHP Mailer: XLSX file coruplted when sending from html file

I am currently having a problem with my PHP code as it corrupts the data/xlsx file when exporting it from HTML.
i am viewing PHP Mailer scripts which has multiple pages connected to it.
This is my PHP XLS Function.
this->_request->download ? true : false;
$htmlPath = realpath(dirname(__FILE__) . "/../../public/reports/html/") . "/" . $fileName;
$fileSource = file_get_contents($htmlPath);
preg_match('!<title>([^<]+)!', $fileSource, $title);
$title = trim($title[1]);
if (stristr($fileSource, '<graph>')) {
$fileSource = preg_replace('!<graph>[^<]+</graph>!is', '', $fileSource);
file_put_contents($htmlPath, $fileSource);
}
file_put_contents($htmlPath,preg_replace('!<title>[^<]+</title>!is','',$fileSource));
$reader = new PHPExcel_Reader_HTML;
$content = $reader->load($htmlPath);
// Pass to writer and output as needed
$objWriter = PHPExcel_IOFactory::createWriter($content, 'Excel2007');
$download = 1;
// Redirect output to a client’s web browser (Excel5)
//header('Content-Type: application/vnd.ms-excel');
$fileName = str_replace(' ', '-', ($title . "-" . date('Y-m-d')));
if ($download) {
// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
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
header('Content-Disposition: attachment;
filename=' . $fileName . ".xlsx")
this is my caller function
if ($reportRow->reportString) {
$reportRow->reportString = stripslashes($reportRow->reportString);
if (!stristr($reportRow->reportString, '</body>'))
$reportRow->reportString = $reportRow->reportString . "</table></body></html>";
$fileName = time() . rand(111, 222);
$htmlPath = realpath(dirname(__FILE__) . "/../../public/reports/html/") . "/" . $fileName;
if ($headerPath) {
$reportRow->html_string = preg_replace('!(\s*</htmlpageheader>)!', '$1<img width="100%" style="clear:both" id="headerPath" src="' . $headerPath . '" />', $reportRow->html_string);
}
$corp_name = preg_replace('!\s+!',' ',$userSessionData->corp_name);
$reportRow->reportString = preg_replace_callback(
'!<title>([^<]+)!is',
function($matches) use ($corp_name){
return '<title>' . $corp_name . '_' . preg_replace('!\s+!',' ',$matches[1]);
},
$reportRow->reportString
);
file_put_contents($htmlPath, $reportRow->reportString);
$kilobites = filesize($htmlPath);
$kilobites = $kilobites / 1024;
$kilobites = 0;
if ($ifXLS) {
echo json_encode(array(
'reportPath' => '/helper/file-To-xls/fileName/' . $fileName,
'error' => false
));
would anyone have any ideas on how to fix this issue?
you can use CSV functions or PHPExcel to do it straight forward
or you can try like below
<?php
$file="1.xls";
$html="<table><tr><td>Col1</td><td>Col2</td></tr></table>";
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$file");
echo $html;
?>
The header for .xlsx files is Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet if you prefer to export it as .xlsx

Problem in exporting data array to xlsx file using PhpSpreadsheet

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');

Unable to download my CSV file on Safari using PHP

I am facing with strange problem while exporting my csv file on safari it is just displaying on browser instead of downloading .While same code is working with Firefox and Crome.I have searched but nothing is working for me. Please help. Here is my code-
<?php
ob_clean();
ob_start();
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
header('Pragma: no-cache');
header('Expires: 0');
function exportData() {
$fp = fopen('php://output', 'w');
fputcsv($fp, array('Market ID', 'Market Name', 'Suburb', 'State', 'Start Time', 'End Time', 'Status',"~"));
include "database.php";
$dbquery = #$_POST['query'];
$queryAllUser = $dbquery;
$resultAllUser = mysql_query($queryAllUser);
$countAllUser = mysql_num_rows($resultAllUser);
if($countAllUser > 0)
{
while($rowMarketId= mysql_fetch_assoc($resultAllUser))
{
$marketId = $rowMarketId['mrkt_id'];
$isCancel = $rowMarketId['is_cancel'];
$openning_tim = $rowMarketId['openning_time'];
$closing_tim = $rowMarketId['closing_time'];
$suburb = $rowMarketId['suburb'];
$name = $rowMarketId['name'];
$state = $rowMarketId['state'];
if($isCancel == 0)
{
$status_type = "Open";
}
else
{
$status_type = "Close";
}
$val = array();
$val[] = $marketId;
$val[] = $name;
$val[] = $suburb;
$val[] = $state;
$val[] = $openning_tim;
$val[] = $closing_tim;
$val[] = $status_type;
$val[] = "~";
fputcsv($fp, $val);
}
}
}
exportData();
?>
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Content-Type: application/force-download");
header('Content-Disposition: attachment; filename=' .urlencode(basename($filename)));
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
Try With this Headers........ This should Work..

Trying to download created file using PHPExcel

I followed questions on stackoverflow and ended up with the following code
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="'.$name.'.xlsx"');
$objWriter->save('php://output');
The problem is the output file is wrong, its in Chinese (encoding probably), i want to know if there is a header for encoding or if its another problem.
Edit:
header('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Length: ' . filesize($file));
header('Content-Transfer-Encoding: binary');
header('Pragma: public');
Excel preparation code:
$iterator = 0;
foreach (get_object_vars($temp[0]) as $key => $value){
$formattedkey = str_replace('_', ' ', $key);
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($iterator, 1, $formattedkey);
$iterator++;
$fieldsnum++;
}
$rowiterator = 2;
foreach ($temp as $asset){
$coliterator = 0;
foreach (get_object_vars($asset) as $key => $value){
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($coliterator, $rowiterator, utf8_encode($value));
$coliterator++;
}
$rowiterator++;
}

transfer data from Mysql to excel

I had created a website using php. In that website,I want to create a report like thing,which involves transferring details from one table to an excel sheet which is downloadable.Is there any way to do this work? Please help me to find the solution.
Thank you.
You can fetch all rows from the database and use fputcsv function to put it as csv
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment;filename=export.csv");
header("Content-Transfer-Encoding: binary");
$csvHandler = fopen("php://output", 'w');
while ($row = mysql_fetch_array ($res))
{
fputcsv($csvHandler, $row);
}
You can use PHPExcel for generating data
and a simple function for file download:
function show_download($data, $name, $type = "unknown/unknown") {
header('Content-Type: ' . $type);
header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Content-Disposition: attachment; filename="' . $name . '"');
header('Content-Length: ' . strlen($data));
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
print $data;
exit();
}
You can create a script that exports a CSV file like this :
header('Content-type: text/csv');
header("Content-Disposition: attachment; filename=clients_" . date("Ymd") . ".csv");
//Open PHP output stream
$fd = fopen('php://output', 'w');
$tab = array();
//get your results from your database
foreach ($results as $res)
$tab[] = array($res->Client_Name, $res->Client_Email);
foreach ($tab as $val)
fputcsv($fd, $val);
fclose($fd);

Categories