I got a problem when call the PHPExcel library AutoLoader.php file.
I try to upload the Excel file, then after clicking on the upload button, it saves data into the database. I get an error, as shown in the photo after uploading the file. How can I fix this?
<?php
require('library/Classes/PHPExcel/IOFactory.php');
/** Include path **/
set_include_path(get_include_path() . PATH_SEPARATOR . '../Classes/');
if(isset($_POST['submit'])){
if((isset($_POST['file'])) && !empty($_POST['file']))
{
$file = $_POST['file'];
}
$fileName= $_FILES["file"]["name"];
echo ('fileName +'.$fileName);
//$uploadPath = $_SERVER['DOCUMENT_ROOT'].'/SMS/excel/' ;
$fileTempName= $_FILES["name"]["temp_name"];
//echo ('fileTempName +'.$fileTempName);
$fileExtension= pathinfo($fileName,PATHINFO_EXTENSION);
$allowedtype= array('xlsx','sls','xlsm');
if(!in_array($fileExtension,$allowedtype)){
echo("<br/>Sorry, File type is not allowed. Only Excel file.");
}
else {
echo("Correct File Extension");
try
{
$inputfiletype = PHPExcel_IOFactory::identify($fileName);
$objReader = PHPExcel_IOFactory::createReader($inputfiletype);
$objPHPExcel = $objReader->load($fileName);
echo 'Reading the number of Worksheets in the WorkBook<br />';
/** Use the PHPExcel object's getSheetCount() method to get a count of the number of WorkSheets in the WorkBook */
$sheetCount = $objPHPExcel->getSheetCount();
echo 'There ',(($sheetCount == 1) ? 'is' : 'are'),' ',$sheetCount,' WorkSheet',(($sheetCount == 1) ? '' : 's'),' in the WorkBook<br /><br />';
echo 'Reading the names of Worksheets in the WorkBook<br />';
/** Use the PHPExcel object's getSheetNames() method to get an array listing the names/titles of the WorkSheets in the WorkBook */
$sheetNames = $objPHPExcel->getSheetNames();
foreach($sheetNames as $sheetIndex => $sheetName) {
echo 'WorkSheet #',$sheetIndex,' is named "',$sheetName,'"<br />';
}
}
catch(Exception $e)
{
die('Error loading file "'.pathinfo($fileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
}
}
?>
Related
just a php beginner question.
How can I create an input to load the XLS file without having to download it on the server and use it in the code below where I have the variable $inputFileName.
<?php
/** Include path **/
set_include_path(get_include_path() . PATH_SEPARATOR . '../../../Classes/');
/** PHPExcel_IOFactory */
include 'PHPExcel/IOFactory.php';
**$inputFileName = './sampleData/example1.xls';**
echo 'Loading file ',pathinfo($inputFileName,PATHINFO_BASENAME),' using IOFactory to identify the format<br />';
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
echo '<hr />';
$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
var_dump($sheetData);
?>
Thank you all...
I'm trying to read excel file. but it's showing me error. I tried with this.
set_include_path(get_include_path() . PATH_SEPARATOR . 'Classes/');
/** PHPExcel_IOFactory */
include 'PHPExcel/IOFactory.php';
// Set the Excel file name and path
$inputFileName = 'uploads/aaa.xlsx'; // this is 2007 new format.
// 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());
}
But this error is showing...
Fatal error: Class 'PHPExcel' not found in F:\xampp\htdocs\preme\PHPExcel\Reader\Excel2007.php on line 351
I autoload the "phpoffice/phpexcel" with composer. Make sure you get the same to your directory. If you do not use composer then point to the right directory. Just for demonstration I pointed to the folder down below
<?php
//require_once 'vendor/autoload.php';
require_once 'vendor\phpoffice\phpexcel\Classes\PHPExcel\IOFactory.php';
$inputFileName = 'uploads/aaa.xlsx';
// Read your Excel workbook
try {
$excelReader = PHPExcel_IOFactory::createReaderForFile($inputFileName);
$excelReader->setReadDataOnly();
$excelReader->setLoadAllSheets();
$excelObj = $excelReader->load($inputFileName);
//var_dump($excelObj);
} catch(Exception $e) {
die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
I have a problem converting file feom CSV to XLSX format:
Index.php
<?php
if (!isset($_FILES["file"]))
{
?>
<html>
<body>
<h1>Convert CSV to XLSX</h1>
<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit"/>
</form>
</body>
</html>
<?php
exit;
}
//obtain PHPExcel from http://phpexcel.codeplex.com
require_once('Classes\PHPExcel.php');
require_once('CSVToExcelConverter.php');
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"];
exit;
}
try
{
header('Content-type: application/ms-excel');
header('Content-Disposition: attachment; filename='.'example.xlsx');
CSVToExcelConverter::convert($_FILES['file']['tmp_name'], 'php://output');
} catch(Exception $e) {
echo $e->getMessage();
}
CSVToExcelConverter.php
class CSVToExcelConverter
{
/**
* Read given csv file and write all rows to given xls file
*
* #param string $csv_file Resource path of the csv file
* #param string $xls_file Resource path of the excel file
* #param string $csv_enc Encoding of the csv file, use utf8 if null
* #throws Exception
*/
public static function convert($csv_file, $xls_file, $csv_enc=null) {
//set cache
$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;
PHPExcel_Settings::setCacheStorageMethod($cacheMethod);
//open csv file
$objReader = new PHPExcel_Reader_CSV();
if ($csv_enc != null)
$objReader->setInputEncoding($csv_enc);
$objPHPExcel = $objReader->load($csv_file);
$in_sheet = $objPHPExcel->getActiveSheet();
//open excel file
$objPHPExcel = new PHPExcel();
$out_sheet = $objPHPExcel->getActiveSheet();
//row index start from 1
$row_index = 0;
foreach ($in_sheet->getRowIterator() as $row) {
$row_index++;
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
//column index start from 0
$column_index = -1;
foreach ($cellIterator as $cell) {
$column_index++;
$out_sheet->setCellValueByColumnAndRow($column_index, $row_index, $cell->getValue());
}
}
//write excel file
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter->save($xls_file);
}
}
CSV File format: CSV file opened with Excel
xlsx file I get after conversion
Basicaly I would like to get output similar to original csv file, but in xmlx format, how to do that?
The "default" separator for reading a CSV file in PHPExcel is a comma (,). Your CSV file is using something other than a comma - perhaps a tab ("\t"), which is also commonly used for such files).
If the values isn't a comma (and we can't tell from an image of the file viewed in MS Excel) then you have to tell PHPExcel explicitly what that separator is before loading.
e.g.
$objReader->setDelimiter("\t");
I am having problem while reading 3Mb data .xlsx file and same for 7Mb data .xls file. Is there any size limitations while reading file?
In my Excel file, I have 30,000 rows and 36 rows. Is there any solutions so that I can read up to 100K records or more then that?
In my project I have to import 1 million records, but my code is not working for more than 29000 records. Up until 29000 records my code works on my local.
And also reading 29000 records takes too much, time may be 25 min.
Can anyone please explain why this happens, and what should I do to resolve this?
Here is my code:
<?php
error_reporting(E_ALL);
set_time_limit(0);
ini_set("memory_limit","-1");
date_default_timezone_set('Europe/London');
define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />');
/** Set Include path to point at the PHPExcel Classes folder **/
set_include_path(get_include_path() . PATH_SEPARATOR . 'Classes/');
/** Include PHPExcel_IOFactory **/
include 'Classes/PHPExcel/IOFactory.php';
$inputFileName = 'files/30000rows.xls';
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
/** Define a Read Filter class implementing PHPExcel_Reader_IReadFilter */
class chunkReadFilter 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 = '')
{
if (($row == 1) || ($row >= $this->_startRow && $row < $this->_endRow))
{
return true;
}
return false;
}
}
echo 'Loading file ',pathinfo($inputFileName,PATHINFO_BASENAME),' using IOFactory with a defined reader type of ',$inputFileType,'<br />';
/** Create a new Reader of the type defined in $inputFileType **/
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
echo '<hr />';
/** Define how many rows we want to read for each "chunk" **/
$chunkSize = 1000;
//total rows in excel
$spreadsheetInfo = $objReader->listWorksheetInfo($inputFileName);
$totalRows = $spreadsheetInfo[0]['totalRows'];
/** Create a new Instance of our Read Filter **/
$chunkFilter = new chunkReadFilter();
/** Tell the Reader that we want to use the Read Filter that we've Instantiated **/
$objReader->setReadFilter($chunkFilter);
$objReader->setReadDataOnly(true);
/** Loop to read our worksheet in "chunk size" blocks **/
for ($startRow = 2; $startRow <= $totalRows; $startRow += $chunkSize) {
echo "in for loop<br>";
echo 'Loading WorkSheet using configurable filter for headings row 1 and for rows ',$startRow,' to ',($startRow+$chunkSize-1),'<br />';
/** Tell the Read Filter, the limits on which rows we want to read this iteration **/
$chunkFilter->setRows($startRow,$chunkSize);
$cacheMethod = PHPExcel_CachedObjectStorageFactory:: cache_to_phpTemp;
$cacheSettings = array( ' memoryCacheSize ' => '1000MB');
PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
$cacheMethod=PHPExcel_CachedObjectStorageFactory::cache_in_memory_serialized;
PHPExcel_Settings::setCacheStorageMethod($cacheMethod);
$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_in_memory_gzip;
if (!PHPExcel_Settings::setCacheStorageMethod($cacheMethod)) {
die($cacheMethod . " caching method is not available" . EOL);
}
echo date('H:i:s') , " Enable Cell Caching using " , $cacheMethod , " method" , EOL;
/** Load only the rows that match our filter from $inputFileName to a PHPExcel Object **/
$objPHPExcel = $objReader->load($inputFileName);
$objWorksheet = $objPHPExcel->getActiveSheet();
$highestColumn = $objWorksheet->getHighestColumn();
$sheetData = $objWorksheet- >rangeToArray('A'.$startRow.':'.$highestColumn.($startRow + $chunkSize-1),null, false, false, true);
echo '<pre>';
print_r($sheetData);
$objPHPExcel->disconnectWorksheets();
unset($objPHPExcel);
echo '<br /><br />';
}
?>
To read XLSX files, I can recommend you to use Spout. It makes it super simple to deal with large files. Here is how you would do it:
$reader = ReaderFactory::create(Type::XLSX);
$reader->open($filePath);
while ($reader->hasNextSheet()) {
$reader->nextSheet();
while ($reader->hasNextRow()) {
$row = $reader->nextRow();
// do stuff
}
}
$reader->close();
This works for any file, regardless of the file size. No need to worry about caching, filtering, memory consumption. It will require less than 10MB of memory and should take less than a minute to process the entire file.
I'm trying to upload a spreadsheet and read it into a MySQL database using PHPExcel.
For .xlsx files it works fine but whenever I try to upload a .ods file it throws the error: PHP Fatal error: Call to a member function getNamespaces() on a non-object in PHPExcel_1.7.9/Classes/PHPExcel/Reader/OOCalc.php on line 341
What's going wrong?
HTML Form:
<form method="post" enctype="multipart/form-data">
Upload File: <input type="file" name="spreadsheet"/>
<input type="submit" name="submit" value="Submit" />
</form>
PHP (In same file):
//Check valid spreadsheet has been uploaded
if(isset($_FILES['spreadsheet'])){
if($_FILES['spreadsheet']['name']){
if(!$_FILES['spreadsheet']['error'])
{
$inputFile = $_FILES['spreadsheet']['name'];
$extension = strtoupper(pathinfo($inputFile, PATHINFO_EXTENSION));
if($extension == 'XLSX' || $extension == 'ODS'){
//Read spreadsheeet workbook
try {
$inputFile = $_FILES['spreadsheet']['tmp_name'];
$inputFileType = PHPExcel_IOFactory::identify($inputFile);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFile);
} catch(Exception $e) {
die($e->getMessage());
}
//Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
//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);
//Insert into database
}
}
else{
echo "Please upload an XLSX or ODS file";
}
}
else{
echo $_FILES['spreadsheet']['error'];
}
}
}
?>
When a file is uploaded to your webserver, The file will be saved in the temporary folder of your system with a random name.
What you were trying to do was giving the actual name of the file you uploaded, But since the file was created with a random name in the tmp folder.
You will need to use tmp_name instead, Which actually point the that random named file.
Also note, in name You only have the name of the file that was uploaded and not the path,
But with tmp_name you have the actual path to the file.
See the following example of a file upload you would get.
array(
[UploadFieldName]=>array(
[name] => MyFile.jpg
[type] => image/jpeg
[tmp_name] => /tmp/php/php6hst32
[error] => UPLOAD_ERR_OK
[size] => 98174
)
)
change your code to this instead
//Check valid spreadsheet has been uploaded
if(isset($_FILES['spreadsheet'])){
if($_FILES['spreadsheet']['tmp_name']){
if(!$_FILES['spreadsheet']['error'])
{
$inputFile = $_FILES['spreadsheet']['tmp_name'];
$extension = strtoupper(pathinfo($inputFile, PATHINFO_EXTENSION));
if($extension == 'XLSX' || $extension == 'ODS'){
//Read spreadsheeet workbook
try {
$inputFileType = PHPExcel_IOFactory::identify($inputFile);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFile);
} catch(Exception $e) {
die($e->getMessage());
}
//Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
//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);
//Insert into database
}
}
else{
echo "Please upload an XLSX or ODS file";
}
}
else{
echo $_FILES['spreadsheet']['error'];
}
}
}
?>
In my case there was an error detecting the extension in this line
$extension = strtoupper(pathinfo($inputFile, PATHINFO_EXTENSION));
if you need to solve just check from the name parameter
$extension = strtoupper(explode(".", $_FILES['spreadsheet']['name'])[1]);
The rest is working thanks :)