作者 SHW\戥岁。。

批量导出

... ... @@ -306,227 +306,6 @@ class Fastexport extends Backend
}
/**
* 执行自定义导出
* @param int $task_id 任务ID
* @param int $subtask_id 子任务ID
* @param boolean $direct_export 是否直接反回文件
*/
public function zdyTask()
{
$task_id = 1;
$subtask_id = 1;
$direct_export = true;
\think\Config::set('default_return_type', 'json');
$row = $this->model->get($task_id);
if (!$row) {
$this->error(__('No Results were found'));
}
if (isset($row['subtask'][$subtask_id]) && is_array($row['subtask'][$subtask_id])) {
$subtask = $row['subtask'][$subtask_id];
$task_name = $row['name'];
} else {
$this->result(['subtask_id' => $subtask_id], 0, '子任务找不到啦~', 'json');
}
set_time_limit(0);// 脚本执行时间限制
ini_set('memory_limit', $row['memory_limit'] . 'M');// 脚本内存限制
$ExportLib = new ExportLib($row);
unset($row);
// 检查任务状态
if (!$direct_export) {
if ($subtask['status'] == 1) {
$this->result(['subtask_id' => $subtask_id], 0, '此子任务正在执行中~', 'json');
} else if ($subtask['status'] == 2) {
if (file_exists($this->save_dir . $task_id . DS . $subtask_id . '.xlsx')) {
$this->result(['subtask_id' => $subtask_id], 1, '此子任务已经处理过啦~', 'json');
}
}
}
$spreadsheet = new Spreadsheet();
$worksheet = $spreadsheet->getActiveSheet();
$worksheet->setTitle($task_name);
//设置表头
$head = $ExportLib->getXlsTitle();
$head_count = count($head);
for ($i = 0; $i < $head_count; $i++) {
$worksheet->setCellValueByColumnAndRow($i + 1, 1, $head[$i]);
}
// 写人数据
try {
$data = Db::query($subtask['sql']);
} catch (PDOException $e) {
$this->result([
'subtask_id' => $subtask_id,
'error_msg' => $e->getMessage(),
], 0, '任务失败!', 'json');
}
$y = 2;
foreach ($data as $row_key => $row) {
$i = 1;
foreach ($ExportLib->fields as $key => $value) {
$field = $value['field'];
if ($value['discerns'] == 0) {
// 文本
$worksheet->setCellValueByColumnAndRow($i, $y, $row[$field], DataType::TYPE_STRING);
} else if ($value['discerns'] == 1) {
// 数字
$worksheet->setCellValueByColumnAndRow($i, $y, $row[$field] . "\t");
} else if ($value['discerns'] == 2) {
// 日期时间
if ($row[$field]) {
$excelDateValue = date('Y-m-d H:i:s', $row[$field]);
$worksheet->setCellValueByColumnAndRow($i, $y, $excelDateValue, DataType::TYPE_STRING);
/*$excelDateValue = PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExcel( $row[$field] );
if ($excelDateValue) {
// 以日期日期格式写入,没区别,有需要的可以打开
$worksheet->setCellValueByColumnAndRow($i, $y, $excelDateValue);
$worksheet->getStyleByColumnAndRow($i,$y)
->getNumberFormat()
->setFormatCode('yyyy-mm-dd h:mm:ss');
$worksheet->getStyleByColumnAndRow($i,$y)->getFont()->setBold(true);
$worksheet->getStyleByColumnAndRow($i,$y)->getFont()->setBold(false);
}*/
} else {
$worksheet->setCellValueByColumnAndRow($i, $y, '-', DataType::TYPE_STRING);
}
} else if ($value['discerns'] == 3) {
// 图片-太慢,太耗资源,弃用
/*$file_info = pathinfo($row[$field]);
$coorrow = $worksheet->getCellByColumnAndRow($i, $y)->getRow();
$coorcolumn = $worksheet->getCellByColumnAndRow($i, $y)->getColumn();
if ($y == 2) {
$worksheet->getColumnDimension($coorcolumn)->setWidth(8);
}
$worksheet->getRowDimension($coorrow)->setRowHeight(40);
if (!empty($file_info['basename'])) {
$basename = $file_info['basename'];
$drawing = new Drawing();
$drawing->setName('图片');
$drawing->setPath($remote_save_dir . $row[$field]);
$drawing->setWidth(40);
$drawing->setHeight(40);
$drawing->setCoordinates($coorcolumn . $coorrow);
$drawing->setWorksheet($worksheet);
} else {
$worksheet->setCellValueByColumnAndRow($i, $y, $row[$field], DataType::TYPE_STRING);
}*/
// 以链接导出图片
$field_value = cdnurl($row[$field], true);
$worksheet->setCellValueByColumnAndRow($i, $y, $field_value, DataType::TYPE_STRING);
$worksheet->getCellByColumnAndRow($i, $y)->getHyperlink()->setUrl($field_value);
} else if ($value['discerns'] == 4) {
// 文件
$field_value = cdnurl($row[$field], true);
$worksheet->setCellValueByColumnAndRow($i, $y, $field_value, DataType::TYPE_STRING);
$worksheet->getCellByColumnAndRow($i, $y)->getHyperlink()->setUrl($field_value);
} else if ($value['discerns'] == 5) {
// 赋值
$field_value = $ExportLib->assignment($row[$field], $value['scheme']);
$worksheet->setCellValueByColumnAndRow($i, $y, $field_value, DataType::TYPE_STRING);
}
$i++;
}
$y++;
unset($data[$row_key]); // 能节约一点内存
}
// xls文件处理
if ($direct_export) {
// 直接下载
ob_end_clean();
header("Pragma: public");
header("Expires: 0");
header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
header("Content-Type:application/force-download");
header("Content-Type:application/vnd.ms-execl");
header("Content-Type:application/octet-stream");
header("Content-Type:application/download");
$task_name = $task_id . '.' . $task_name . '.xlsx';
$encoded_filename = urlencode($task_name);
$ua = $_SERVER["HTTP_USER_AGENT"];
if (preg_match("/MSIE/", $ua)) {
header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
} else if (preg_match("/Firefox/", $ua)) {
header('Content-Disposition: attachment; filename*="utf8\'\'' . $task_name . '"');
} else {
header('Content-Disposition: attachment; filename="' . $task_name . '"');
}
header("Content-Transfer-Encoding:binary");
header('Cache-Control: max-age=0');// 禁止缓存
$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
$spreadsheet->disconnectWorksheets();
unset($spreadsheet);
} else {
// 保存
$writer = new Xlsx($spreadsheet);
$writer->save($this->save_dir . $task_id . DS . $subtask_id . '.xlsx');
// 设置任务状态
$result = false;
Db::startTrans();
try {
// 读取最新的 subtask 数据
$row = $this->model->get($task_id);
$progress = $row->progress + round(92 / count($row['subtask']), 2);
$progress = ($progress > 100) ? 100 : $progress;
if (isset($row['subtask'][$subtask_id]) && is_array($row['subtask'][$subtask_id])) {
$subtask = $row['subtask'];
$subtask[$subtask_id]['status'] = 2;
$row->subtask = $subtask;
$row->progress = $progress;
$row->save();
$result = true;
}
Db::commit();
} catch (PDOException $e) {
Db::rollback();
$this->result([
'subtask_id' => $subtask_id,
'error_msg' => $e->getMessage(),
], 0, '任务失败!', 'json');
} catch (Exception $e) {
Db::rollback();
$this->result([
'subtask_id' => $subtask_id,
'error_msg' => $e->getMessage(),
], 0, '任务失败!', 'json');
}
$spreadsheet->disconnectWorksheets();
unset($spreadsheet);
if ($result) {
$this->result(['subtask_id' => $subtask_id], 1, '子任务处理成功!', 'json');
} else {
$this->result(['subtask_id' => $subtask_id], 0, '子任务找不到啦~', 'json');
}
}
}
/**
* 执行子任务
* @param int $task_id 任务ID
* @param int $subtask_id 子任务ID
... ...
... ... @@ -2,6 +2,7 @@
namespace app\admin\controller\litestore;
use addons\fastexport\library\ExportLib;
use app\admin\model\litestore\Litestoregoodsspec;
use app\api\model\Goods;
use app\common\controller\Backend;
... ... @@ -12,7 +13,12 @@ use PHPExcel_Style;
use PHPExcel_Style_Alignment;
use PHPExcel_Style_Border;
use PHPExcel_Style_Fill;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\Db;
use think\Exception;
use think\exception\PDOException;
/**
*
... ... @@ -278,147 +284,88 @@ class Litestoregoods extends Backend
/**
* 导出
*/
// public function export()
// {
// //1.从数据库中导出需要进行要导出的数据
// $list = Db::name('litestore_goods_spec')->alias('c')
// ->join('fa_litestore_goods g', 'g.goods_id = c.goods_id', 'LEFT')
// ->select();
// if (empty($list)) {
// $this->error('没有可导出的数据');
// }
// //重要补助
// //2.加载PHPExcle类库
// vendor('PHPExcel.PHPExcel');
// //3.实例化PHPExcel类
// $objPHPExcel = new \PHPExcel();
// //4.激活当前的sheet表
// $objPHPExcel->setActiveSheetIndex(0);
// //5.设置表格头(即excel表格的第一行)
// $objPHPExcel->setActiveSheetIndex(0)
// ->setCellValue('A1', '商品ID')
// ->setCellValue('B1', '商品名称')
// ->setCellValue('C1', '商品原价')
// ->setCellValue('D1', '折扣')
// ->setCellValue('E1', '商品现价')
// ->setCellValue('F1', '已销数量')
// ->setCellValue('G1', '导出时间');
// //设置A列水平居中
// $objPHPExcel->setActiveSheetIndex(0)->getStyle('A1')->getAlignment()
// ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
// //设置单元格宽度
// //6.循环刚取出来的数组,将数据逐一添加到excel表格。
// $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('B')->setWidth(10);
// $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('C')->setWidth(20);
// $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('D')->setWidth(20);
// $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('E')->setWidth(20);
// $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('F')->setWidth(20);
// $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('G')->setWidth(20);
//
// for ($i = 0; $i < count($list); $i++) {
// $objPHPExcel->getActiveSheet()->setCellValue('A' . ($i + 2), $list[$i]['goods_id']);//ID
// $objPHPExcel->getActiveSheet()->setCellValue('B' . ($i + 2), $list[$i]['goods_name']);//商品名称
// $objPHPExcel->getActiveSheet()->setCellValue('C' . ($i + 2), $list[$i]['line_price']);//原价
// $objPHPExcel->getActiveSheet()->setCellValue('D' . ($i + 2), $list[$i]['discount']);//ID
// $objPHPExcel->getActiveSheet()->setCellValue('E' . ($i + 2), $list[$i]['goods_price']);//标签码
// $objPHPExcel->getActiveSheet()->setCellValue('F' . ($i + 2), $list[$i]['goods_sales']);//ID
// $objPHPExcel->getActiveSheet()->setCellValue('G' . ($i + 2), datetime(time()));//标签码
// }
// ob_end_clean();
// ob_start();
// $title = 'ahhah';
// header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
// header('Content-Disposition:attachment;filename="' . $title . '.xlsx"');
// header('Cache-Control: max-age=0');
// header('Cache-Control: max-age=1');
// header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
// header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
// header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
// header('Pragma: public'); // HTTP/1.0
// $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
// $objWriter->save('php://output'); //文件通过浏览器下载
// exit();
// }
public function export()
{
if ($this->request->isPost()) {
set_time_limit(0);
$search = $this->request->post('search');
$ids = $this->request->post('ids');
$filter = $this->request->post('filter');
$op = $this->request->post('op');
$columns = $this->request->post('columns');
//$excel = new PHPExcel();
$spreadsheet = new Spreadsheet();
$spreadsheet->getProperties()
->setCreator("FastAdmin")
->setLastModifiedBy("FastAdmin")
->setTitle("标题")
->setSubject("Subject");
$spreadsheet->getDefaultStyle()->getFont()->setName('Microsoft Yahei');
$spreadsheet->getDefaultStyle()->getFont()->setSize(12);
$worksheet = $spreadsheet->setActiveSheetIndex(0);
$whereIds = $ids == 'all' ? '1=1' : ['id' => ['in', explode(',', $ids)]];
$this->request->get(['search' => $search, 'ids' => $ids, 'filter' => $filter, 'op' => $op]);
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$line = 1;
//设置过滤方法
$this->request->filter(['strip_tags']);
//如果发送的来源是Selectpage,则转发到Selectpage
if ($this->request->request('keyField')) {
return $this->selectpage();
}
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$total = $this->model
->where($whereIds)
->order($sort, $order)
->count();
$list = $this->model
->where($whereIds)
->order($sort, $order)
->limit($offset, $limit)
->select();
$list = collection($list)->toArray();
$result = array("total" => $total, "rows" => $list);
$first = array_keys($list[0]);
foreach ($first as $index => $item) {
$worksheet->setCellValueByColumnAndRow($index, 1, __($item));
//1.从数据库中导出需要进行要导出的数据
$list = Db::name('litestore_goods_spec')->alias('c')
->join('fa_litestore_goods g', 'g.goods_id = c.goods_id', 'LEFT')
->select();
$list = collection($list)->toArray();
foreach ($list as &$item) {
if (!empty($item['spec_sku_id'])) {
$sku_value = explode('_', $item['spec_sku_id']);
if (count($sku_value) > 1) {
$key = Db::name('litestore_spec_value')->where('id', $sku_value[0])->value('spec_value');
$value = Db::name('litestore_spec_value')->where('id', $sku_value[1])->value('spec_value');
$item['sku_value'] = $key . '_' . $value;
} else {
$key = Db::name('litestore_spec_value')->where('id', $sku_value[0])->value('spec_value');
$item['sku_value'] = $key;
}
} else {
$item['sku_value'] = '';
}
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load(__DIR__ . '/muban/test.xls'); //读取模板
$worksheet = $spreadsheet->getActiveSheet(); //指向激活的工作表
$worksheet->setTitle('模板测试标题');
for($i=0;$i<$total;++$i){
//向模板表中写入数据
$worksheet->setCellValue('A1', '模板测试内容'); //送入A1的内容
$worksheet->getCell('B2')->setValue($result['rows'][$i]['week']); //星期
$worksheet->getCell('d2')->setValue($result['rows'][$i]['genderdata']); //性别
$worksheet->getCell('f2')->setValue($result['rows'][$i]['hobbydata']); //爱好
$worksheet->getCell('b3')->setValue($result['rows'][$i]['title']); //标题
$worksheet->getCell('b4')->setValue($result['rows'][$i]['content']); //内容
}
if (empty($list)) {
$this->error('没有可导出的数据');
}
//重要补助
//2.加载PHPExcle类库
vendor('PHPExcel.PHPExcel');
//3.实例化PHPExcel类
$objPHPExcel = new \PHPExcel();
//4.激活当前的sheet表
$objPHPExcel->setActiveSheetIndex(0);
//5.设置表格头(即excel表格的第一行)
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', '商品ID')
->setCellValue('B1', '商品名称')
->setCellValue('C1', '商品规格')
->setCellValue('D1', '商品原价')
->setCellValue('E1', '折扣')
->setCellValue('F1', '商品现价')
->setCellValue('G1', '已销数量')
->setCellValue('H1', '导出时间');
//设置A列水平居中
$objPHPExcel->setActiveSheetIndex(0)->getStyle('A1')->getAlignment()
->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
//设置单元格宽度
//6.循环刚取出来的数组,将数据逐一添加到excel表格。
$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('B')->setWidth(10);
$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('C')->setWidth(20);
$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('D')->setWidth(20);
$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('E')->setWidth(20);
$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('F')->setWidth(20);
$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('G')->setWidth(20);
$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('H')->setWidth(20);
for ($i = 0; $i < count($list); $i++) {
$objPHPExcel->getActiveSheet()->setCellValue('A' . ($i + 2), $list[$i]['goods_id']);//ID
$objPHPExcel->getActiveSheet()->setCellValue('B' . ($i + 2), $list[$i]['goods_name']);//商品名称
$objPHPExcel->getActiveSheet()->setCellValue('C' . ($i + 2), $list[$i]['sku_value']);//商品规格
$objPHPExcel->getActiveSheet()->setCellValue('D' . ($i + 2), $list[$i]['line_price']);//原价
$objPHPExcel->getActiveSheet()->setCellValue('E' . ($i + 2), $list[$i]['discount']);//ID
$objPHPExcel->getActiveSheet()->setCellValue('F' . ($i + 2), $list[$i]['goods_price']);//标签码
$objPHPExcel->getActiveSheet()->setCellValue('G' . ($i + 2), $list[$i]['goods_sales']);//ID
$objPHPExcel->getActiveSheet()->setCellValue('H' . ($i + 2), datetime(time()));//标签码
}
ob_end_clean();
ob_start();
$title = '商品列表';
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition:attachment;filename="' . $title . '.xlsx"');
header('Cache-Control: max-age=0');
header('Cache-Control: max-age=1');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header('Pragma: public'); // HTTP/1.0
$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output'); //文件通过浏览器下载
exit();
}
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
//下载文档
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'. date('Y-m-d') . $result['rows'][$i]['admin_id'] .'_test'.'.xlsx"');
header('Cache-Control: max-age=0');
$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
}
return;
}
}
}
... ...
... ... @@ -17,11 +17,11 @@
<a href="javascript:;"
class="btn btn-danger btn-del btn-disabled disabled {:$auth->check('litestore/litestoregoods/del')?'':'hide'}"
title="{:__('Delete')}"><i class="fa fa-trash"></i> {:__('Delete')}</a>
<a href="javascript:;"
class="btn btn-danger btn-import {:$auth->check('litestore/litestoregoods/import')?'':'hide'}"
title="{:__('Import')}" id="btn-import-file" data-url="ajax/upload"
data-mimetype="csv,xls,xlsx" data-multiple="false"><i class="fa fa-upload"></i>
{:__('Import')}</a>
<!-- <a href="javascript:;"-->
<!-- class="btn btn-danger btn-import {:$auth->check('litestore/litestoregoods/import')?'':'hide'}"-->
<!-- title="{:__('Import')}" id="btn-import-file" data-url="ajax/upload"-->
<!-- data-mimetype="csv,xls,xlsx" data-multiple="false"><i class="fa fa-upload"></i>-->
<!-- {:__('Import')}</a>-->
<!-- <a href="javascript:;"-->
<!-- class="btn btn-info btn-change btn-export btn-disable" data-params="action=export"-->
<!-- data-url="litestore/litestoregoods/export"-->
... ...
... ... @@ -113,9 +113,9 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'template', 'litestor
var page = table.bootstrapTable('getData');
var all = table.bootstrapTable('getOptions').totalRows;
console.log(ids, page, all);
Layer.confirm("请选择导出的选项<form action='" + Fast.api.fixurl("test/export") + "' method='post' target='_blank'><input type='hidden' name='ids' value='' /><input type='hidden' name='filter' ><input type='hidden' name='op'><input type='hidden' name='search'><input type='hidden' name='columns'></form>", {
Layer.confirm("请选择导出的选项<form action='" + Fast.api.fixurl("litestore/litestoregoods/export") + "' method='post' target='_blank'><input type='hidden' name='ids' value='' /><input type='hidden' name='filter' ><input type='hidden' name='op'><input type='hidden' name='search'><input type='hidden' name='columns'></form>", {
title: '导出数据',
btn: ["选中项(" + ids.length + "条)", "本页(" + page.length + "条)", "全部(" + all + "条)"],
btn: ["导出(" + all + "条)"],
// btn: ["选中项(" + ids.length + "条)"],
success: function (layero, index) {
$(".layui-layer-btn a", layero).addClass("layui-layer-btn0");
... ...