我正在尝试读取excel文件(即xls)并将数据导入mysql数据库并使用codeigniter 2.0.1框架。
以下是生成查询的代码
public function read_file($table = 'organization', $filename = 'test.xls') {
$pathToFile = './uploads/' . $filename;
$this->load->library('Spreadsheet_Excel_Reader');
$data = new Spreadsheet_Excel_Reader($pathToFile);
$sql = "INSERT INTO $table (";
for($index = 1;$index <= $data->sheets[0]['numCols']; $index++){
$sql.= strtolower($data->sheets[0]['cells'][1][$index]) . ", ";
}
$sql = rtrim($sql, ", ")." ) VALUES ( ";
for ($i = 2; $i <= $data->sheets[0]['numRows']; $i++) {
for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) {
$sql .= "\"" . $data->sheets[0]['cells'][$i][$j] . "\", ";
}
echo rtrim($sql, ", ")." ) <br>";
}
}
循环中生成的值是重复的,我无法找到循环的问题...
以下是运行上述功能后的结果:
INSERT INTO organization (userid, datestamp, kata, kaya, kaya_zenye_vuoo, vyoo_vyenye_bamba, mifuniko, matumizi_mifuniko, uzuiaji_inzi, usafishikaji_sakafu, usitiri, uezekaji, milango_inayofungika, harufu, wadudu, sabuni, maji, vibuyuchirizi ) VALUES ( "mpwapwa@live.com", "2011-04-10 08:21", "Chunyu", "2", "4", "5", "3", "56", "5", "6", "8", "45", "7", "8", "9", "8", "9", "8" )
INSERT INTO organization (userid, datestamp, kata, kaya, kaya_zenye_vuoo, vyoo_vyenye_bamba, mifuniko, matumizi_mifuniko, uzuiaji_inzi, usafishikaji_sakafu, usitiri, uezekaji, milango_inayofungika, harufu, wadudu, sabuni, maji, vibuyuchirizi ) VALUES ( "mpwapwa@live.com", "2011-04-10 08:21", "Chunyu", "2", "4", "5", "3", "56", "5", "6", "8", "45", "7", "8", "9", "8", "9", "8", "annie@yahoo.com", "2011-04-10 08:21", "Chunyu", "2", "4", "5", "3", "56", "5", "6", "8", "45", "7", "8", "9", "8", "9", "8" )
INSERT INTO organization (userid, datestamp, kata, kaya, kaya_zenye_vuoo, vyoo_vyenye_bamba, mifuniko, matumizi_mifuniko, uzuiaji_inzi, usafishikaji_sakafu, usitiri, uezekaji, milango_inayofungika, harufu, wadudu, sabuni, maji, vibuyuchirizi ) VALUES ( "mpwapwa@live.com", "2011-04-10 08:21", "Chunyu", "2", "4", "5", "3", "56", "5", "6", "8", "45", "7", "8", "9", "8", "9", "8", "annie@yahoo.com", "2011-04-10 08:21", "Chunyu", "2", "4", "5", "3", "56", "5", "6", "8", "45", "7", "8", "9", "8", "9", "8", " sam@yahoo.com", "2011-04-10 08:21", "Chunyu", "2", "4", "5", "3", "56", "5", "6", "8", "45", "7", "8", "9", "8", "9", "8" )
很抱歉,由于我是新手,我无法发布图片。
提前完成..推荐
答案 0 :(得分:1)
我无法测试,但......:
public function read_file($table = 'organization', $filename = 'test.xls') {
$pathToFile = './uploads/' . $filename;
$this->load->library('Spreadsheet_Excel_Reader');
$data = new Spreadsheet_Excel_Reader($pathToFile);
$sql = "INSERT INTO $table (";
for($index = 1;$index <= $data->sheets[0]['numCols']; $index++){
$sql.= strtolower($data->sheets[0]['cells'][1][$index]) . ", ";
}
$sql = rtrim($sql, ", ")." ) VALUES ( ";
for ($i = 2; $i <= $data->sheets[0]['numRows']; $i++) {
$valuesSQL = '';
for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) {
$valuesSql .= "\"" . $data->sheets[0]['cells'][$i][$j] . "\", ";
}
echo $sql . rtrim($valuesSql, ", ")." ) <br>";
}
}