append Indian currency symbol after export excel sheet using PhpOffice PhpSpreadsheet? - php

I am working on "export to excel" sheet functionality using "PhpOffice\PhpSpreadsheet" library, till export to excel sheet working fine but My Problem here is that I have a total amount column where I have to add Indian currency symbol. I searched for a solution but no luck yet.
My Code:
require_once('../vendor/autoload.php');
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$objPHPSpreadSheet = new Spreadsheet();
$sheet = $objPHPSpreadSheet->getActiveSheet();
$results=getsalesReport($data);
$sheet->setCellValue('A1', 'title1');
$sheet->setCellValue('B1', 'title2');
$sheet->setCellValue('C1', 'title3');
$rowCount = 2;
if(isset($results) && !empty($results)){
foreach ($results as $key => $val) {
$total_amount = '₹'.$val['TotalAmount']; // I added '₹' for INR currency symbol, its working fine in HTML
$sheet->setCellValue('A'.$rowCount, $val['my_val1']);
$sheet->setCellValue('B'.$rowCount, $val['my_val2']);
$sheet->setCellValue('C'.$rowCount, $total_amount);
$rowCount++;
}
}
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename=sales_report.xlsx');
header('Cache-Control: max-age=0');
$writer = new Xlsx($objPHPSpreadSheet);
$writer->save("php://output");
How to add Indian currency symbol to total_amount cell in Excel sheet? Hope someone helps. Thanks.

Related

Create Dataset/Array for VLOOKUP Using PHPSpreadsheet

I have a export.php file with a goal of setting data validation with a VLOOKUP function off of that. However, it seems I can't find anything in the Recipes that actually seem to support this. I thought I found something but it doesn't seem to work, or at least, it doesn't work how I'd like.
Here is my simplified code:
require_once 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$i = 3;
foreach ($_POST['foo'] as $key => $el)
{
$sheet->setCellValue('D'. $i, '=VLOOKUP(C'. $i .',array,2,0)');
$i++;
}
# Column A = labels
# Column B = value
# create range
$spreadsheet->addNamedRange(new \PhpOffice\PhpSpreadsheet\NamedRange('array', $spreadsheet->getActiveSheet(), 'A'));
$spreadsheet->addNamedRange(new \PhpOffice\PhpSpreadsheet\NamedRange('array', $spreadsheet->getActiveSheet(), 'B'));
# redirect browser output -> php://output (download)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="hello.xlsx"');
header('Cache-Control: max-age=0');
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
However, this doesn't work - the cell ranges fatal error as you can't select a column to add to the range.
How do I create a dataset for VLOOKUP using PHPSpreadsheet?
Thanks
The answer is to not use a dataset as such, but use a cell range:
$lastValueCell = 84; # this is dynamically got, but no value in showing how
$output[$partNum][3] = '=VLOOKUP(C'. $x .',Formulas!A$1:B$'. $lastValueCell .',2,0)';
# then append to spreadsheet using ->setCellValue()
VLOOKUP now works on export

Issue using formula on PHPExcel (Excel2007)

When I try to set the value of an cell with a formula, e.g.: setCellValue('C1', '=A1+B1'), the generated file don't have the calculated value for the cells.
I have the following script:
<?php
require_once '../vendor/autoload.php';
date_default_timezone_set('America/Sao_Paulo');
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setCellValue('A1', 5)
->setCellValue('B1', 10)
->setCellValue('C1', '=A1+B1');
echo $objPHPExcel->getActiveSheet()->getCell('C1')->getCalculatedValue() . PHP_EOL;
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('a.xlsx');
When I open a.xlsx with libreoffice, the cell C1 shows the string "0". The odd thing is that when I click the cell it actually shows "=A1+B1", but not the final result.
How do I get PHPExcel to work with formulas properly?
I had the same problem with LibreOffice 5.0.5.2.
Changing the following option in LibreOffice Calc worked for me:
Go to Tools/Options.../LibreOffice Calc/Formula
In section "Recalculation on file load", "Excel 2007 and newer", change the value to "Always recalculate"
Found on
https://ask.libreoffice.org/en/question/12165/calc-auto-recalc-does-not-work/

PHPExcel removes Data Validation Option of Excel sheet after editing existing Excel Sheet

