我在https://phppot.com/php/import-excel-file-into-mysql-database-using-php/中尝试了一个教程,用于将XLSX文件导入到我的数据库中(使用PHP)
但是问题是,如果列值以前导零开头,那么在导入后,我发现前导零已被删除。
如何防止这种情况?
顺便说一下,我要导入的特定列的phpmyadmin表被构造为文本列,而不是整数
我尝试添加”以将文件视为字符串,但未成功
$conn = mysqli_connect("localhost","root","test","phpsamples");
require_once('vendor/php-excel-reader/excel_reader2.php');
require_once('vendor/SpreadsheetReader.php');
if (isset($_POST["import"]))
{
$allowedFileType = ['application/vnd.ms-excel','text/xls','text/xlsx','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
if(in_array($_FILES["file"]["type"],$allowedFileType)){
$targetPath = 'uploads/'.$_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $targetPath);
$Reader = new SpreadsheetReader($targetPath);
$sheetCount = count($Reader->sheets());
for($i=0;$i<$sheetCount;$i++)
{
$Reader->ChangeSheet($i);
foreach ($Reader as $Row)
{
$name = "";
if(isset($Row[0])) {
$name = mysqli_real_escape_string($conn,$Row[0]);
}
$description = "";
if(isset($Row[1])) {
$description = mysqli_real_escape_string($conn,$Row[1]);
}
if (!empty($name) || !empty($description)) {
$query = "insert into tbl_info(name,description) values('".$name."','".$description."')";
$result = mysqli_query($conn, $query);
if (! empty($result)) {
$type = "success";
$message = "Excel Data Imported into the Database";
} else {
$type = "error";
$message = "Problem in Importing Excel Data";
}
}
}
}
}
else
{
$type = "error";
$message = "Invalid File Type. Upload Excel File.";
}
}
答案 0 :(得分:0)
添加前导撇号(当然,$description
仅以0
开头),它将强制Excel将单元格读取为文本。
if ($description[0] === '0') {
$description = "'" . $description;
}