导出Excel(CSV):二十万数据导出大概需要2到3秒。
<?php
/** * 导出excel(csv)
* @data 导出数据
* @headlist 第一行,列名
* @fileName 输出Excel文件名
*/
function csv_export($data = array(), $headlist = array(), $fileName) {
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$fileName.'.csv"');
header('Cache-Control: max-age=0');
//打开PHP文件句柄,php://output 表示直接输出到浏览器
$fp = fopen('php://output', 'a');
//输出Excel列名信息
foreach ($headlist as $key => $value) {
//CSV的Excel支持GBK编码,一定要转换,否则乱码
$headlist[$key] = iconv('utf-8', 'gbk', $value);
}
//将数据通过fputcsv写到文件句柄
fputcsv($fp, $headlist);
//计数器
$num = 0;
//每隔$limit行,刷新一下输出buffer,不要太大,也不要太小
$limit = 100000;
//逐行取出数据,不浪费内存
$count = count($data);
for ($i = 0; $i < $count; $i++) {
$num++;
//刷新一下输出buffer,防止由于数据过多造成问题
if ($limit == $num) {
ob_flush();
flush();
$num = 0;
}
$row = $data[$i];
foreach ($row as $key => $value) {
$row[$key] = iconv('utf-8', 'gbk', $value);
}
fputcsv($fp, $row);
}
}
$data = array(
array(
'name' => 'jake',
'score' => 80,
'grade' => 'A'
),
array(
'name' => 'jin',
'score' => 70,
'grade' => 'A'
),
array(
'name' => 'john',
'score' => 80,
'grade' => 'A'
),
array(
'name' => 'ben3',
'score' => 203,
'grade' => 'B3'
)
);
$titleList = array('姓名', '总分', '等级');
$fileName = '高三(3)班 7 月份考试结果';
csv_export($data, $titleList, $fileName);
CSV数据导入
<?php
/**
* 导入Excel数据表格
* @param string $fileName 文件名
* @param int $line 读取几行,默认全部读取
* @param int $offset 从第几行开始读,默认从第一行读取
* @return bool|array
*/
function importCsv($fileName, $line=0, $offset=0){
//set_time_limit(0);//防止超时
//ini_set("memory_limit", "512M");//防止内存溢出
$handle = fopen($fileName,'r');
if(!$handle){
return '文件打开失败';
}
$i = 0;
$j = 0;
$arr = [];
while($data = fgetcsv($handle)){
//小于偏移量则不读取,但$i仍然需要自增
if($i < $offset && $offset){
$i++;
continue;
}
//大于读取行数则退出
if($i > $line && $line){
break;
}
foreach ($data as $key => $value) {
$content = iconv("gbk","utf-8//IGNORE",$value);//转化编码
$arr[$j][] = $content;
}
$i++;
$j++;
}
return $arr;
}
$arr = importCsv("高三(3)班 7 月份考试结果.csv");
var_dump($arr);