【问题标题】:How to convert the date while importing Excel sheet to the database?将Excel工作表导入数据库时​​如何转换日期?
【发布时间】:2011-07-28 05:53:52
【问题描述】:

我有一个格式为 01-Mar-10 的 Excel 工作表。当我将该 csv 文件导入我的数据库时,它存储为 0000-00-00。导入时如何转换日期格式,或者有其他方法吗?

这是我用来导入数据库的代码

        $databasetable = "sample";
        $fieldseparator = ",";
        $lineseparator = "\n";
        $csvfile = "../uploads/" . basename( $_FILES['file']['name']); 
        $addauto = 0;
        $save = 1;
        $outputfile = "../temp/output.sql";
        if(!file_exists($csvfile)) {
            #echo $csvfile;
            echo "File not found. Make sure you specified the correct path.\n";
            return 0;
            exit;
        }

        $file = fopen($csvfile,"r");

        if(!$file) {
            #echo "Error opening data file.\n";
            return 0;
            exit;
        }

        $size = filesize($csvfile);

        if(!$size) {
            echo "File is empty.\n";
            return 0;
            exit;
        }

        $csvcontent = fread($file,$size);

        fclose($file);

        $lines = 0;
        $queries = "";
        $linearray = array();

        foreach(split($lineseparator,$csvcontent) as $line) {
            $lines++;
            $line = trim($line," \t");
            $line = str_replace("\r","",$line);
            $line = str_replace("'","\'",$line);
            $linearray = explode($fieldseparator,$line);
            $linemysql = implode("','",$linearray);
            if($addauto)
                $query = "insert into $databasetable values('','$linemysql');";
            else
                $query = "insert into $databasetable values('$linemysql');";
            $queries .= $query . "\n";
            @mysql_query($query);

【问题讨论】:

    标签: php mysql database excel import


    【解决方案1】:
    $d = "01-Mar-10";
    $in_db = date('Y-m-d', strtotime($d));
    echo $in_db;
    

    输出:

    2010-03-01
    

    使用date() 转换来获得有效的日期格式以存储在数据库中。使用strtotime()将excel日期格式转换为时间戳。

    将数据分解到$linearray后使用

    $linearray[ID]=date('Y-m-d', strtotime($linearray[ID]));
    

    将其值更改为正确的格式。将 ID 替换为具有日期字段的元素的数组索引。

    【讨论】:

      【解决方案2】:
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-05
      • 1970-01-01
      相关资源
      最近更新 更多