douciping4283 2019-07-12 14:44
浏览 219
已采纳

如何防止PHP excel导入删除列中的前导零?

I tried a tutorial here in https://phppot.com/php/import-excel-file-into-mysql-database-using-php/ to import XLSX file to my database (using PHP)

But the problem is, if the column value started with leading zero, after import, I found out that the leading zero was removed.

How to prevent this?

By the way, my phpmyadmin table for that particular column to be imported is structured as Text column, not integer

I've tried adding '' to treat the file as string but shows no success

$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.";
  }
}
  • 写回答

1条回答 默认 最新

  • dongnao2582 2019-07-12 15:25
    关注

    Add a leading apostrophe (only if $description starts with a 0, of course), it will force Excel to read the cell as a text.

    if ($description[0] === '0') {
        $description = "'" . $description;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?