I am trying to make cells in first row are bold.
This is the method I have created for that purpose.
function ExportToExcel($tittles,$excel_name)
{
$objPHPExcel = new PHPExcel();
$objRichText = new PHPExcel_RichText();
// Set properties
$objPHPExcel->getProperties()->setCreator("SAMPLE1");
$objPHPExcel->getProperties()->setLastModifiedBy("SAMPLE1");
$objPHPExcel->getProperties()->setTitle("SAMPLE1");
$objPHPExcel->getProperties()->setSubject("SAMPLE1");
$objPHPExcel->getProperties()->setDescription("SAMPLE1");
// Add some data
$objPHPExcel->setActiveSheetIndex(0);
$letters = range('A','Z');
$count =0;
$cell_name="";
foreach($tittles as $tittle)
{
$cell_name = $letters[$count]."1";
$count++;
$value = $tittle;
$objPHPExcel->getActiveSheet()->SetCellValue($cell_name, $value);
// Make bold cells
$objPHPExcel->getActiveSheet()->getStyle($cell_name)->getFont()->setBold(true);
}
// Save Excel 2007 file
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
//$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
$objWriter->save($excel_name.".xlsx");
}
The problem is in output excel file the cells are not bold.
Try this for range of cells:
$from = "A1"; // or any value
$to = "B5"; // or any value
$objPHPExcel->getActiveSheet()->getStyle("$from:$to")->getFont()->setBold( true );
or single cell
$cell_name = "A1";
$objPHPExcel->getActiveSheet()->getStyle( $cell_name )->getFont()->setBold( true );
Try this
$objPHPExcel->getActiveSheet()->getStyle('A1:D1')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('1:1')->getFont()->setBold(true);
That way you get the complete first row
Assuming headers are on the first row of the sheet starting at A1, and you know how many of them there are, this was my solution:
$header = array(
'Header 1',
'Header 2'
);
$objPHPExcel = new PHPExcel();
$objPHPExcelSheet = $objPHPExcel->getSheet(0);
$objPHPExcelSheet->fromArray($header, NULL);
$first_letter = PHPExcel_Cell::stringFromColumnIndex(0);
$last_letter = PHPExcel_Cell::stringFromColumnIndex(count($header)-1);
$header_range = "{$first_letter}1:{$last_letter}1";
$objPHPExcelSheet->getStyle($header_range)->getFont()->setBold(true);
Use this:
$sheet->getStyle('A1:'.$sheet->getHighestColumn().'1')->getFont()->setBold(true);
These are some tips to make your cells Bold, Big font, Italic
Let's say I have columns from A to L
A1 - is your starting cell
L1 - is your last cell
$objPHPExcel->getActiveSheet()->getStyle('A1:L1')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('A1:L1')->getFont()->setSize(16);
$objPHPExcel->getActiveSheet()->getStyle('A1:L1')->getFont()->setItalic(true);
$objPHPExcel->getActiveSheet()->getStyle("A1:".$objPHPExcel->getActiveSheet()->getHighestDataColumn()."1")->getFont()->setBold(true);
I found this to be a working solution, you can replace the two instances of 1 with the row number. The HighestDataColumn function returns for example C or Z, it gives you the last/highest column that's in the sheet containing any data. There is also getHighestColumn(), that one would include cells that are empty but have styling or are part of other functionality.
This iterates through a variable number of columns of a particular row, which in this case is the 1st row:
$rownumber = 1;
$row = $this->objPHPExcel->getActiveSheet()->getRowIterator($rownumber)->current();
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
foreach ($cellIterator as $cell) {
$cell->getStyle()->getFont()->setBold(true);
}
The simple way to make bold headers:
$row = 1;
foreach($tittles as $index => $tittle) {
$worksheet->getStyleByColumnAndRow($index + 1, $row)->getFont()->setBold(true);
$worksheet->setCellValueByColumnAndRow($index + 1, $row, $tittle);
}
Try this
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
->setLastModifiedBy("Maarten Balliauw")
->setTitle("Office 2007 XLSX Test Document")
->setSubject("Office 2007 XLSX Test Document")
->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
->setKeywords("office 2007 openxml php")
->setCategory("Test result file");
$objPHPExcel->setActiveSheetIndex(0);
$sheet = $objPHPExcel->getActiveSheet();
$sheet->setCellValue('A1', 'No');
$sheet->setCellValue('B1', 'Job ID');
$sheet->setCellValue('C1', 'Job completed Date');
$sheet->setCellValue('D1', 'Job Archived Date');
$styleArray = array(
'font' => array(
'bold' => true
)
);
$sheet->getStyle('A1')->applyFromArray($styleArray);
$sheet->getStyle('B1')->applyFromArray($styleArray);
$sheet->getStyle('C1')->applyFromArray($styleArray);
$sheet->getStyle('D1')->applyFromArray($styleArray);
$sheet->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 1);
This is give me output like below link.(https://www.screencast.com/t/ZkKFHbDq1le)
You can try
$objPHPExcel->getActiveSheet()->getStyle(1)->getFont()->setBold(true);
Related
I'v been struggling for days now with this issue.
I have an xls file, containing multiple sheets, with functions on it.
What i'm trying to do is to insert values at the first sheet, and then retrieve the result from the second one, but the result i'm getting is 0.
This is the code i'v written
$fileType = 'Excel5';
$fileName = storage_path().'/penssion_simulator_file/test2.xls';
// Read the file
$objReader = PHPExcel_IOFactory::createReader($fileType);
$objReader->setReadDataOnly(true);
echo "Start loading file:</br>";
echo date('H:i:s d/m/Y')."</br>";
$objPHPExcel = $objReader->load($fileName);
echo "End of loading file:</br>";
echo date('H:i:s d/m/Y')."</br>";
PHPExcel_Calculation::getInstance($objPHPExcel)->disableCalculationCache();
PHPExcel_Calculation::getInstance($objPHPExcel)->clearCalculationCache();
echo "Start setting values to file:</br>";
echo date('H:i:s d/m/Y')."</br>";
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('B7', (string)date('d/m/Y'))
->setCellValue('B8', (string)'30/05/1984')
->setCellValue('B9', (string)'01/05/2013')
->setCellValue('B10', (integer)20000)
->setCellValue('B11', (string)'ללא בן זוג וילדים (לצורכי ביטוח)')
->setCellValue('B12', (float)5.5)
->setCellValue('B13', (float)6.0)
->setCellValue('B14', (float)8.33)
->setCellValue('B15', '-')
->setCellValue('B16', (string)'גבר')
->setCellValue('B17', (integer)0)
->setCellValue('B18', (integer)0)
->setCellValue('B19', (string)'עתיר חיסכון')
->setCellValue('B20', (float)6.0)
->setCellValue('B21', (float)0.25)
->setCellValue('B22', (integer)67)
->setCellValue('B23', (string)'כן')
->setCellValue('B24', (string)'לא');
echo "End of setting values to file:</br>";
echo date('H:i:s d/m/Y')."</br>";
$objWorksheet = $objPHPExcel->setActiveSheetIndex(1);
echo "Value of cell B6 on sheet 1: ".($objWorksheet->getCell('B6')->getCalculatedValue())."</br>";
// $value = $this->getCellValue($objWorksheet,'B3');
// echo "</br>This is the value og cell B3: ".$value."</br>";
// PHPExcel_Calculation::getInstance()->writeDebugLog = true;
// $this->testFormula($objWorksheet,'B3');
$objWorksheet = $objPHPExcel->setActiveSheetIndex(0);
echo "Value of cell B7 on sheet 0: ".($objPHPExcel->getActiveSheet()->getCell('B7')->getValue())."</br>";
echo date('H:i:s d/m/Y')."</br>";
// Change the file
die('FIN');
And those are the outputs that i'm printing:
Start loading file:
09:03:27 28/01/2015.
End of loading file:
09:04:26 28/01/2015.
Start setting values to file:
09:04:26 28/01/2015.
End of setting values to file:
09:04:26 28/01/2015
Value of cell B6 on sheet 1: 0
Value of cell B7 on sheet 0: 28/01/2015
09:04:30 28/01/2015
FIN
I'm using laravel as i mentioned at the header of this post, and the laravel-phpexcel package.
Appreciate your help!
I have array of data like:
$products = array(
array('path/to/image1', 'name1', 'description1'),
array('path/to/image2', 'name2', 'description2'),
array('path/to/image3', 'name3', 'description3'),
...
array('path/to/imageN', 'nameN', 'descriptionN'),
);
With this code I generate *.xlsx table:
foreach($products as $row) {
$c = 0;
foreach ($row as $cell) {
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($c, $r, $cell);
$c++;
}
$r++;
}
require_once 'Classes/PHPExcel/IOFactory.php';
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('/path/for/save');
And after that I get a table with path, name and descriptions. Please help me, because I can't get table where instead of pathes I will get images.
Setting a cell to contain 'path/to/image1' will do exactly that, set the cell to contain a string value of 'path/to/image1'.
You need to set images very specifically, as explained in the documentation and shown in the examples:
$objDrawing = new PHPExcel_Worksheet_Drawing();
$objDrawing->setName('Image');
$objDrawing->setPath('./path/to/image1.jpg');
$objDrawing->setCoordinates('B2');
$objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
You should also note that MS Excel does not store images in a cell. It stores images overlaying a cell, so the image may cover several cells
EDIT
If you need to convert numeric coordinates such as $row=3 and $col=0 to a cell reference like A3:
$cellReference = PHPExcel_Cell::stringFromColumnIndex($col) . $row;
or
$cellReference = $objPHPExcel->getActiveSheet()
->getCellByColumnAndRow($col, $row)
->getCoordinate();
Code without merge
$objPHPExcel = new PHPExcel();
$sheet = $objPHPExcel->getActiveSheet();
$sheet->setCellValueByColumnAndRow(0, 1,
"test test test test test test test test");
$sheet->getColumnDimension('A')->setAutoSize(true);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save("test.xlsx");
Code with merge
$objPHPExcel = new PHPExcel();
$sheet = $objPHPExcel->getActiveSheet();
$sheet->setCellValueByColumnAndRow(0, 1,
"test test test test test test test test");
//this breaks the width calculation
$sheet->mergeCells('A1:B1');
$sheet->getColumnDimension('A')->setAutoSize(true);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save("test.xlsx");
As far as I understand, there is no standard way to set auto size for merged cells. Is there any workaround for this?
You could calculate the column widths before merging the cells using ->calculateColumnWidths(), and then ->setAutoSize(false) to make sure that they are not calculated again. The code could
look something like this:
// Set the data in the cells
$objPHPExcel->getActiveSheet()->fromArray($sheet, null, 'A1');
// Calculate the column widths
foreach(range('A', 'E') as $columnID) {
$objPHPExcel->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(true);
}
$objPHPExcel->getActiveSheet()->calculateColumnWidths();
// Set setAutoSize(false) so that the widths are not recalculated
foreach(range('A', 'E') as $columnID) {
$objPHPExcel->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(false);
}
// Merge cells
$objPHPExcel->getActiveSheet()->mergeCells("A1:A5");
i personnaly used the size of the value to adapt the size of the cell :
$value = $sheet->getCell('A1')->getValue();
$width = mb_strwidth ($value); //Return the width of the string
$sheet->getColumnDimension('A')->setWidth($width);
Beware if you have made a ->setAutoSize(true) on the column that you want to modify you need to put it at false before doing any modifications :
$sheet->getColumnDimension('A')->setAutoSize(false);
I have a excel file with two sheet:
Worksheet;
List- list of items which will display in Worksheet sheet as a list item.
Please see the below images:
I want to generate this using PHPExcel library. I have tried but not getting the expected results. See my below code :
$objPHPExcel = new PHPExcel();
// Set document properties
$objPHPExcel->getProperties()->setCreator("Soumya Biswas")
->setLastModifiedBy("Soumya Biswas")
->setTitle("Office 2007 XLSX Test Document")
->setSubject("Office 2007 XLSX Test Document")
->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
->setKeywords("office 2007 openxml php")
->setCategory("Test result file");
// Create a first sheet
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setCellValue('A5', "List");
// Set data validation
$objValidation = $objPHPExcel->getActiveSheet()->getCell('B5')->getDataValidation();
$objValidation->setType( PHPExcel_Cell_DataValidation::TYPE_LIST );
$objValidation->setErrorStyle( PHPExcel_Cell_DataValidation::STYLE_INFORMATION );
$objValidation->setAllowBlank(false);
$objValidation->setShowInputMessage(true);
$objValidation->setShowErrorMessage(true);
$objValidation->setShowDropDown(true);
$objValidation->setErrorTitle('Input error');
$objValidation->setError('Value is not in list.');
$objValidation->setPromptTitle('Pick from list');
$objValidation->setPrompt('Please pick a value from the drop-down list.');
$objValidation->setFormula1('"$List.$A$1:$A$10"'); // Make sure to put the list items between " and " !!!
$objPHPExcel->createSheet();
$objPHPExcel->setActiveSheetIndex(1);
$objPHPExcel->getActiveSheet()->setTitle('List');
for ($i = 1; $i <= 10; $i++) {
$objPHPExcel->getActiveSheet()->setCellValue("A{$i}", "List Item {$i}");
}
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="data-validation.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
I think the correct syntax for referencing ranges of cells in another sheet is:
List!$A$1:$A$10
So you should try:
$objValidation->setFormula1('List!$A$1:$A$10'); // tested it, worked for me
Got the idea from http://phpexcel.codeplex.com/discussions/320393:
->setFormula1("Worksheet!A1:{$endCell}1");// work....
Although this guy had another problem with using named ranges.
Background: I think with:
$objValidation->setFormula1('"$List.$A$1:$A$10"');
you're explicity using the given string between the quotation marks as the list value as explained here: here (where you probably got this snippet in the first place) or here.
But since you don't want to use fixed list items but dynamically referred ones, you should omit the double quotation marks.
I have 2 xls, i want to plot this information into one HTML Page.
Note: For assumption i mentioned as xls. actual xls positions are already in the database table. i will just render these position and plot into HTML Page.
include_once("Classes/PHPExcel/IOFactory.php");
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
//first excel file
$objPHPExcel->getActiveSheet()
->setCellValue('c5','10');
$objPHPExcel->getActiveSheet()
->setCellValue('c6','20');
$objPHPExcel->getActiveSheet()
->setCellValue('c7','30');
$objPHPExcel->getActiveSheet()
->setCellValue('c8','40');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'HTML');
//second excel file
$objPHPExcel->getActiveSheet()
->setCellValue('c5','50');
$objPHPExcel->getActiveSheet()
->setCellValue('c6','60');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'HTML');
$objWriter->save('combinedexcelpage.html');
I'm not going to go through a long explanation of why this doesn't work, because it would take too long to explain; but there are a couple of solutions that you could take to achieve what you want:
Option #1
An Excel workbook comprises one or more worksheets, so you could create each "file" as a separate worksheet, rather than a separate file.
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// First excel worksheet, (created when you instantiate a new PHPExcel object)
$objPHPExcel->getActiveSheet()
->setCellValue('c5','10');
$objPHPExcel->getActiveSheet()
->setCellValue('c6','20');
$objPHPExcel->getActiveSheet()
->setCellValue('c7','30');
$objPHPExcel->getActiveSheet()
->setCellValue('c8','40');
// Second excel worksheet
// Add new sheet, which should also set it as the new "active" sheet
$objPHPExcel->createSheet()
$objPHPExcel->getActiveSheet()
->setCellValue('c5','50');
$objPHPExcel->getActiveSheet()
->setCellValue('c6','60');
By default, the HTML Writer will only write a single worksheet (the first), but you can set it to write all sheets:
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'HTML');
$objWriter->writeAllSheets();
$objWriter->save('combinedexcelpage.html');
Option #2
The HTML Writer save() method will always generate a file stream (whether a filesystem file or php://output), but rather than using save(), you can call individual methods in the class to generate a string containing the formatted worksheet data, and build your own output from those "blocks".
$data = '';
// First excel file
$objPHPExcel1 = new PHPExcel();
$objPHPExcel1->getActiveSheet()
->setCellValue('c5','10');
$objPHPExcel1->getActiveSheet()
->setCellValue('c6','20');
$objPHPExcel1->getActiveSheet()
->setCellValue('c7','30');
$objPHPExcel1->getActiveSheet()
->setCellValue('c8','40');
$objWriter1 = PHPExcel_IOFactory::createWriter($objPHPExcel, 'HTML');
$objWriter1->generateStyles(false);
$data .= $objWriter1->generateHTMLHeader();
$data .= $objWriter1->generateSheetData();
// Second excel file
$objPHPExcel2 = new PHPExcel();
$objPHPExcel2->getActiveSheet()
->setCellValue('c5','50');
$objPHPExcel2->getActiveSheet()
->setCellValue('c6','60');
$objWriter2 = PHPExcel_IOFactory::createWriter($objPHPExcel2, 'HTML');
$objWriter2->generateStyles(false);
$data .= $objWriter2->generateSheetData();
$data .= $objWriter2->generateHTMLFooter();
file_put_contents('combinedexcelpage.html', $data);
Both of these options are described in section 6.8 of the developer documentation