excel to json in php - php

I am just learning to code, i dont know much yet.
<!doctype>
<html>
<head>
</head>
<body>
<?php
require_once "Classes/PHPExcel.php";
$tmpfname = "tabula1.xlsx";
$excelReader = PHPExcel_IOFactory::createReaderForFile($tmpfname);
$excelObj = $excelReader->load($tmpfname);
$worksheet = $excelObj->getSheet(0);//
$lastRow = $worksheet->getHighestRow();
echo "<table>";
for ($row = 1; $row <= $lastRow; $row++) {
echo "<tr><td>";
echo $worksheet->getCell('A'.$row)->getValue();
echo "</td><td>";
echo $worksheet->getCell('B'.$row)->getValue();
echo "</td><tr>";
}
echo "</table>";
</body>
</html>
here's my code. I need to output the data in json from excel table. I have been searching for solution in youtube and google, but i have found nothing i understand so far. What should i write, what should i do? Also, i got this code from this forum and i edited it so it works for me. I would be very grateful if someone could help me with this <3

Try something like this, using your loop to create an array and the json_encode to convert it to a json string:
<!doctype>
<html>
<head>
</head>
<body>
<?php
require_once "Classes/PHPExcel.php";
$tmpfname = "tabula1.xlsx";
$excelReader = PHPExcel_IOFactory::createReaderForFile($tmpfname);
$excelObj = $excelReader->load($tmpfname);
$worksheet = $excelObj->getSheet(0);//
$lastRow = $worksheet->getHighestRow();
$data = [];
for ($row = 1; $row <= $lastRow; $row++) {
$data[] = [
'A' => $worksheet->getCell('A'.$row)->getValue(),
'B' => $worksheet->getCell('B'.$row)->getValue()
];
}
echo json_encode($data);
</body>
</html>

Only logic not tested
$result=array();
for ($row = 1; $row <= $lastRow; $row++)
{
array_push($result,array($worksheet->getCell('A'.$row)->getValue(),$worksheet->getCell('B'.$row)->getValue()));
}
echo json_encode($result);

https://github.com/PHPOffice/PhpSpreadsheet
<?php
require(DIR_SYSTEM . 'library/export_import/vendor/autoload.php');
$inputFileName = __DIR__ . '/1.xlsx';
$inputFileType = 'Xlsx';
/** Create a new Reader of the type defined in $inputFileType **/
$reader = PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
/** Advise the Reader that we only want to load cell data **/
$reader->setReadDataOnly(true);
/** Load $inputFileName to a Spreadsheet Object **/
$spreadsheet = $reader->load($inputFileName);
$sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
$worksheet = $spreadsheet->getSheet(0);//
// Get the highest row and column numbers referenced in the worksheet
$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);
$data = array();
for ($row = 1; $row <= $highestRow; $row++) {
$riga = array();
for ($col = 1; $col <= $highestColumnIndex; $col++) {
$riga[] = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
}
if (1 === $row) {
// Header row. Save it in "$keys".
$keys = $riga;
continue;
}
$data[] = array_combine($keys, $riga);
}
header('Content-Type: application/json');
print json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);

Related

How to read multiple xlsx files in a folder and put them into one array?

