将Excel文件上传到数据库
答
对于客户端网页端,使用html格式<input type="file">
将excel文件从浏览器上传到PHP文件。
示例性上传-submit.html:
<form action="upload.php">
<input type="file" name="excel-upload" />
<input type="submit" />
</form>
在你的PHP上传脚本,您将需要包括PHPExcel库(https://github.com/PHPOffice/PHPExcel)来读取和解析上传的Excel文件。您可以阅读马克·贝克对很好的例子,如何从Excel中读取并插入到数据库中:how to use phpexcel to read data and insert into database?
upload.php的例子:
// Include PHPExcel_IOFactory
include 'PHPExcel/IOFactory.php';
// Move the uploaded file from temporary server directory into an 'uploads' directory
$fileName = basename($_FILES["excel-upload"]["name"]);
$uploadedExcelFullPath = __DIR__.'/uploads/'.$fileName;
move_uploaded_file($_FILES['excel-upload']['tmp_name'],$uploadedExcelFullPath);
// Read your Excel workbook
try {
$inputFileType = PHPExcel_IOFactory::identify($uploadedExcelFullPath);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($uploadedExcelFullPath);
} catch(Exception $e) {
die('Error loading file "'.pathinfo($uploadedExcelFullPath,PATHINFO_BASENAME).'": '.$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 row data array into your database here
// You can also format data into HTML table row format and echo out here
var_dump($rowData);
}
是的,它是可能的;你可以发布你的代码,你尝试过吗? –
我还没试过这个,我试过的那个是导入数据。我目前正在寻找一些关于如何做到这一点的教程。 – keme