thinkphp导出excel | 我的日常分享

thinkphp导出excel

thinkphp导出excel

使用库:PHPOffice/PHPExcel https://github.com/PHPOffice/PHPExcel

以下为核心代码:可根据具体需求更改。

1、控制器文件添加export方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
use PhpOffice\PhpSpreadsheet\Helper\Sample;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;

public function export()
{
if ($this->request->isPost()) {
/**
* 设置程序执行时间的函数
* 为零说明永久执行直到程序结束
*/
set_time_limit(0);
$ids = $this->request->post('ids');
$columns = $this->request->post('columns');
$excel = new Spreadsheet();
$excel->getProperties()
->setCreator("FastAdmin")
->setLastModifiedBy("FastAdmin")
->setTitle("标题")
->setSubject("Subject");
$excel->getDefaultStyle()->getFont()->setName('Microsoft Yahei');
$excel->getDefaultStyle()->getFont()->setSize(12);
$excel->getDefaultStyle()->applyFromArray(
array(
'fill' => array(
'type' => Fill::FILL_SOLID,
'color' => array('rgb' => '000000')
),
'font' => array(
'color' => array('rgb' => "000000"),
),
'alignment' => array(
'vertical' => Alignment::VERTICAL_CENTER,
'horizontal' => Alignment::HORIZONTAL_CENTER,
'indent' => 1
),
'borders' => array(
'allborders' => array('style' => Border::BORDER_THIN),
)
));

$worksheet = $excel->setActiveSheetIndex(0);
$worksheet->setTitle('标题');
// 配合js,如果提交参数为all,则导出所有数据
$whereIds = $ids == 'all' ? '1=1' : ['id' => ['in', explode(',', $ids)]];
$line = 1;
$list = [];
$this->model
->field($columns)
->where($whereIds)
// 使用分批查询
/**
* 注意点:如果使用到了with关联查询,
* 需要指定chunk分批处理的字段名(形参)
* 例如:fa_student.id fa_student表的id
* 默认为id,如果关联表也有id字段,则会抛出异常
* SQLSTATE[23000]: Column ‘id’ in where clause is ambiguous
*/
->chunk(100, function ($items) use (&$list, &$line, &$worksheet) {
$styleArray = array(
'font' => array(
'color' => array('rgb' => '000000'),
'size' => 12,
'name' => 'Verdana'
));
$list = $items = collection($items)->toArray();
foreach ($items as $key => $v) {
foreach ($v as $k => $ele) {
$tmparray = explode("_text", $k);
if (count($tmparray) > 1) {
$items[$key][$tmparray[0]] = $ele;
unset($items[$key][$k]);
}
}
}
foreach ($items as $index => $item) {
$line++;
$col = 0;
foreach ($item as $field => $value) {
$worksheet->setCellValueByColumnAndRow($col, $line, $value);
$worksheet->getStyleByColumnAndRow($col, $line)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
$worksheet->getCellByColumnAndRow($col, $line)->getStyle()->applyFromArray($styleArray);
$col++;
}
}
});
// 获取查询到记录的字段值
$first = array_keys($list[0]);
/**
* 去除带_text的字段
* "category_text"
* "status_text"
*/
foreach ($first as $k => $ele) {
$tmparray = explode("_text", $ele);
if (count($tmparray) > 1) {
unset($first[$k]);
}
}

foreach ($first as $index => $item) {
$worksheet->setCellValueByColumnAndRow($index, 1, __($item));
}
$excel->createSheet();
// Redirect output to a client’s web browser (Excel2007)
// 保存文件名
$title = date("YmdHis");
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $title . '.xlsx"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
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 = IOFactory::createWriter($excel, 'Xlsx');
$objWriter->save('php://output');
return;
}
}

2、html页面添加后按钮,在js中绑定按钮事件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
var table = $('form[role=form]');
//自定义export开始
var submitForm = function (ids, layero) {
var options = table.bootstrapTable('getOptions');
console.log(options);
var columns = [];
$.each(options.columns[0], function (i, j) {
if (j.field && !j.checkbox && j.visible && j.field != 'operate') {
columns.push(j.field);
}
});
var search = options.queryParams({});
$("input[name=columns]", layero).val(columns.join(','));
$("form", layero).submit();
};
$(document).on("click", ".btn-export", function () {
var ids = Table.api.selectedids(table);
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='columns'></form>", {
title: '导出数据',
btn: ["选中项(" + ids.length + "条)", "本页(" + page.length + "条)", "全部(" + all + "条)"],
// btn: ["选中项(" + ids.length + "条)"],
success: function (layero, index) {
$(".layui-layer-btn a", layero).addClass("layui-layer-btn0");
}
, yes: function (index, layero) {
submitForm(ids.join(","), layero);
return false;
}
,
btn2: function (index, layero) {
var ids = [];
$.each(page, function (i, j) {
ids.push(j.id);
});
submitForm(ids.join(","), layero);
return false;
}
,
btn3: function (index, layero) {
submitForm("all", layero);
return false;
}
})
});

图片