Tell me how to do it, I have a folder with xlsx files, with 2 arguments name and price
The task is that I need to pull out information from all files into one array.
Here is my code
<?php
$filelist = glob("prices/*.xlsx");
// $data = substr_replace($filelist, null, 0, 7);
// echo '<pre>';
// print_r($filelist);
// echo '<pre>';
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;
$myarr = array();
foreach($filelist as $value) {
$file = $value;
$reader = IOFactory::createReaderForFile($file);
$reader->setReadDataOnly(true);
// Читаем файл и записываем информацию в переменную
$spreadsheet = $reader->load($file);
// Так можно достать объект Cells, имеющий доступ к содержимому ячеек
$cells = $spreadsheet->getSheet(0)->getCellCollection();
// Далее перебираем все заполненные строки
for ($row = 2; $row <= $cells->getHighestRow(); $row++){
$array[$row]['name']=($cells->get('A'.$row))?$cells->get('A'.$row)->getValue():'';
$array[$row]['price']=($cells->get('B'.$row))?$cells->get('B'.$row)->getValue():'';
}
$myarr[] = $array;
}
echo '<pre>';
print_r($myarr);
echo '<pre>'
?>
The error is that the total number of products in xlsx files is somewhere around 500-600
and I get 1200 in the array
If I take out
$myarr[] = $array;
For a cycle, only 2 files are read.
You are overwriting the array in the inner loop on the second pass
$myarr = array();
foreach($filelist as $value) {
$file = $value;
$reader = IOFactory::createReaderForFile($file);
$reader->setReadDataOnly(true);
// Читаем файл и записываем информацию в переменную
$spreadsheet = $reader->load($file);
// Так можно достать объект Cells, имеющий доступ к содержимому ячеек
$cells = $spreadsheet->getSheet(0)->getCellCollection();
// Далее перебираем все заполненные строки
for ($row = 2; $row <= $cells->getHighestRow(); $row++) {
$myarr[] = ['name' => $cells->get('A'.$row) ? $cells->get('A'.$row)->getValue() : '',
'price' => $cells->get('B'.$row) ? $cells->get('B'.$row)->getValue() : ''
];
}
}

Import Excel Data to mysql 1 sheet only using PHP

I am trying to import a grade sheet into mysql database but that excel file have multiple sheet how can i make it so only a specified sheet will be going into my database
$uploadfile=$_FILES['uploadfile']['tmp_name'];
require 'PHPExcel/Classes/PHPExcel.php';
require_once 'PHPExcel/Classes/PHPExcel/IOFactory.php';
$objExcel =PHPExcel_IOFactory::load($uploadfile);
foreach($objExcel->getWorksheetIterator() as $worksheet)
{
$highestrow=$worksheet->getHighestRow();
for($row=8;$row<=$highestrow;$row++){
$name=$worksheet->getCellByColumnAndRow(1,$row)->getValue();
$finalgrade=$worksheet->getCellByColumnAndRow(15,$row)->getValue();
if($finalgrade != ''){
$insertqry = "INSERT INTO `user`(`stud_name`, `final_grade`) VALUES ('$name',' $finalgrade')";
$insertres = mysqli_query($con,$insertqry);
}
}
}
As far as I understand you are looking to get data from a specific sheet.
In PHPExcel there is this function: setActiveSheetIndex(sheet_index)
You can try like this:
$uploadfile = 'test.xlsx';
$objExcel = PHPExcel_IOFactory::load($uploadfile);
$objData = PHPExcel_IOFactory::createReader('Excel2007');
//read only
$objData->setReadDataOnly(true);
$objPHPExcel = $objData->load($uploadfile);
// Select sheet to get
$sheet = $objPHPExcel->setActiveSheetIndex(1);
$Totalrow = $sheet->getHighestRow();
$LastColumn = $sheet->getHighestColumn();
$TotalCol = PHPExcel_Cell::columnIndexFromString($LastColumn);
$data = [];
// Proceed to loop through each data cell
// Repeat rows, Since the first row is assumed to be the column header, we will loop the value from line 2
for ($i = 2; $i <= $Totalrow; $i++) {
//---- Loop column
for ($j = 0; $j < $TotalCol; $j++) {
// Proceed to get the value of each cell into the array
$data[$i - 2][$j] = $sheet->getCellByColumnAndRow($j, $i)->getValue();;
}
}
var_dump($data);
i just deleted the foreach and add getSheetName()
require 'PHPExcel/Classes/PHPExcel.php';
require_once 'PHPExcel/Classes/PHPExcel/IOFactory.php';
$objExcel =PHPExcel_IOFactory::load($uploadfile);
$worksheet = $objExcel->getSheetByName('GEN.AVERAGE');
$highestrow=$worksheet->getHighestRow();
for($row=8;$row<=$highestrow;$row++){
$name=$worksheet->getCellByColumnAndRow(1,$row)->getValue();
$finalgrade=$worksheet->getCellByColumnAndRow(15,$row)->getValue();
if($finalgrade != ''){
$insertqry = "INSERT INTO `user`(`stud_name`, `final_grade`) VALUES ('$name',' $finalgrade')";
$insertres = mysqli_query($con,$insertqry);
}
}

