I'm fairly new to PHPExcel and was wondering if you would be able to assist me with the code below.
Exporting with PHPExcel works perfectly, but when I am importing a xls or xlsx document, it stores the content of the sheet (which is what i want) but also inserts almost 200 blank entries into the Database, from a sheet with 4 rows of data.
I've searched the internet for quite a while now, but cannot seem to find the solution to this.
See my code below:
$storedir = "../uploads/". $_FILES['file']['name'];
$store = move_uploaded_file($_FILES['file']['tmp_name'], $storedir);
$filename = $_FILES['file']['name'];
$srow = $_POST['srow'];
if ($store) {
$objPHPExcel = PHPExcel_IOFactory::load($storedir);
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$highestRow = $worksheet->getHighestRow();
$highestColumn = $worksheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$nrColumns = ord($highestColumn) - 64;
for ($row = $srow; $row <= $highestRow-2; ++ $row) {
$val=array();
for ($col = 1; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val[] = $cell->getValue();
}
$savetodb = mysql_query("INSERT INTO `students` (`gender`, `name`, `surname`) VALUES ('".$val[1]."','".$val[2]."','".$val[3]."')") or die (mysql_error());
}
}
}
I've not added my Connection codes and includes for PHPExcel classes and IOFactories, although they are in the code.
Any assistance would be greatly appreciated.
Related
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);
}
}
I have the code that can save the uploaded csv file in the database. But the problem is that it can only save 100-200 rows out of more than 1000 rows. I have an idea to save rows batch by batch instead of a whole but i don't know how to code it.
require_once 'PHPexcel/PHPExcel.php';
$objPHPExcel = PHPExcel_IOFactory::load($file);
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$worksheetTitle = $worksheet->getTitle();
$highestRow = $worksheet->getHighestRow();
$highestColumn = $worksheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
for ($row = 2; $row <= $highestRow; ++ $row) {
$val=array();
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val[] = $cell->getValue();
}
}
}
I'm using the column header as an array index (row 1), and I don't want to have problems when they start uploading their XLSX file with incorrect column headers (or sometimes missing).
I found this answer really useful. I can make my array indexes as column headers:
for ($row = 2; $row <= $highestRow; $row++){
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
$rowData[0] = array_combine($headings[0], $rowData[0]);
}
The code above is from https://stackoverflow.com/a/32526911/8191721
Here's what I want to happen:
Check first the column headers if they matches with the column
headers I provided (in array, so I can use in_array in a loop) before
writing it to the database.
If the headers are correct, I will now turn the array indexes to column headers (so instead of [0], it should now return [firstname]) or else throw an error message.
Write to database where the column names in my database exactly matches the column header names (or if not, at least matches the query) in their XLSX file. (I called them "column mapping").
Long story short, here's my code:
try {
$inputFileName = $_FILES['file']['tmp_name'];
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
//-- Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
$headings = $sheet->rangeToArray('A1:'.$highestColumn.'1', NULL, TRUE, FALSE);
//-- $row = 2 <- skip row 1 since this is our headers
for($row = 2; $row <= $highestRow; $row++) {
//-- Read a row of data into an array
$xlsxRow = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
//-- Combine to replace indexes with header names
$xlsxRow[0] = array_combine($headings[0], $xlsxRow[0]);
//-- Got stucked in here..
/*
If column header fails, should exit the loop
*/
//-- SQL query follows here..
}
So can someone help me figuring this out?
To compare the header value you can use array_diff() function.
If you want to give more flexibility to user then you can use following example.
In this case use
$excelSheetHeaders = array();
for ($i = 1; $i <= 1; $i++) {
$rowData = $sheet->rangeToArray('A' . $i . ':' . $highestColumn . $i, NULL, TRUE, FALSE);
$excelSheetHeaders = $rowData[0];
$excelSheetHeaders = array_map('strtolower', $excelSheetHeaders);
$errorCount = 0;
foreach ($headerArray as $index => $value){
if(!in_array(strtolower($value), $excelSheetHeaders)){
$errorCount++;
}
}
if($errorCount > 0){
//Throw Error and exit;
}
}
for ($i = 2; $i <= $highestRow; $i++){
$rowData = $sheet->rangeToArray('A' . $i . ':' . $highestColumn . $i,NULL,TRUE,FALSE);
$spreadsheetData = array();
foreach($headerArray as $index => $value){
$spreadsheetData[$value] = $rowData[0][array_search(strtolower($value),$excelSheetHeaders)];
}
var_dump($spreadsheetData);
}
This error is exactly what you want. Now you can access $spreadsheetData['firstName'].
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 have PHPExcel plugin to generated excel which data came from database, how if I wanted to add in additional text into a column A during the loop, and column B remain untouched data as from DB?
For example column A in DB is
alex
andy
jennifer
when output to excel, I wanted to add #domain.com for each name behind, wich will become
alex#domain.com
andy#domain.com
jennifer#domain.com
Code:
$query = "SELECT mail_name, account_id FROM email ORDER BY mail_name ASC";
$headings = array('Email', 'Id');
if ($result = mysql_query($query) or die(mysql_error())) {
// Create a new PHPExcel object
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->setTitle('emailList');
$rowNumber = 1;
$col = 'A';
foreach($headings as $heading) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$heading);
$col++;
}
// Loop through the result set
$rowNumber = 1;
while ($row = mysql_fetch_row($result)) {
$col = 'A';
foreach($row as $cell) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$cell);
$col++;
}
$rowNumber++;
}
Keep in mind that $col++ is not going to work.
What about this way?:
// Loop through the result set
$rowNumber = 1;
while ($row = mysql_fetch_row($result)) {
$objPHPExcel->getActiveSheet()
->setCellValue('A'.$rowNumber,$row['mail_name'].'#domain.com');
$objPHPExcel->getActiveSheet()
->setCellValue('B'.$rowNumber,$row['account_id']);
++$rowNumber;
}