4

I am trying to create a webpage using php which uploads excel file on the page using browse button and imports it into mysql database.

I am able to upload csv file and import it in database

//html code

<form action="import.php" enctype="multipart/form-data" method="post"
role="form">
<input type="file" name="file" id="file" accept=".xls">
<br><br>
<input type="submit" name="submit" value="submit">

//php code

 if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
 } 
 echo nl2br("Connected to Database successfully \n");
 mysqli_query($conn,'Truncate table sheet');
 $file = $_FILES['file']['tmp_name'];
 file_put_contents($file,str_replace("'","\'",file_get_contents($file)));
 $handle = fopen($file,"r");

// another part of code

 if($sql) {
     $ffilename=basename($_FILES['file']['name']);
     $filename=preg_replace('/\\.csv/',' ',$ffilename);
     echo "File ".$filename." imported in database";
 } 

I want to upload excel file and convert it to csv without pressing any extra button and use the same code for csv file which i have been using , i.e csv file while will be imported but excel file will be uploaded.

LF00
  • 27,015
  • 29
  • 156
  • 295

2 Answers2

1

You can use Github: PHPOffice/PhpSpreadsheet which is the successor of Github: PHPOffice/PHPExcel

install it with composer require phpoffice/phpspreadsheet

require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

$reader = new Xls();
$spreadsheet = $reader->load("test.xls");
$writer = new Csv($spreadsheet);
$writer->save("test.csv");

input file test.xls
enter image description here

output file text.csv
enter image description here


You may also refer to How to convert Excel XLS to CSV using PHP

LF00
  • 27,015
  • 29
  • 156
  • 295
  • Thank-you for your reply, but can u suggest a method where composer wont be required as in my system composer is not installing showing i tried a lot to solve the error but its not solving. – Jessica Gonsalves Aug 16 '19 at 13:10
-1

Also you can try to use https://developers.convertio.co/ru/api/docs/ to save some time with .xlsx file mess and simply use side project API.

I tried to make such things on PHP only but finally after hours spent on document aspects and deprecated libraries used Convertio.

*not paid by Convertio

Tesmen
  • 559
  • 1
  • 6
  • 21