I am using PHPExcel for editing existing excel sheets.
I had already set up a Data Validation method in my excel sheet as below.
When i edit this excel using PHPExcel, this Excel Specific Data Validation vanishes.
Can anyone help me to overcome this issue. I need to edit the excel without changing its functionality.
My PHP code:
//load existing template..
$objPHPExcel = PHPExcel_IOFactory::load('www/PHPExcelReader/Excel_Uploads/sample.xls');
// Set document properties
$objPHPExcel->getProperties()->setCreator("Logic Item")
->setLastModifiedBy("Logic")
->setTitle("List");
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('AZ1', $combination);
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$file_name='sample.xls';
$objWriter->save($file_name);
echo "Excel is ready to download now...";
From spreadsheet files that I've just created with data validation on cell A1 applying values from a list in $G1:$G4 and the following code:
$inputFileType = 'Excel5';
$inputFileName = './15datavalidationUnpopulated.xls';
$outputFileType = 'Excel5';
$outputFileName = './15datavalidationPopulated.xls';
$objPHPExcelReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objPHPExcelReader->load($inputFileName);
$objPHPExcel->getActiveSheet()->setCellValue('G1', "India")
->setCellValue('G2', "America")
->setCellValue('G3', "China")
->setCellValue('G4', "Russia");
$objPHPExcelWriter = PHPExcel_IOFactory::createWriter($objPHPExcel,$outputFileType);
$objPHPExcel = $objPHPExcelWriter->save($outputFileName);
works with both .xls and .xlsx files, showing India, America, China and Russia in the data validation dropdown list for cell A1

PHPExcel - How to make part of the text bold

How do you create a bold cell value using PHPExcel? I know I can use \n to add a carriage return within the text, but is there some kind of way to bold part of cell value? I also have tried using html formatting such as <b> or <strong> but it did not work.
You can bold part of the text in a cell using rich text formatting, as described in section 4.6.37 of the developer documentation.
$objRichText = new PHPExcel_RichText();
$objRichText->createText('This text is ');
$objBold = $objRichText->createTextRun('bold');
$objBold->getFont()->setBold(true);
$objRichText->createText(' within the cell.');
$objPHPExcel->getActiveSheet()->getCell('A18')->setValue($objRichText);
Yes you can bold a cell's value with the following code:
$workbook = new PHPExcel;
$sheet = $workbook->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World');
$styleArray = array(
'font' => array(
'bold' => true
)
);
$sheet->getStyle('A1')->applyFromArray($styleArray);
$writer = new PHPExcel_Writer_Excel5($workbook);
header('Content-type: application/vnd.ms-excel');
$writer->save('php://output');
Hope this helps.
Source
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Hello')
->setCellValue('B1', 'world!')
->setCellValue('C1', 'Hello')
->setCellValue('D1', 'world!');
for single cell use:
$objPHPExcel->getActiveSheet()->getStyle("A1")->getFont()->setBold(true);
for multiple cells use:
$objPHPExcel->getActiveSheet()->getStyle("A1:D1")->getFont()->setBold(true);
You can use the HTML helper class in PHPExcel to bold text.
$htmlHelper = new \PHPExcel_Helper_HTML();
$html = "<b> Bold Text!! </b>";
$rich_text = $htmlHelper->toRichTextObject($html);
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $rich_text);
$objPHPExcel->getActiveSheet()->getStyle('1:1')->getFont()->setBold(true);

php_excel07- How to make grow the height of cell based on cell data(xls)

