douping7105 2016-05-16 11:38
浏览 32

PHP mysql通过excel导入数据

I want to import data using php mysql from excel sheet containing 1.6 million records. What is the best way to do this?

this is the sample code I have used to iterate excel file and insert data in database:

public function iterateData($file_name) {
        $fileDirectory = '';
        $file_name = $fileDirectory . $file_name;
        if (file_exists($file_name)) {
            $this->truncateTable();
            include 'PHPExcel2/Classes/PHPExcel/IOFactory.php';
            $objReader = PHPExcel_IOFactory::createReader('Excel2007');
            $objPHPExcel = $objReader->load($file_name);
            $count = 1;
            foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
                foreach ($worksheet->getRowIterator() as $row) {
                    $cellIterator = $row->getCellIterator();
                    $cellIterator->setIterateOnlyExistingCells(true); // Loop all cells, even if it is not set
                    $cellValues = array();
                    foreach ($cellIterator as $cell) {
                        if (!is_null($cell)) {
                            $cellValues[] = $cell->getCalculatedValue();
                        }
                    }
                    if (isset($cellValues[0]) && $cellValues[0] != 'Product' && $cellValues[0] != '') {
                        $this->inserInDatabase($cellValues);
                    } elseif (empty($cellValues[0]) && empty($cellValues[1]) && empty($cellValues[2])) {
                        continue;
                    }
                }
                if ($objPHPExcel->getSheetCount() == $count) {
                    return TRUE;
                }
                $count++;
            }
        } else {
            return FALSE;
        }
    } private function inserInDatabase($data) {
        $dbDetails = array(
            'db_name' => '*',
            'db_pass' => '*',
            'db_host' => 'localhost',
            'db_user' => '*'
        );
        $dbh = dbConnect::connect($dbDetails);
        $date = date('Y-m-d H:i:s');
        $sql = "INSERT INTO product_description (product_id, prpoduct_description, price, created_date) values ('" . mysql_escape_string($data[0]) . "', '" . mysql_escape_string($data[1]) . "', '" . mysql_escape_string($data[2]) . "', '$date')";
        if (!$dbh->dbh->query($sql)) {
            die('Database Connection Failed.');
        }
    }
  • 写回答

2条回答 默认 最新

  • dongre6270 2016-05-16 11:40
    关注

    export you excel data to csv format, and then import the csv format to mysql

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起