首先需要安装Laravel Excel
,安装方法详见:http://www.maatwebsite.nl/laravel-excel/docs/getting-started#installation
我的excel文件格式如下:
商品货号(编号) | 入库数量 |
---|---|
KS000341 | 4 |
KS000342 | 5 |
KS000343 | 6 |
KS000344 | 7 |
代码如下:
Excel::load($tmp_file, function($reader) {
$reader = $reader->getSheet(0);
//获取表中的数据
$results = $reader->toArray();
foreach ($results as $key => $value) {
echo '<BR><BR>goods_sn:'.$value[0];
echo '<BR>storage_num:'.$value[1];
}
dd($results);
});
其中,tmp_file为文件的路径。
显示效果如图:
这种方法是从文件的第一行数据开始读,一直读取到最后。每行的数据在转化的数组里的下标都是按照先后顺序从零开始的。
其实还有两位两种方法读取excel文件的方法,只是对文件的格式需要变化,如:
goods_sn | storage_num |
---|---|
KS000341 | 4 |
KS000342 | 5 |
KS000343 | 6 |
KS000344 | 7 |
方法一、
代码:
$reader->each(function($sheet) { //这里是按行循环读取每一行的数据
echo "<BR>goods_sn:".$sheet['goods_sn'];
echo "<BR>storage_num:".$sheet['storage_num'];
// Loop through all rows
$sheet->each(function($value) { //这里循环每行的每个字段value
echo '<BR>value:'.$value;
});
echo '<BR><BR>';
});
结果:
goods_sn:KS000341
storage_num:4
value:KS000341
value:4
goods_sn:KS000342
storage_num:5
value:KS000342
value:5
goods_sn:KS000343
storage_num:6
value:KS000343
value:6
goods_sn:KS000344
storage_num:7
value:KS000344
value:7
说明:这种方法是从第二行开始读取的,第一行的数据作为没列的下标。
方法二、
代码:
$results = $reader->get()->toArray();
foreach ($results as $val) {
// 进行数据操作
// dd($val);
echo '<BR><BR>goods_sn:'.$val['goods_sn'];
echo '<BR>storage_num:'.$val['storage_num'];
}
dd($results);
结果:
goods_sn:KS000341
storage_num:4
goods_sn:KS000342
storage_num:5
goods_sn:KS000343
storage_num:6
goods_sn:KS000344
storage_num:7
array:4 [▼
0 => array:2 [▼
"goods_sn" => "KS000341"
"storage_num" => 4.0
]
1 => array:2 [▼
"goods_sn" => "KS000342"
"storage_num" => 5.0
]
2 => array:2 [▼
"goods_sn" => "KS000343"
"storage_num" => 6.0
]
3 => array:2 [▼
"goods_sn" => "KS000344"
"storage_num" => 7.0
]
]
Author:leedaning
本文地址:http://blog.csdn.net/leedaning/article/details/53841995