123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108 |
- <?php
- /**
- * Created by PhpStorm.
- * User: shensong
- * Date: 2023/5/6
- * Time: 18:23
- */
- namespace App\libs\XLSXWriter;
- class XLSXWriteClass
- {
- private $write;
- public function __construct()
- {
- $this->write = new XLSXWriter(); //如果提示不存在,就引入一下
- }
- /**
- * 把数据下载为文件
- * @param array $title 标题数据
- * @param array $data 内容数据
- * @param string $fileName 文件名(可包含路径)
- * @param int $type Excel下载类型:1-下载文件;2-浏览器弹框下载
- * @param string $sheet Excel的工作表
- */
- public function downloadExcel($title, $data, $fileName, $type = 1, $sheet = 'Sheet1')
- {
- if ($type == 2) {
- //设置 header,用于浏览器下载
- header('Content-disposition: attachment; filename="' . XLSXWriter::sanitize_filename($fileName) . '"');
- header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
- header('Content-Transfer-Encoding: binary');
- header('Cache-Control: must-revalidate');
- header('Pragma: public');
- }
- //处理标题数据,都设置为string类型
- $header = [];
- foreach ($title as $value) {
- $header[$value] = 'string'; //把表头的数据全部设置为string类型
- }
- $this->write->writeSheetHeader($sheet, $header);
- //根据标题数据title,按title的字段顺序把数据一条条加到excel中
- foreach ($data as $key => $value) {
- $row = [];
- foreach ($title as $k => $val) {
- $row[] = $value[$k];
- }
- $this->write->writeSheetRow($sheet, $row);
- }
- if ($type == 1) { //直接保存文件
- $this->write->writeToFile($fileName);
- } else if ($type == 2) { //浏览器下载文件
- $this->write->writeToStdOut();
- // echo $this->write->writeToString();
- exit(0);
- } else {
- die('文件下载方式错误~');
- }
- }
- /**
- * 设置excel第一行的数据
- * @param array $title 标题数据,格式如:['A1' => '姓名', 'B1' => '爱好']
- * @param string $sheet excel工作区,默认第一个
- * @return void
- */
- public function setTitle($title, $sheet = 'Sheet1')
- {
- //处理标题数据,都设置为string类型
- $header = [];
- foreach ($title as $value) {
- $header[$value] = 'string'; //把表头的数据全部设置为string类型
- }
- $this->write->writeSheetHeader($sheet, $header);
- }
- /**
- * 根据标题顺序,设置每一行的数据
- * @param array $data 一行数据
- * @param array $title 标题数据
- * @param string $sheet excel工作区,默认第一个
- * @return void
- */
- public function setOneRowData($data, $title, $sheet = 'Sheet1')
- {
- $row = [];
- foreach ($title as $k => $val) {
- $row[] = $data[$k];
- }
- $this->write->writeSheetRow($sheet, $row);
- }
- /**
- * 设置文件保存的位置
- * @param string $fileName 保存的文件名(可包含路径)
- * @return void
- */
- public function setSaveFile($fileName)
- {
- $this->write->writeToFile($fileName);
- }
- }
|