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);
}
}
Related
What would be the most efficient way of checking data contained in arrays
I want to validate in the following ways:
if cell a and b are a string
if cell c and d are numbers
if cells are empty
Then how would it be best to catch errors and display them to the user?
I'm using codeigniter and the PHPExcel library
an example of where I'm currently at
public function read_excel()
{
$this->load->library('excel');
$inputFileName = 'test.xlsx';
/** Identify the type of $inputFileName **/
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
/** Advise the Reader that we only want to load cell data **/
$objReader->setReadDataOnly(true);
/** Load $inputFileName to a PHPExcel Object **/
$objPHPExcel = $objReader->load($inputFileName);
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
// Loop through each row of the worksheet
for ($row = 2; $row <= $highestRow; $row++){ // Read a row of data into an array
$rowData = $sheet->rangeToArray('A'.$row.':'.$highestColumn.$row,NULL,TRUE,FALSE);
$cella = strtoupper($rowData[0][0]);
$cellb = strtoupper($rowData[0][1]);
$cellc = $rowData[0][2];
$celld = $rowData[0][3];
}
}
To Answer my own question i eventually went with the below
if (!isset($rowData[0][0],$rowData[0][1],$rowData[0][2])) {
echo "error cells a-c are required.";
}
for ($i=0; $i <$columns ; $i++) {
switch ($rowData[0][$i]) {
case (is_numeric($rowData[0][$i])):
filter_var($rowData[0][$i],FILTER_SANITIZE_NUMBER_INT);
echo $rowData[0][$i];
echo "</br>";
break;
case (is_string($rowData[0][$i])):
$rowData[0][$i] = preg_replace("/[^A-Za-z0-9\-]/"," ",$rowData[0][$i]);
break;
}
}
We are converting excel to CSV with every sheet. For example if a excel file has 5 sheets then we are converting 5 CSV file for every sheet.
Its working fine except one thing.
As we know excel sheet has some formulas for calculation like sum, Average etc..., So when we are converting them to CSV file, Then function is showing as it is, Their calculated value is not showing, which we can read as a excel sheet.
This is the function which we are using
function write_csv($filename,$definename){
$dir = "";
$file_arr = array();
array_push($file_arr, $filename);
// Make CSV File
$list = array();
foreach($file_arr as $val)
{
$arr_data = array();
// echo $val;
$objPHPExcel = PHPExcel_IOFactory::load($dir . $val);
// print_r($objPHPExcel->getSheetNames());exit;
$loadedSheetNames = $objPHPExcel->getSheetNames();
foreach($loadedSheetNames as $sheetIndex => $loadedSheetName) {
// echo $sheetIndex;
$objPHPExcel->setActiveSheetIndex($sheetIndex);
$fp = fopen($definename.'_'.$sheetIndex.'.csv', 'a');
$cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();
// print_r($cell_collection);
foreach($cell_collection as $cell)
{
$column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
$row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
$data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();
//header will / should be in row 1 only. of course this can be modified to suit your need.
// Skip Rows From Top if you have header in Excel then Change 0 to 1
if($row == 0)
{
$header[$row][$column] = $data_value;
}
else
{
$arr_data[$row]['row'] = $row;
$arr_data[$row][$column] = $data_value;
}
}
$data = $arr_data;
foreach($data as $val1)
{
$num_col = sizeof($val1) - 1; // get number of columns in Excel
break;
}
$lwrcol=array();
foreach($data as $val2)
{
$alphaArr = range('A','Z');
$colArr = range('A',$alphaArr[$num_col - 1]);
foreach($colArr as $col)
{
$lwrcol[$col] = isset($val2[$col]) ? utf8_decode($val2[$col]) : "";
fwrite($fp,$lwrcol[$col].",");
}
fwrite($fp,"\n");
}
// chmod(getcwd()."/file.csv", 0777);
fclose($fp);
}
}
}
Please tell me what we are doing wrong.
Complete Code:
http://pastebin.com/DaRBSpqP
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.
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
How can i read Excel worksheet row by row using PHPExcel? I have a sheet contains more than 100000 rows, but i want to read only 500 rows.
$sheetData = $objPHPExcel->getActiveSheet();
$highestRow = $sheetData->getHighestRow();
$highestColumn = $sheetData->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
echo '<table>';
for ($row = 1; $row <= $highestRow; ++$row) {
echo '<tr>';
for ($col = 0; $col <= $highestColumnIndex; ++$col) {
echo '<td>' . $sheetData->getCellByColumnAndRow($col, $row)->getValue() . '</td>';
}
echo '</tr>';
}
echo '</table>';
If you only want to read 500 rows, then only load 500 rows using a read filter:
$inputFileType = 'Excel5';
$inputFileName = './sampleData/example2.xls';
/** Define a Read Filter class implementing PHPExcel_Reader_IReadFilter */
class myReadFilter implements PHPExcel_Reader_IReadFilter
{
private $_startRow = 0;
private $_endRow = 0;
/** Set the list of rows that we want to read */
public function setRows($startRow, $chunksize) {
$this->_startRow = $startRow;
$this->_endRow = $startRow + $chunkSize;
}
public function readCell($column, $row, $worksheetName = '') {
// Only read the heading row, and the rows that are configured in $this->_startRow and $this->_endRow
if (($row >= $this->_startRow && $row < $this->_endRow)) {
return true;
}
return false;
}
}
/** Create a new Reader of the type defined in $inputFileType **/
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
/** Define how many rows we want to read for each "chunk" **/
$chunkSize = 500;
/** Create a new Instance of our Read Filter **/
$chunkFilter = new myReadFilter();
/** Tell the Reader that we want to use the Read Filter that we've Instantiated **/
$objReader->setReadFilter($chunkFilter);
/** Tell the Read Filter, the limits on which rows we want to read this iteration **/
$chunkFilter->setRows(1,500);
/** Load only the rows that match our filter from $inputFileName to a PHPExcel Object **/
$objPHPExcel = $objReader->load($inputFileName);
See the PHPExcel User Documentation - Reading Spreadsheet Files document in /Documentation for more details on Read Filters
You can load 500 rows or even setting start index by setting parameters directly to the getRowIterator function.
$path = "Your File Path HERE";
$fileObj = \PHPExcel_IOFactory::load( $path );
$sheetObj = $fileObj->getActiveSheet();
$startFrom = 50; //default value is 1
$limit = 550; //default value is null
foreach( $sheetObj->getRowIterator($startFrom, $limit) as $row ){
foreach( $row->getCellIterator() as $cell ){
$value = $cell->getCalculatedValue();
}
}
This loops through all rows and columns and assigns the cell value to $cellValue. If the $i is greater than 500, it breaks out the loop
$objWorksheet = $objPHPExcel->getActiveSheet();
$i = 0;
foreach ($objWorksheet->getRowIterator() as $row) {
if ($i > 500) break;
$i++;
foreach ($row->getCellIterator() as $cell) {
$cellValue = trim($cell->getCalculatedValue());
}
}
require_once "/PATH TO PHP EXCEL FOLDER/PHPExcel.php";
$inputFileName = $_FILES['FILENAME'];
$objTpl = PHPExcel_IOFactory::load('./PATH TO UPLOAD FOLDER/' . $inputFileName);
$sheetData = $objTpl->getActiveSheet()->toArray(null, true, true, true);
array_shift($sheetData);
$i=0;
$test_array = array();
foreach($sheetData as $key=>$val){
if($i < 500)
$test_array[$i] = $val;
$i++;
}