doushi3322 2012-11-21 13:48
浏览 25

阅读excel数据并以下面的格式插入

I have data in excel sheet which looks like below.

enter image description here

I have to read the data(i'll try csv format, please suggest otherwise). Using PHP to read data...

Create two tables, hopefully like below.

1.

enter image description here

2.

enter image description here

  1. I am expecting ExtJs tree like this.

enter image description here

I am having trouble in step 1. How shall I read my excel sheet, csv file so that database is updated like table 1

  • 写回答

2条回答 默认 最新

  • douzhui8531 2012-11-21 14:30
    关注

    Here's a solution, though I did not maintain the same Data_Id's as you did (you seem to increment the id by depth and node, but I just used the row number).

    <?php
    $data = <<<EOT
    Eatables,,
    ,Fruits,
    ,,Apple
    ,,Mango
    ,Vegetables,
    ,,Tomatoes
    ,,Potatoes
    EOT;
    
    $mysqli = new mysqli("localhost", "username", "password", "test");
    
    $dataInsertStatement = $mysqli->prepare("INSERT INTO Data (Data_Id, Data_Value) VALUES (?, ?)");
    $treeInsertStatement = $mysqli->prepare("INSERT INTO Tree (parent_id, child_id) VALUES (?, ?)");
    
    $lines = explode("
    ", $data);
    
    $path = array();
    
    foreach ($lines as $rowNum => $line) {
        // convert line of csv to array
        $row = str_getcsv($line);
        // loop through the row's fields and find the one that's not empty
        foreach ($row as $column => $value) {
            if (!empty($value)) {
                // use row number + 1 as $Data_Id
                $Data_Id = $rowNum + 1;
    
                // track our depth in the tree
                $path[$column] = $Data_Id;
    
                // insert the data
                $dataInsertStatement->bind_param('is', $Data_Id, $value);
                $dataInsertStatement->execute();
    
                // check if this node has a parent
                if (isset($path[$column - 1])) {
                    // connect this node to its parent in the tree
                    $treeInsertStatement->bind_param('ii', $path[$column - 1], $Data_Id);
                    $treeInsertStatement->execute();
                }
    
                continue;
            }
        }
    }
    
    $mysqli->close();
    
    评论

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)