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

时间:2012-11-21 13:48:03

标签: php mysql excel csv

我在excel表中有数据,如下所示。

enter image description here

我必须阅读数据(我会尝试csv格式,请另行建议)。使用PHP读取数据......

创建两个表,希望如下所示。

1

enter image description here

2

enter image description here

  1. 我期待这样的ExtJs树。
  2. enter image description here

    我在第1步遇到问题。如何阅读我的Excel工作表csv文件,以便更新数据库,如表1

2 个答案:

答案 0 :(得分:1)

这是一个解决方案,虽然我没有像你那样保持相同的Data_Id(你似乎按深度和节点增加了id,但我只是使用了行号)。

<?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("\n", $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();

答案 1 :(得分:1)

类似

lastvalues=array(); // To hold the last value on each level
data=array();
foreach($lines as $i=>$line){
  elems=explode(',',$line);
  foreach($elems as $n=>$e){
     if($e>''){
        $data[$i]=$e;
        lastvalues[$n]=$i;
        if($n){ // makes no sense for 0th level
           $tree[]=array('parent'=>$lastvalues[$n-1],child=>$i);
        }
     }
  }
}

应该为您提供数据结构。您可以使用SQL插入而不是$ data和$ tree数组。