使用php将上传的Excel文件转换为csv [英] Convert uploaded excel file to csv using php
问题描述
我正在尝试使用php创建一个网页,该网页使用浏览按钮将excel文件上传到页面上,并将其导入到mysql数据库中.
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.
我能够上传csv文件并将其导入数据库中
I am able to upload csv file and import it in database
//html代码
<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代码
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");
//代码的另一部分
if($sql) {
$ffilename=basename($_FILES['file']['name']);
$filename=preg_replace('/\\.csv/',' ',$ffilename);
echo "File ".$filename." imported in database";
}
我想上传excel文件并将其转换为csv,而无需按任何额外的按钮,并对我一直使用的csv文件使用相同的代码,即csv文件虽然将被导入,但是excel文件将被上传.
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.
推荐答案
您可以使用 Github:PHPOffice/PhpSpreadsheet 是 Github:PHPOffice/PHPExcel
使用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");
输入文件test.xls
input file test.xls
输出文件text.csv
output file text.csv
您还可以参考如何使用PHP将Excel XLS转换为CSV
这篇关于使用php将上传的Excel文件转换为csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!