I want to import the data from xlsx file into my database for this i used phpexcel library to convert xls or xlsx file into csv and then read data.
This code is working properly to convert xls file into csv on local-host and server both but xlsx to csv conversion is done only on local-host.
here is my code:
function convertXLStoCSV($infile,$outfile)
{
$fileType = PHPExcel_IOFactory::identify($infile);
$objReader = PHPExcel_IOFactory::createReader($fileType);
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load($infile);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
$objWriter->save($outfile);
}
and call this function using:
if($ext == 'xls' or $ext == 'xlsx')
{
$new_doc_name = time() . "." .$ext;
$target_path = "../../uploaded_files/";
$target_path = $target_path . $new_doc_name ;
if ($_FILES["CSV_file"]["type"] == "application/xls" or $_FILES["CSV_file"]["type"] == "application/xlsx" or $_FILES["CSV_file"]["type"] == "application/vnd.ms-excel" or $_FILES["CSV_file"]["type"] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"){
if(move_uploaded_file($_FILES['CSV_file']['tmp_name'], $target_path)) {
convertXLStoCSV($target_path,'output.csv');
if(($handle = fopen("output.csv" , "r")) !== FALSE)
please help
Try this
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load($uploadFIle);
$objWorksheet = $objPHPExcel->setActiveSheetIndex(0);
$highestRow = $objWorksheet->getHighestRow();
$highestColumn = $objWorksheet->getHighestColumn();
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
$index = 0;
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$objPHPExcel->setActiveSheetIndex($index);
// write out each worksheet to it's name with CSV extension
$outFile = str_replace(array("-"," "), "_", $worksheet->getTitle()) .".csv";
$objWriter->setSheetIndex($index);
$objWriter->save($outFile);
$index++;
}
Related
I am building a script that takes every xls file from the /uploads folder and converts it to CSV.
But, I am having this error:
Fatal error:
Uncaught Error: Call to undefined function convertXLStoCSV() in C:\xampp\htdocs\Technocripa-php\scandir.php:46 Stack trace: #0 {main} thrown in C:\xampp\htdocs\Technocripa-php\scandir.php on line 46
Here is the code:
$dir = "uploads/*";
foreach(glob($dir) as $file)
{
if(!is_dir($file)) { echo basename($file)."\n";}
//--------------------------
$nameAsString = (string)$file;
require_once('Classes/PHPExcel.php');
$inputfilename = $nameAsString;
$outputfilename = 'convert.csv';
//Usage:
convertXLStoCSV($inputfilename, $outputfilename);
function convertXLStoCSV($infile, $outfile)
{
$fileType = PHPExcel_IOFactory::identify($infile);
$objReader = PHPExcel_IOFactory::createReader($fileType);
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load($infile);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
$objWriter->save($outfile);
}
}
I think the error comes from wrong variable usage, but I really can't find a way to fix this. All I want to is store the name of te file in the uploads/ folder in a variable and use it throughout my script.
Here's the program without the LOOP, it works without any errors. Maybe it helps to understand better.
require_once('Classes/PHPExcel.php');
$inputfilename = 'test2.xls';
$outputfilename = 'convert.csv';
//Usage:
convertXLStoCSV($inputfilename, $outputfilename);
function convertXLStoCSV($infile, $outfile)
{
$fileType = PHPExcel_IOFactory::identify($infile);
$objReader = PHPExcel_IOFactory::createReader($fileType);
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load($infile);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
$objWriter->save($outfile);
}
Create the function outside of foreach and call it inside like below:
function convertXLStoCSV($infile, $outfile)
{
$fileType = PHPExcel_IOFactory::identify($infile);
$objReader = PHPExcel_IOFactory::createReader($fileType);
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load($infile);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
$objWriter->save($outfile);
}
$dir = "uploads/*";
foreach(glob($dir) as $file)
{
if(!is_dir($file)) { echo basename($file)."\n";}
//--------------------------
$nameAsString = (string)$file;
require_once('Classes/PHPExcel.php');
$inputfilename = $nameAsString;
$outputfilename = 'convert.csv';
//Usage:
convertXLStoCSV($inputfilename, $outputfilename);
}
function convertXLStoCSV($infile, $outfile)
{
$fileType = PHPExcel_IOFactory::identify($infile);
$objReader = PHPExcel_IOFactory::createReader($fileType);
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load($infile);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
$objWriter->save($outfile);
}
convertXLStoCSV($inputfilename, $outputfilename);
declare the function before using it
I am developing a page where emails sent from myself are updating a webpage.
Steps:
Email sent by me -> Website opened -> Script takes attachments from email -> script converts all .xls .xlsx to .csv, than parses to db for update
However, my code runs through the while loop (labeled in code) 6-8 times when it should only be going once! Why?
Code:
<?php
require_once('Classes/PHPExcel/IOFactory.php');
require('includes/email.php');
$dir = 'excels/';
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) { //*THIS WHILE LOOP*//
//echo "yes";
if(filetype($dir . $file) == 'dir') {
continue; }
$ext = substr($file, -3);
if($ext == 'xls') {
$inputFileType = 'Excel5';
$inputFileName = $dir . $file;
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcelReader = $objReader->load($inputFileName);
$loadedSheetNames = $objPHPExcelReader->getSheetNames();
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcelReader, 'CSV');
$objWriter->save(str_replace('.xls', '.csv', $inputFileName));
$objWriter->save('abc.csv');
$direct = "excels/" .$file;
$files = fopen('abc.csv', 'r');
while (($line = fgetcsv($files)) !== FALSE) {
$csv_array[] = array_combine(range(1, count($line)), array_values($line));
}
$file2 = str_replace('.xls', '.csv', $file);
$oldname = "excels/" .$file;
$newname = "excels/archives/" .$file2;
rename($oldname, $newname);
$delete = unlink($direct);
//echo 'Your .xls file was uploaded successfully. Have a nice day.';
} elseif($ext == 'csv'){
$inputFileType = 'CSV';
$inputFileName = $dir . $file;
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcelReader = $objReader->load($inputFileName);
$loadedSheetNames = $objPHPExcelReader->getSheetNames();
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcelReader, 'CSV');
$objWriter->save('abc.csv');
$files = fopen('abc.csv', 'r');
while (($line = fgetcsv($files)) !== FALSE) {
$csv_array[] = array_combine(range(1, count($line)), array_values($line));
}
//echo 'Your .csv file was uploaded successfully. Have a nice day.';
} elseif($ext == 'lsx') {
$inputFileType = 'Excel2007';
$inputFileName = $dir . $file;
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcelReader = $objReader->load($inputFileName);
$loadedSheetNames = $objPHPExcelReader->getSheetNames();
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcelReader, 'CSV');
$objWriter->save(str_replace('.xlsx', '.csv', $inputFileName));
$objWriter->save('abc.csv');
$files = fopen('abc.csv', 'r');
while (($line = fgetcsv($files)) !== FALSE) {
$csv_array[] = array_combine(range(1, count($line)), array_values($line));
}
//echo 'Your .xlsx file was uploaded successfully. Have a nice day.';
}
else {
//echo "This is not an accepted file type. Please save as either '*.csv' or '*.xls' and re-upload.";
}
I am having admins update a website by uploading .xlsx .xls or .csv files into an HTML form. The issue is that the second worksheet, NORTH, isn't being saved into the server with the first worksheet, SOUTH.
My Code:
<?php
require('./Classes/PHPExcel/IOFactory.php');
ini_set('max_execution_time', 800);
ini_set('memory_limit', 200M);
$inputFileType = 'Excel2007';
$inputFileName = $_FILES['uploaded']['tmp_name'];
class MyReadFilter implements PHPExcel_Reader_IReadFilter {
public function __construct($fromColumn, $toColumn) {
$this->columns = array();
$toColumn++;
while ($fromColumn !== $toColumn) {
$this->columns[] = $fromColumn++;
}
}
public function readCell($column, $row, $worksheetName = '') {
// Read columns from 'A' to 'AF'
if (in_array($column, $this->columns)) {
return true;
}
return false;
}
}
$filterSubset = new MyReadFilter('A', 'AF');
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objReader->setReadFilter($filterSubset);
$objReader->setLoadSheetsOnly( array("SOUTH", "NORTH") );
$objPHPExcelReader = $objReader->load($inputFileName);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcelReader, 'CSV');
$objWriter->save('abc.csv');
$files = fopen('abc.csv', 'r');
while (($line = fgetcsv($files)) !== FALSE) {
$csv_array[] = array_combine(range(1, count($line)), array_values($line));
}
?>
What have I done wrong that won't allow my code to save both worksheets? TIA!
A CSV file can only hold a single worksheet, so you need to save each worksheet to a separate file
$objReader->setLoadSheetsOnly( array("SOUTH", "NORTH") );
$objPHPExcelReader = $objReader->load($inputFileName);
for ($ws = 0; $ws < $objPHPExcelReader->getSheetCount(); $ws++) {
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcelReader, 'CSV');
$objWriter->setSheetIndex($ws);
$objWriter->save('abc' .$ws. '.csv');
}
I am in searching to find a solution to convert the .xlsx(Excel) file into pdf files.
require_once('phpExcel/PHPExcel/IOFactory.php');
require_once('phpexcel/PHPExcel.php');
$fileType = 'Excel5';
$fileName = 'testing.xlsx';
$outputFileType = 'PDF';
$outputFileName = 'test.pdf';
$objPHPExcel = PHPExcel_IOFactory::load($fileName);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, $outputFileType);
$objWriter->writeAllSheets();
$objWriter->save($outputFileName);
I used this above code,but is not working. If any can an Idea, please help me
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 :)