初始化仓库
This commit is contained in:
74
common/services/ExportService.php
Normal file
74
common/services/ExportService.php
Normal file
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
namespace common\services;
|
||||
class ExportService
|
||||
{
|
||||
//导出
|
||||
public function export($headlist,$Name,$class)
|
||||
{
|
||||
ini_set("memory_limit", "2048M");
|
||||
set_time_limit(0);
|
||||
$params = \Yii::$app->request->post();
|
||||
|
||||
$data = $class->inventory($params);
|
||||
//设置导出的文件名
|
||||
$fileName = iconv('utf-8', 'gbk', "$Name" . date("Y-m-d"));
|
||||
header('Content-Type: application/vnd.ms-excel');
|
||||
//指明导出的格式
|
||||
header('Content-Disposition: attachment;filename="' . $fileName . '.xsl"');
|
||||
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] = $value;
|
||||
}
|
||||
//将数据通过fputcsv写到文件句柄
|
||||
fputcsv($fp, $headlist);
|
||||
//每隔$limit行,刷新一下输出buffer,不要太大,也不要太小
|
||||
$limit = 100000;
|
||||
//逐行取出数据,不浪费内存
|
||||
|
||||
foreach ($data as $k => $v) {
|
||||
//刷新一下输出buffer,防止由于数据过多造成问题
|
||||
if ($k % $limit == 0 && $k != 0) {
|
||||
ob_flush();
|
||||
flush();
|
||||
}
|
||||
$row = $data[$k];
|
||||
foreach ($row as $key => $value) {
|
||||
$row[$key] = $value;
|
||||
}
|
||||
fputcsv($fp, $row);
|
||||
}
|
||||
}
|
||||
|
||||
public static function ExportByCors($parameter)
|
||||
{
|
||||
ini_set("memory_limit", "2048M");
|
||||
set_time_limit(0);
|
||||
if (is_array($parameter)) {
|
||||
$filename = date('Y-m-d_H-i-s') . '.csv';
|
||||
// header('Content-Type: application/vnd.ms-excel');
|
||||
header('Content-Type: application/json');
|
||||
header('Access-control-Allow-Origin:*');
|
||||
header("Content-Disposition: attachment;filename=$filename");
|
||||
header('Cache-Control: max-age=0');
|
||||
$fp = fopen('php://output', 'w');
|
||||
fwrite($fp,chr(0xEF).chr(0xBB).chr(0xBF));
|
||||
if ( ! empty($parameter['header']) && is_array($parameter['header'])) {
|
||||
fputcsv($fp, $parameter['header']);
|
||||
}
|
||||
if (isset($parameter['data'])) {
|
||||
foreach ($parameter['data'] as $row) {
|
||||
fputcsv($fp, $row);
|
||||
}
|
||||
exit();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
// throw new \yii\web\HttpException(500, "Not a valid parameter!");
|
||||
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user