with phpexcel how do I set column formats? - php

I am using an existing Excel file, with the first row containing plain text, to be used later as template. I then changed a few of the column formats to currency, accounting, date...e.t.c. Now I am loading in this file in phpExcel and populating data from my database to this file and saving it with a new name. But on the saved file, all cells in the newly created rows seem to be marked general, though the original plain text row still seems to have the correct format assigned.
My Code:
$xl_tmplt = ((isset($_REQUEST['excel_template']) && $_REQUEST['excel_template'] != "")
? $_REQUEST['excel_template']
: "report_tab1.xlsx");
require_once 'includes/classes/PHPExcel/PHPExcel.php';
$cacheMethod = PHPExcel_CachedObjectStorageFactory:: cache_to_phpTemp;
$cacheSettings = array('memoryCacheSize' => '8MB');
PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
$tmp_workbook = PHPExcel_IOFactory::load($tmp_folder_path . '/templates/' . $xl_tmplt);
$tmp_workbook->setActiveSheetIndex(0);
$sheet = $tmp_workbook->getActiveSheet();
$sheet->fromArray($arr, '', 'A2');
$objWriter = PHPExcel_IOFactory::createWriter($tmp_workbook, 'Excel2007');
$objWriter->save($tmp_folder_path . "output/$filename");
$result['type'] = "success";
$result['msg'] = "The file was successfully created.";
Any idea how I can load in an excel file with predefined column formats and use it to generate a new excel? Or change/set the format of a column or cell range during generation?
PS: I am not too good with excel so I might have set the column format in the wrong way. basically I clicked on the column letter which selects the column, and then changed the format in the dropdown above. If this is wrong, please let me know.

Please check below link for example of setting Row and Cell style
http://phpexcel.codeplex.com/workitem/7333
UPDATE:
For formatting Numbers, Text, Date and Currency, please check below link
PHPExcel Formatting

Related

Convert Entire Value in Spesific Column Date From Excel Using PHPSpreadSheet

I have xlsx tables and I use PhpSpreadsheet to parse them. One Column is date format. The problem is that PhpSpreadsheet returns the values from date-formatted cells in an unspecified format:
2-Jan-19 (in Excel) and 43467 (After Exporting)
And I need to save entire tables exactly as they look like in Excel Format, like "2-Jan-19" not "43467"
I've been read
Retrieve Date From Table Cell,
But it can't solve my problem
Below is the code I have right now:
$spreadsheet = $reader->load($_FILES['berkas_excel']['tmp_name']);
$sheetData = $spreadsheet->getSheet(0)->toArray();
echo count($sheetData);
for($i = 3;$i < count($sheetData) ;$i++)
{
$kode = $sheetData[$i]['0'];
$tgl = $sheetData[$i]['1']; //This is where the Date Column
$shift_rec = $sheetData[$i]['2'];
$grup = $sheetData[$i]['3'];
$pekan = $sheetData[$i]['4'];
$bulan = $sheetData[$i]['5'];
}
I hope somebody can help me to get "2-Jan-19" as the result, so I can insert it into my DB after that,
Thanks to anyone who willing to answer/help my problem right now

PHP Excel isDateTime not working

