I am using phpexcel to send student record via excel in bulk and i want to post to api in json format.my output is below but i want in the format like below from which the api can save the each data in database.
My Controller:
$import = new ImportExcel();
if ($import->load(Yii::$app->request->post())) {
//upload path global parameters
Yii::$app->params['uploadPath'] = Yii::$app->basePath . '/web/upload/excel/';
$file = UploadedFile::getInstance($import, 'import');
$path = Yii::$app->params['uploadPath'] . $file;
$file->saveAs($path);
// Include PHPExcel_IOFactory
try {
$inputFileType = PHPExcel_IOFactory::identify($path);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($path);
} catch (Exception $e) {
die('Error loading file "' . pathinfo($path, PATHINFO_BASENAME) . '": ' . $e->getMessage());
}
// Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$worksheet = $objPHPExcel->setActiveSheetIndexbyName('Sheet1');
$worksheetTitle = $worksheet->getTitle();
// Loop through each row of the worksheet in turn
for ($row = 1; $row <= $highestRow; $row++) {
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
var_dump(json_encode($rowData));
}
}
OutPut:
string(70) "[["name","address","class","section","guardian","contact us","email"]]" string(107) "[["sugam pradhan","rambazar,pokhara-10",10,"A","jayandra kumar rajbhandari",61431910,"suyog844#gmail.com"]]" string(105) "[["Bill gurung","rambazar,pokhara-10",10,"A","jayandra kumar rajbhandari",61431910,"suyog844#gmail.com"]]" string(107) "[["Bimal poudelq","rambazar,pokhara-10",10,"A","jayandra kumar rajbhandari",61431910,"suyog844#gmail.com"]]" string(101) "[["Dam sir","rambazar,pokhara-10",10,"A","jayandra kumar rajbhandari",61431910,"suyog844#gmail.com"]]"
I want to post in :
[{'school_id':3,'name':'name1','image':'image1','guardian_name':'guardian_name1','address':'address1','contact_no':'111','email':'email1#mail.com','blood_grp':'A','d_o_b':'2001-01-01','class_id':1,'section_id':2,'roll_no':'1','enrolled_date':'2010-01-01','is_active':0},
You need to map first row as keys as far as I understood.
$row = 1; $result = [];
$keys = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
// Loop through each row of the worksheet in turn
for ($row = 2; $row <= $highestRow; $row++) {
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
$result[] = array_combine($keys,$rowData);
}
var_dump($result);
This way you will get what you need if 1st row is keys for your array.
Related
I have this code that I use to read Excel 2007 file.
<?php
function load_table(){
require_once('Classes/PHPExcel.php');
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(false);
$objPHPExcel = $objReader->load("SampleData.xlsx");
$objWorksheet = $objPHPExcel->getActiveSheet();
$highestRow = $objWorksheet->getHighestRow(); // e.g. 10
$highestColumn = $objWorksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); // e.g. 5
echo '<table class="table">' . "\n";
for ($row = 1; $row <= $highestRow; ++$row) {
echo '<tr>' . "\n";
for ($col = 0; $col <= $highestColumnIndex; ++$col) {
echo '<td>';
$first = $objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
if($first[0] == '='){
echo $objWorksheet->getCellByColumnAndRow($col, $row)->getCalculatedValue();
}
else
echo $first;
echo '</td>' . "\n";
}
echo '</tr>' . "\n";
}
echo '</table>' . "\n";
}
?>
But I need to read an Excel 2003 file. When I change the code I get error saying that:
Fatal error: Class 'PHPExcel_Reader_Excel2003' not found in ...
Change code:
$objReader = PHPExcel_IOFactory::createReader('Excel2003');
I think you should use
PHPExcel_IOFactory::createReader('Excel5');
or
PHPExcel_IOFactory::createReader('Excel2003XML');
instead of
PHPExcel_IOFactory::createReader('Excel2007');
It's depends your xls file. You can read more details here PHPExcel Docs.
$inputFileType = PHPExcel_IOFactory::identify($inputFile);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
Make phpexcel identify what type of your file.
I'm using PHPExcel to import xls to mysql.
I recently switched connection to PDO.
But then an error accord.
Fields in my xls that is NULL are no longer accepted.
Why? How can i change my code to accept NULL value?
PHP:
if(isset($_POST["Import"])){
echo 'Fortsätt...<br />';
echo $path=$_FILES["file"]["tmp_name"];
//Load file into PHPExcel
$objPHPExcel = PHPExcel_IOFactory::load($path);
//Loop threw file to get data
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$worksheetTitle = $worksheet->getTitle();
$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = 'J'; //$worksheet->getHighestColumn(''); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$nrColumns = ord($highestColumn) - 64;
//Echo file info
echo "<br>The worksheet ".$worksheetTitle." has ";
echo $nrColumns . ' columns (A-' . $highestColumn . ') ';
echo ' and ' . $highestRow . ' row.';
echo '<br>Data: <table border="1"><tr>';
//Loop threw colum, rows and cells
for ($row = 2; $row <= $highestRow; ++ $row) {
echo '<tr>';
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val = $cell->getCalculatedValue();
//$dataType = PHPExcel_Cell_DataType::dataTypeForValue($val);
echo '<td>' . $val . '<br></td>';
}
echo '</tr>';
}
echo '</table>';
}
for ($row = 2; $row <= $highestRow; ++ $row) {
$val=array();
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val[] = $cell->getCalculatedValue();
}
// Prepare Query
$query = "INSERT INTO table(
objekt_nr,
objekt_rev,
element_nr,
element_hojd,
element_typ,
element_langd,
element_oppningar,
element_vikt,
element_ritare,
element_status)
VALUES (
:objekt_nr,
:objekt_rev,
:element_nr,
:element_hojd,
:element_typ,
:element_langd,
:element_oppningar,
:element_vikt,
:element_ritare,
:element_status
)";
// Security measures
$query_params = array(
':objekt_nr' => $val[0],
':objekt_rev' => $val[1],
':element_nr' => $val[2],
':element_hojd' => $val[3],
':element_typ' => $val[4],
':element_langd' => $val[5],
':element_oppningar' => $val[6],
':element_vikt' => $val[7],
':element_ritare' => $val[8],
':element_status' => $val[9]
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage()); }
To accept a NULL value you have to edit the database table, not the code. Your message error is generated by MySQL, not the PHP.
I’m trying to write a if code, but can't figure out how.
In my database table i have the primary key id.
In the table i have objekt_nr & element_nr.
Now, before i call an INSTERT i need to check if objekt_nr with element_nr already exist.
If objekt_nr With element_nr exist. Then UPDATE instead of INSTERT. Only id can be unique.
example of table:
id......objekt_nr......element_nr
1.......1...............1
2.......1...............2
3.......1...............3
4.......2...............1
5.......2...............2
PHP:
if(isset($_POST["Import"])){
echo 'Fortsätt...<br />';
echo $path=$_FILES["file"]["tmp_name"];
//Load file into PHPExcel
$objPHPExcel = PHPExcel_IOFactory::load($path);
//Loop threw file to get data
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$worksheetTitle = $worksheet->getTitle();
$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = 'J'; //$worksheet->getHighestColumn(''); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$nrColumns = ord($highestColumn) - 64;
//Echo file info
echo "<br>The worksheet ".$worksheetTitle." has ";
echo $nrColumns . ' columns (A-' . $highestColumn . ') ';
echo ' and ' . $highestRow . ' row.';
echo '<br>Data: <table border="1"><tr>';
//Loop threw colum, rows and cells
for ($row = 2; $row <= $highestRow; ++ $row) {
echo '<tr>';
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val = $cell->getCalculatedValue();
//$dataType = PHPExcel_Cell_DataType::dataTypeForValue($val);
echo '<td>' . $val . '<br></td>';
}
echo '</tr>';
}
echo '</table>';
}
for ($row = 2; $row <= $highestRow; ++ $row) {
$val=array();
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val[] = $cell->getCalculatedValue();
}
// Prepare Query
$query = "INSERT INTO phpexcel(
objekt_nr,
objekt_rev,
element_nr,
element_hojd,
element_typ,
element_langd,
element_oppningar,
element_vikt,
element_ritare,
element_status)
VALUES (
:objekt_nr,
:objekt_rev,
:element_nr,
:element_hojd,
:element_typ,
:element_langd,
:element_oppningar,
:element_vikt,
:element_ritare,
:element_status
)";
// Security measures
$query_params = array(
':objekt_nr' => $val[0],
':objekt_rev' => $val[1],
':element_nr' => $val[2],
':element_hojd' => $val[3],
':element_typ' => $val[4],
':element_langd' => $val[5],
':element_oppningar' => $val[6],
':element_vikt' => $val[7],
':element_ritare' => $val[8],
':element_status' => $val[9]
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage()); }
//echo $query."\n";
}
}
Two options here.
1) Make "objekt_nr" field a PRIMARY or UNIQUE key and use REPLACE instead of INSERT (http://dev.mysql.com/doc/refman/5.0/en/replace.html). This is pretty much #hd 's answer in the comments.
2) Check for an existing "objekt_nr" and "element_nr" and run the appropriate query
$check_duplicate_query = "SELECT COUNT(*) FROM phpexcel WHERE objekt_nr = ':objekt_nr' AND element_nr = ':element_nr'";
$stmt = $db->prepare($check_duplicate_query);
$result = $stmt->execute($query_params);
$rows = $stmt->fetch(PDO::FETCH_NUM);
if($rows[0] > 0) {
//UPDATE
} else {
//INSERT
}
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
EDIT:
Just thought of a 3rd option
Create another field "objekt_element_nr" and set this field to unique.
This field gets assigned objekt and element number combination, which from your example should be unique.
e.g. 1_1, 1_2, 1_3, 2_1, 2_2, etc.
Then simply use the REPLACE function I linked to above.
Your $query_params would look like
$query_params = array(
':objekt_nr' => $val[0],
':objekt_rev' => $val[1],
':element_nr' => $val[2],
':objekt_element_nr' => $val[0].'_'.$val[2]
':element_hojd' => $val[3],
':element_typ' => $val[4],
':element_langd' => $val[5],
':element_oppningar' => $val[6],
':element_vikt' => $val[7],
':element_ritare' => $val[8],
':element_status' => $val[9]
);
Grid lines are not showing up .Below is my code.Please Help.
<?php
require_once '../Classes/PHPExcel.php';
$inputFileName = 'current.xlsx';
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
$objWorksheet = $objPHPExcel->getActiveSheet();
$objPHPExcel->getActiveSheet()->setShowGridlines(true);
$highestRow = $objWorksheet->getHighestRow();
$highestColumn = $objWorksheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
echo '<div id="xl">' . "\n";
echo '<table>' . "\n";
for ($row = 1; $row <= 2; ++$row) {
echo '<tr>' . "\n";
for ($col = 0; $col <= $highestColumnIndex; ++$col) {
echo '<td>' . $objWorksheet->getCellByColumnAndRow($col, $row)->getValue() . '</td>' . "\n";
}
echo '</tr>' . "\n";
}
echo '</table>' . "\n";
echo '</div>' . "\n";
?>
I got it displayed as such.Below is my code.
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'HTML');
$objWriter->save('php://output');
so I'm trying to create an array from excel list using php
my excel has these values between A1:A3 - value1, value2, value3
My code is this:
<?php
require_once dirname(__FILE__) . '/includes/libraries/classes/PHPExcel.php';
$objPHPExcel = new PHPExcel();
$objReader = new PHPExcel_Reader_Excel5();
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load( dirname(__FILE__) . '/Tellimus.xls' );
$objWorksheet = $objPHPExcel->getActiveSheet();
$highestRow = $objWorksheet->getHighestRow(); // e.g. 10
$highestColumn = $objWorksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); // e.g. 5
$newarray=array();
echo '<table>' . "\n";
for ($row = 1; $row <= $highestRow; ++$row) {
echo '<tr>' . "\n";
for ($col = 0; $col <= $highestColumnIndex; ++$col) {
$column=$objWorksheet->getCellByColumnAndRow($col,$row)->getValue();
echo '<td>' . $objWorksheet->getCellByColumnAndRow($col, $row)->getValue() . '</td>' . "\n";
$newarray[] = $column;
}
echo '</tr>' . "\n";
}
echo '</table>' . "\n";
print_r($newarray);
?>
And it shows as: Array ( [0] => value1 [1] => [2] => value2 [3] => [4] => value3 [5] => )
My goal is to get an array without having empty spaces as number 1 array and number 3 array and so on after every entry. How can I accomplish this?
hope this help:
<?php
require_once dirname(__FILE__) . '/includes/libraries/classes/PHPExcel.php';
$objPHPExcel = new PHPExcel();
$objReader = new PHPExcel_Reader_Excel5();
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load( dirname(__FILE__) . '/Tellimus.xls' );
$objWorksheet = $objPHPExcel->getActiveSheet();
$highestRow = $objWorksheet->getHighestRow(); // e.g. 10
$highestColumn = $objWorksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); // e.g. 5
$newarray=array();
echo '<table>' . "\n";
for ($row = 1; $row <= $highestRow; ++$row) {
echo '<tr>' . "\n";
for ($col = 0; $col <= $highestColumnIndex; ++$col) {
$column=$objWorksheet->getCellByColumnAndRow($col,$row)->getValue();
echo '<td>' . $objWorksheet->getCellByColumnAndRow($col, $row)->getValue() . '</td>' . "\n";
if (isset ($column)){
$newarray[] = $column;
}
}
echo '</tr>' . "\n";
}
echo '</table>' . "\n";
print_r($newarray);
?>