In my application i need to export to xls file in a predefined format.
so I just integrated php_excel2007. I am using one template with a predefined format.
The problem here is the cell data may change dynamically. if data is much bigger than cell height then data is collapsing.
So is ther anyway to increase the height of cell based on content of the cell(in XLX not xlsx)?
The only way is as described in this answer to your previous question on this topic: setting the row height to autofit, and the cell alignment to wrap. This should work the same way, whether you use the Excel5 Writer or the Excel2007 Writer.
$objPHPExcel = new PHPExcel();
// Set some long string values in some cells
$objPHPExcel->getActiveSheet()->getCell('A1')->setValue("This is a large block of text,\ncomprising several lines,\nthat will be set to autofit.");
$objPHPExcel->getActiveSheet()->getCell('A2')->setValue("This is a large block of text that will NOT be set to autofit.");
$objPHPExcel->getActiveSheet()->getCell('B1')->setValue("This is another large block of text without any line breaks, that will be set to autofit.");
$objPHPExcel->getActiveSheet()->getCell('A3')->setValue("This is another large block of text,\ncomprising several lines,\nthat will be set to autofit.");
$objPHPExcel->getActiveSheet()->getCell('A4')->setValue("This is another large block of text without any line breaks, that will be set to autofit but not wrap.");
// Fix the column width to a reasonable size
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(30);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(30);
// Set text wrap for cells A1 and B1. This forces the text to wrap, but doesn't adjust the height of the row
$objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('B1')->getAlignment()->setWrapText(true);
// Set rows 1, 3 and 4 to autofit the height to the size of text
$objPHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(-1);
$objPHPExcel->getActiveSheet()->getRowDimension(3)->setRowHeight(-1);
$objPHPExcel->getActiveSheet()->getRowDimension(4)->setRowHeight(-1);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('testAutoHeight.xls');
EDIT
Added comments to the code sample to explain what each called method actually does
setRowHeight to -1 for make auto height (based on cell data)
// auto-size on row 1
$objWorksheet->getRowDimension('1')->setRowHeight(-1);
<?php
error_reporting(E_ALL);
require_once ROOT.'/PHPExcel.php';
function down($details)
{
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
$objReader = PHPExcel_IOFactory::createReader('Excel5');
$objPHPExcel = $objReader->load(ROOT."/templates/project_report1.xls");
// Set properties
$p_i=5;$alpa="B";$row_no=5;$mil="";$d_cel="B";
$objPHPExcel->setActiveSheetIndex()
->setCellValue('K1', $details['report_details']['cur_time']);
$objPHPExcel->setActiveSheetIndex()
->setCellValue('C2', 'REPORT START DATE:'.$details['report_details']['start_date'])
->setCellValue('H2', $details['report_details']['details'])
->setCellValue('C3', 'SHOWING:'.$details['report_details']['showing']);
foreach($details as $p_name=>$date){
//thisis to display date at the top
foreach($date as $p1=>$m_name1){
$objPHPExcel->setActiveSheetIndex(0)->setCellValue($d_cel.'4', $p1);$d_cel++;//to display date in the top
}
break;
}
foreach($details as $p_name=>$date){
if($p_name=="report_details")break;
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.$p_i, $p_name);
$objPHPExcel->getActiveSheet(0)->duplicateStyle( $objPHPExcel->getActiveSheet()->getStyle('A5'), 'A'.$p_i );
$objPHPExcel->setActiveSheetIndex(0)->getStyle('A'.$p_i)->getAlignment()->setWrapText(true);
foreach($date as $p=>$m_name){
$mil=$tic=$st=" ";
foreach($m_name as $name=>$val){
if($name=="milestone")
foreach($val as $in_det=>$det){
if($det && isset($det['start_date']))
$mil.=$det['name']."\n".$det['start_date']."\n";
else
$mil.=$det['name'];
}
if($name=="ticket")
foreach($val as $in_det=>$det){
if($det)
$tic.=$det['name']." ".$det['start_date']."\n";
}
if($name=="task")
foreach($val as $in_det=>$det){
if($det)
$st.=$det['name']." ".$det['start_date']."\n";
}
}
$summary=$mil.$tic.$st;
$objPHPExcel->getActiveSheet(0)->duplicateStyle( $objPHPExcel->getActiveSheet()->getStyle('B5'), $alpa.$p_i );
$objPHPExcel->getActiveSheet(0)->getRowDimension($p_i)->setRowHeight();
$objPHPExcel->getActiveSheet(0)->getStyle('A'.$p_i.':'.'M'.$p_i)->getAlignment()->setWrapText(true);
$objPHPExcel->setActiveSheetIndex(0)->getStyle($alpa.$p_i)->getFont()->setSize(5);
$objPHPExcel->setActiveSheetIndex(0)->setCellValue($alpa.$p_i, $summary);
$alpa++;
}
$alpa="B";
$p_i++;
}
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setTitle('Report');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="project_report.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
}
?>

Categories