I'd like some help to solve a problem with the PHP Excel library to import a cell data.
In my script I need to check if a cell is formatted as a date, using "PHPExcel_Shared_Date::isDateTime".
For some date cells, the format is flagged by MS Excel like this :
"Date formats that begin with an asterisk (*) respond to changes in regional date and time settings that are specified for the Operating System."
And for thoses cells, the test PHPExcel_Shared_Date::isDateTime fails, I obtain this :
$reader = PHPExcel_IOFactory::createReaderForFile($filepath);
$objexcel = $reader->load($filepath);
$cell = $objexcel->getSheet()->getCell('A2');
var_dump(PHPExcel_Shared_Date::isDateTime($cell)); // return false
echo $cell->getFormattedValue(); // return timestamp : 43466
When I convert my xlsx file in xls file or when I give another date format to my cell, it works, I obtain this :
$reader = PHPExcel_IOFactory::createReaderForFile($filepath);
$objexcel = $reader->load($filepath);
$cell = $objexcel->getSheet()->getCell('A2');
var_dump(PHPExcel_Shared_Date::isDateTime($cell)); // return true
echo $cell->getFormattedValue(); // return 2019-01-01
The "setReadDataOnly" is still at false for my reader.
Does someone has any idea to fix it ?
(I precise that i'm in France, and we write dates at format 'd/m/Y')
Thanks in advance for helping me.

I cannot format a row copied from one sheet to another as string in PHPExcel

I am having trouble when copying a row from one sheet to another in the same Excel file. Some cells contain large numbers, which creates a problem when copying them because they get rounded up and I don't want that to happen. I heard I can overcome that problem by pasting them as a string, as shown here. But no matter what I do the values of the cells are still formatted as numbers, which messes up the whole process.
Can you please help me? Thanks!
Excerpt code:
//por ultimo lo demas
for($i=2; $i<$rowCount;$i++){
$order = $objPHPExcel->getActiveSheet()->getCell('B'.$i)->getValue();
if($order != 'xxx'){
$cellValues = $objPHPExcel->getActiveSheet()->rangeToArray("A$i:AP$i", null, true, true, false);
$objPHPExcel->setActiveSheetIndex(1);
PHPExcel_Cell::setValueBinder(new PHPExcel_Cell_MyColumnValueBinder($cellValues));
$objPHPExcel->getActiveSheet()->fromArray($cellValues, null, 'A'.$newRow);
$newRow++;
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setCellValue('B'.$i, 'xxx');
}
}

How to read subscript/superscript/new line using PHPExcel library when importing excel file to PHP and storing in MySQL

I am having trouble saving the excel file in mysql database, It contains enter(new line) inside a cell and symbols & superscripts as well. But it stores as plain text only.
$objReader = new PHPExcel_Reader_Excel5();
$objPHPExcel = $objReader->load($inputFileName);
$sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
then i read some data and use
reset($sheetData);
to reset the pointer.
and again use foreach() loop, to add the data into an array and insert that array to mysql table. Does any of these steps remove pre-formatting (superscript/subscript/new line inside a cell and bold/italics)? and How can I put the data in the table exactly as in the excel?
Edit: I am using v1.8 of PHPExcel, v5.4 of PHP and MySQL v5.6
include APPPATH.'/spreadsheetreader/php-excel-reader/excel_reader2.php';
require(APPPATH.'/spreadsheetreader/SpreadsheetReader.php');
require(APPPATH.'/spreadsheetreader/SpreadsheetReader_CSV.php');
require(APPPATH.'/spreadsheetreader/SpreadsheetReader_ODS.php');
require(APPPATH.'/spreadsheetreader/SpreadsheetReader_XLS.php');
require(APPPATH.'/spreadsheetreader/SpreadsheetReader_XLSX.php');
class Dashboard extends REST_Controller
{
public function __construct()
{
parent:: __construct();
$this->load->library("PHPExcel");
}
public function dashboard_post()
{
$Reader = new SpreadsheetReader('./upload/'.$filename);
$totalSheet = count($Reader->sheets());
//print_r($totalSheet);exit;
// For Loop for all sheets
if($totalSheet>0)
{
for($i=0;$i<$totalSheet;$i++)
{
$Reader->ChangeSheet($i);
foreach ($Reader as $Row)
{
$data=array(
'your table column name'=>isset($Row[1]) ? $Row[1] : '',
'your table column name'=>isset($Row[2]) ? $Row[2] : '',
'your table column name'=>isset($Row[3]) ? $Row[3] : '',
'your table column name'=>isset($Row[4]) ? $Row[4] : '',);
}
The toArray() method is intended to provide a simple function to get the plain text from data cells in a spreadsheet; so all "formatting" of rich text (cells that contain different styles, colours, newlines and font information for different parts of the cell content) is removed to provide that plain text.
If you want to access that style information, then you need to get the data from the individual cells yourself using the cell's getValue() method; so you'll need to write your own loop to do that for all cells in the sheet; and you'll need to decide how you're going to store things like superscripts or bold/italic/underline in your database, and parse rich-text cell data accordingly

PHPExcel: Combine 2 Excel files into 1 into the same worksheet

I have 2 excel files birds.xlsx and bees.xlsx both of which have the same number of columns and same type of column header. I've seen how PHPExcel does wonders with excel files but is there some way to combine 2 separate files into the same worksheet and saving it as a new file? The analogy that comes to mind is something like the SQL UNION command.
Something like:
// Load both spreadsheet files
$objPHPExcel1 = PHPExcel_IOFactory::load("birds.xlsx");
$objPHPExcel2 = PHPExcel_IOFactory::load("bees.xlsx");
// Find the last cell in the second spreadsheet
$findEndDataRow = $objPHPExcel2->getActiveSheet->getHighestRow();
$findEndDataColumn = $objPHPExcel2->getActiveSheet->getHighestColumn();
$findEndData = $findEndDataColumn . $findEndDataRow;
// Read all the data from second spreadsheet to a normal PHP array
// skipping the headers in row 1
$beeData = $objPHPExcel2->getActiveSheet->rangeToArray('A2:' . $findEndData);
// Identify the row in the first spreadsheet where we want to start
// adding merged bee data without overwriting any bird data
$appendStartRow = $objPHPExcel1->getActiveSheet->getHighestRow() + 1;
// Add bee data from the PHP array into the bird data
$objPHPExcel1->getActiveSheet->fromArray($beeData, null, 'A' . $appendStartRow);
// Save the spreadsheet with the merged data
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel1, 'Excel2007');
$objWriter->save(str_replace('animals.xlsx');

Categories