How to Skip Header from Excel Spreadsheet While Uploading to MySQL

Is it possible by code to skip the Header (Top Row) in Excel Spreadsheet?
I'm using PHPExcel_Reader to process upload into database.
this image is my data excel
this is my code:
<?php require_once('../../php-excel-reader/excel_reader2.php'); require_once('../../SpreadsheetReader.php'); if (isset($_POST["import"])) { $allowedFileType = ['application/vnd.ms-excel','text/xls','text/xlsx','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']; if(in_array($_FILES["file"]["type"],$allowedFileType)){ $targetPath = '../assets/uploads/'.$_FILES['file']['name']; move_uploaded_file($_FILES['file']['tmp_name'], $targetPath); $Reader = new SpreadsheetReader($targetPath); $sheetCount = count($Reader->sheets()); for($i=0;$i<$sheetCount;$i++) { $Reader->ChangeSheet($i); foreach ($Reader as $Row) { $student_id = ""; if(isset($Row[0])) { $student_id = mysqli_real_escape_string($conn,$Row[0]); } $roll_no = ""; if(isset($Row[1])) { $roll_no = mysqli_real_escape_string($conn,$Row[1]); } $student_name = ""; if(isset($Row[2])) { $student_name = mysqli_real_escape_string($conn,$Row[2]); } $class_name = ""; if(isset($Row[3])) { $class_name = mysqli_real_escape_string($conn,$Row[3]); } ?>
I use this method for skip header :
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load('FILE.xlsx');
$sheetData = array();
foreach ($spreadsheet->getWorksheetIterator() as $worksheet) {
$worksheetTitle = $worksheet->getTitle();
$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);
for ($row = 1; $row <= $highestRow; ++$row) {
for ($col = 0; $col <= $highestColumnIndex; ++$col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val = $cell->getValue();
$sheetData[$row][$col] = $val;
}
}
}
unset($sheetData[1]); // SKIP HEADER
foreach ($sheetData as $val) {
// set data for upload DB
}
i just unset that from array.

PHPExcell get cell value and cell color?

How to get cell values and cell colors from spreadsheet-reader-master or PHPExcell?
<?php
require('spreadsheet-reader-master/php-excel-reader/excel_reader2.php'); //spreadsheet-reader-master
require('spreadsheet-reader-master/SpreadsheetReader.php'); //spreadsheet-reader-master
$reader = new SpreadsheetReader('Book1.xlsx'); // xlsx file
foreach ($reader as $key ) {
//foreach loop
echo "<pre>";
print_r($key);
}
<?php
require('./PHPExcel-1.8/Classes/PHPExcel.php');
$tmpframe = './Book1.xlsx';
$exceReader = PHPExcel_IOFactory::createReaderForFile($tmpframe);
$excelObj = $exceReader->load($tmpframe);
$worksheet = $excelObj->getActiveSheet();
$lastRow = $worksheet->getHighestRow();
// $highestRow = $sheet->getHighestRow();
// $highestColumn = $worksheet->getHighestColumn();
$rowl = $worksheet->getHighestRow();
$coll = $worksheet->getHighestColumn();
echo "number of rows---".$rowl."<br>";
echo "number of column---".$coll."<br>";
$rowdumy = 20;
$crt = 'QT';
$crt++;
for ($row=1; $row <= $rowdumy; $row++) {
echo "<h6>number of-----".$row."</h5><br>";
for ($i = 'A'; $i !== $crt; $i++){
$cell = $worksheet->getCell($i.$row);
$colurc = $excelObj->getActiveSheet()->getStyle($i.$row)->getFill()->getStartColor()->getARGB();
if($cell != '')
{
echo $cell."-[[".$colurc."]]";
}
}
echo "<br>";
}
?>

Not able to retrive data from array

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?

Categories