I'm looking for a way to do the following:
$file = 'file.xls';
$input = '<tr><td>Some input</td></tr>';
if (!file_exists($file))
{
create_excel($file); //Create the sheet
input_titles($file); //Add column titles
}
else
{
add_input_to_the_last_line($input);
}
Is there a library which can simply do the above?
You could use PHPExcel library:
Example Usage:
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$rowCount = 1;
while($row = mysql_fetch_array($result)){
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, <your_row_name>);
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, <your_row_name>);
$rowCount++;
}
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter->save('your_file_name.xlsx');
Related
I use PHPspreadsheet to covert a xlsx file to a csv file.
In column "I" I have dates and times like [26-04-2019 07:57:35] how can I change this to [2019-04-26 07:57:35]?
I want to change this for uploading to MYSQL.
use \PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use \PhpOffice\PhpSpreadsheet\Writer\Csv;
$xls_file = "$file";
$reader = new Xlsx();
$spreadsheet = $reader->load($xls_file);
$loadedSheetNames = $spreadsheet->getSheetNames();
$writer = new Csv($spreadsheet);
foreach($loadedSheetNames as $sheetIndex => $loadedSheetName) {
$writer->setSheetIndex($sheetIndex);
$writer->save($loadedSheetName.'.csv');
}
You will need to loop through each row of each sheet and change column I to the format needed for MySQL.
foreach($loadedSheetNames as $sheetIndex => $loadedSheetName) {
$writer->setSheetIndex($sheetIndex);
$worksheet = $spreadsheet->getActiveSheet();
$highestRow = $worksheet->getHighestRow(); // e.g. 10
for ($row = 1; $row <= $highestRow; ++$row) {
$datenow = $worksheet->getCellByColumnAndRow(9,$row)->getValue();
$worksheet->setCellValue('I' . $row,date('Y-m-d h:i:s',strtotime($datenow)));
} // end of for loop through the sheet
$writer->save($loadedSheetName.'.csv');
}
I am trying to parse an Excel file. I am able to get the contents of individual cells of the excel. I am unable to add the data I got from the cell into an array.
function parseExcel($inputFileName){
$mh = new MainHandler;
// Read your Excel workbook
try {
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
}catch(Exception $e) {
die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
$Arr = array();
// Get worksheet dimensions
$sheet = $objPHPExcel->getActiveSheet();
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
for ($row = 1; $row <= $highestRow; $row++){
$myArray = array();
for($col = 'A' ; $col <= $highestColumn ; $col++){
$a = $sheet->getCell($col.$row);
// echo "\n".$a;
$myArray[] = $a;
}
// $Arr[] = $myArray;
echo json_encode($myArray);
}
// echo json_encode($Arr);
}
The output i get is
[{},{},{},{},{}][{},{},{},{},{}][{},{},{},{},{}]
What should be done to get the populated array as output?
I am exporting mysql data to an excel file using phpexcel library. The code works fine. But the excel file created doesn't have column name. I want to fetch them as well. Is there any built-in method for it? What adjustment do i need to make my code? Here is my current working code:
<?php
require_once 'PHPExcel/classes/PHPExcel.php';
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$rowcount = 1;
while($row = mysqli_fetch_array($rs))
{
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowcount, $row['id']);
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowcount, $row['title']);
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowcount, $row['date']);
$rowcount++;
}
$filename = "backup-" . date("h.i.s.d-m-Y") . ".xls";
header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment; filename=" . $filename);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
?>
Use mysqli_fetch_fields for getting the field names.
I have edited your code and add column names in code. It might help you.
<?php
require_once 'PHPExcel/classes/PHPExcel.php';
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$rowcount = 1;
$fieldinfo=mysqli_fetch_fields($rs);
foreach ($fieldinfo as $val)
{
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowcount, $val->id);
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowcount, $val->title);
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowcount, $val->date);
}
$rowcount = 2;
while($row = mysqli_fetch_array($rs))
{
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowcount, $row['id']);
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowcount, $row['title']);
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowcount, $row['date']);
$rowcount++;
}
$filename = "backup-" . date("h.i.s.d-m-Y") . ".xls";
header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment; filename=" . $filename);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
?>
If i am right , you were searching for something like below
Insert Title Row
$f=0;
$fChar='A';
while($f<mysql_num_fields($rs)){
$objPHPExcel->getActiveSheet()->setCellValue($fChar.'1', mysql_fetch_field($rs,$f++)->name);
$objPHPExcel->getActiveSheet()->getStyle($fChar.'1')->applyFromArray(
array(
'fill' => array(
'type' => PHPExcel_Style_Fill::FILL_SOLID,
'color' => array('rgb'=>'E1E0F7'),
),
'font' => array(
'bold' => true,
)
)
);
$fChar++;
}
Now insert values
$fC=2;
while($row=mysql_fetch_array($rs,MYSQL_BOTH)){
$fChar='A';
$f=0;
while($f<mysql_num_fields($rs)){
$objPHPExcel->getActiveSheet()->setCellValue($fChar++.''.$fC, $row[$f++]);
}
$fC++;
}
You need to change the code something like below to show the column name and data
//this is for showing the column name
$q = mysql_query("SHOW COLUMNS FROM table_name");
if (mysql_num_rows($q) > 0) {
while ($row_q = mysql_fetch_assoc($q)) {
$col='A';
$objPHPExcel->getActiveSheet()->SetCellValue($col.$rowcount, $row_q['Field']);
$col++;
}
$rowcount++;
}
//this is for showing coulmn data based in results
while($row_data1 = mysql_fetch_assoc($rs)){
$col=0;
foreach($row_data1 as $key=>$value){
$objPHPExcel->getActiveSheet()->SetCellValueByColumnAndRow($col, $rowcount, $value);
$col++;
}
$rowcount++;
}
I want to export data from orangehrm attendance report to csv file by using phpexcel but I don't know how to do it:
$records = array();
foreach ($empRecords as $employee) {
$hasRecords = false;
$attendanceRecords = $employee->getAttendanceRecord();
$total = 0;
foreach ($attendanceRecords as $attendance) {
$from = $this->date . " " . "00:" . "00:" . "00";
$end = $this->date2 . " " . "23:" . "59:" . "59";
if (strtotime($attendance->getPunchInUserTime()) >= strtotime($from) && strtotime($attendance->getPunchInUserTime()) <= strtotime($end)) {
if ($attendance->getPunchOutUtcTime()) {
$total = $total + round((strtotime($attendance->getPunchOutUtcTime()) - strtotime($attendance->getPunchInUtcTime())) / 3600, 2);
}
$records[] = $attendance;
$hasRecords = true;
}
}
if ($hasRecords) {
$last = end($records);
$last->setTotal($total);
} else {
$attendance = new AttendanceRecord();
$attendance->setEmployee($employee);
$attendance->setTotal('---');
$records[] = $attendance;
}
}
// Algorithm to export filtered/ searched data
if($post['export'] == '1'){
//require_once 'PHPExcel/Reader/Excel15.php';
//require_once 'PHPExcel/Reader/Excel2007.php';
require_once 'PHPExcel/IOFactory.php';
require_once 'PHPExcel.php';
$objPHPExcel = new PHPExcel();
$objActSheet = $objPHPExcel->getActiveSheet();
$objActSheet->setTitle('Staff AttendanceRecord');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('Attendance.xslx');
}
csvYou didn't mention the structure of your array ($records)..
Hope it's like
$records[] = array('EMPLOYEE'=>'name1','TOTAL'=>'total1'),array('EMPLOYEE'=>'name2','TOTAL'=>'total2');
Please try code below
if($post['export'] == '1')
{
if(!empty($records))
{
require_once 'PHPExcel/IOFactory.php';
require_once 'PHPExcel.php';
$objPHPExcel = new PHPExcel(); // Create new PHPExcel object
$column = A;
$headings=array('EMPLOYEE','TOTAL');
for($c=0;$c<count($headings);$c++)
{
$objPHPExcel->getActiveSheet()->setCellValue($column.'1',$headings[$c]); // Add column heading data
if($c==count($headings)-1)
{
break;// Need to terminate the loop when coumn letter reachs max
}
$column++;
}
while (list($key,$value) = each($records))
{
$objPHPExcel->getActiveSheet()->setCellValue('A'.$j,$value['EMPLOYEE']);
$objPHPExcel->getActiveSheet()->setCellValue('B'.$j,$value['TOTAL']);
$j++;
}
$objActSheet->setTitle('Staff AttendanceRecord');
$workbookName = 'Attendance';
// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$workbookName.'.csv"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
}
}
I'm having a situation, that i get one template in excel, where i just want to add the information of my database, but when i do that put the template blank just with the information. Please tell me what i'm doing wrong. I'm new to PHPExcel
MODEL:
public function export_excel($id)
{
require_once APPPATH.'Classes/PHPExcel.php';
$queryResult = $this->get($id);
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$result = mysql_query($queryResult[0]['query_sql']) or die (mysql_error());
//echo "SQL = ", $queryResult[0]['query_sql']; // pass query allright
// Initialise the Excel row number
$rowCount = $queryResult[0]['start_line'];
//start of printing column names as names of MySQL fields
$column = $queryResult[0]['title_cell'];
for ($i = 1; $i < mysql_num_fields($result); $i++)
{
$objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount, mysql_field_name($result,$i));
$column++;
}
//end of adding column names
//start while loop to get data
$rowCount = $rowCount+1;
while($row = mysql_fetch_row($result))
{
$column = 'B';
for($j=1; $j<mysql_num_fields($result);$j++)
{
if(!isset($row[$j]))
$value = NULL;
elseif ($row[$j] != "")
$value = strip_tags($row[$j]);
else
$value = "";
$objPHPExcel->getActiveSheet()->getColumnDimension($column)->setAutoSize(true);
$objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount, $value);
$column++;
}
$rowCount++;
}
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
//$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
// Write the Excel file to filename some_excel_file.xlsx in the current directory
if($queryResult[0]['template_location'] !=null){
$objWriter->save($queryResult[0]['template_location']);
//echo date('H:i:s') , " Write to Excel2007 format" , EOL;
return 1;
}
else{
$objWriter->save('php://output');
//echo date('H:i:s') , " Write to Excel2007 format" , EOL;
return 1;
}
return null;
}
You're not reading the template, you need to read first from the template and write into:
something like this:
$objReader = PHPExcel_IOFactory::createReader('Excel5');
$objPHPExcel = $objReader->load($queryResult[0]['template_location']);
i hope it helped