首页 > 编程语言 >PhpSpreadsheet基本使用

PhpSpreadsheet基本使用

时间:2022-11-19 11:11:52浏览次数:40  
标签:基本 sheet 单元格 spreadsheet PhpSpreadsheet header getStyle 设置 使用

composer require phpoffice/phpspreadsheet 

composer require phpoffice/phpspreadsheet 

<?php

require_once __DIR__ . '/phpoffice/vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Helper\Html as HtmlHelper;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;

$spreadsheet = new Spreadsheet(); //新建文件
// $spreadSheet = IOFactory::load($inputFileName); //载入文件
$sheet = $spreadsheet->getActiveSheet();
//$spreadSheet->getProperties()->setCreator("hellow");//设置作者
//$spreadSheet->getSheetCount();//工作表总数
//$spreadSheet->getSheetNames();//工作表名数组
//$sheet = $spreadSheet->getSheetByName('Sheet1');//根据表名获取工作表
//$sheet = $spreadSheet->getSheet(0);//根据表索引获取工作表
//$sheet = $spreadSheet->setActiveSheetIndex(0);//切换当前工作表
//$sheet = $spreadsheet->setActiveSheetIndexByName('DataSheet')

//设置打印选项
$sheet->getPageSetup()->setFitToWidth(1);
$sheet->getPageSetup()->setFitToHeight(0);
$sheet->getPageSetup()->setOrientation(PageSetup::ORIENTATION_LANDSCAPE)->setPaperSize(PageSetup::PAPERSIZE_A4);;
$sheet->getPageMargins()->setTop(1)->setRight(0.75)->setLeft(0.75)->setBottom(1);
$sheet->getPageSetup()->setHorizontalCentered(true)->setVerticalCentered(false);
$sheet->setPrintGridlines(true);
$sheet->getPageSetup()->setPrintArea('A1:E5,G4:M20');

//设置缩放
$sheet->getSheetView()->setZoomScale(75);
//设置worksheet的颜色
$sheet->getTabColor()->setRGB('FF0000');
//设置worksheet名字
$sheet->setTitle('sheet 1');

//设置默认样式
$spreadsheet->getDefaultStyle()->getFont()->setName('Arial');
$spreadsheet->getDefaultStyle()->getFont()->setSize(8);

//获取文档所有值
$data = $sheet->toArray();
//获取最大行数 
$res = $sheet->getHighestRow();
//获取最大列数 
$res = $sheet->getHighestColumn();

//单元格信息
$cell = $sheet->getCellByColumnAndRow(2, 1); //获取单元格 B1
$cell = $sheet->getCell('A1'); //获取单元格A1
$cell->getValue(); //获取单元格的数据值
$cell->getCoordinate(); //获取行列信息 A1
$column = $cell->getColumn(); //获取列信息 A
$row   = $cell->getRow(); //获取行信息 1
$cell->getDataType(); //获取数据类型
$cell->setValue('8888'); //设置值
$cell->getStyle()->getFont()->getName(); //单元格样式

//设置行高
$sheet->getDefaultRowDimension()->setRowHeight(10, 'mm');
$sheet->getRowDimension(1)->setRowHeight(10, 'mm');
//设置列宽
// $sheet->getColumnDimension('A')->setAutoSize(true);
//$sheet->getColumnDimension('A')->setWidth(300);//设置A列的宽度
$sheet->getDefaultColumnDimension()->setWidth(20); //设置列默认宽度

//设置换行
$sheet->setCellValue('A2', "hellow\nphp"); //设置换行 双引号+\n+setWrapText
$sheet->getStyle('A2')->getAlignment()->setWrapText(true); //设置换行

//合并拆分单元格
$sheet->mergeCells('B2:B3');
// $sheet->unmergeCells('B2:B3');

//设置值
// $sheet->setCellValue('A1', "hellow\nphp");
$sheet->setCellValueByColumnAndRow(2, 2, '6666'); //设置B2的值
// $sheet->fromArray($arr, null, 'D5'); //数组,空值时填充值,开始单元格坐标

//设置超链接
$sheet->setCellValue('B3', "百度"); //设置A链接
$sheet->getCell('B3')->getHyperlink()->setUrl('https://www.baidu.com');
// $sheet->setCellValue('E26', 'www.phpexcel.net');
// $sheet->getCell('E26')->getHyperlink()->setUrl("sheet://'Sheetname'!A1");

//设置字体粗细大小颜色
$sheet->getStyle('B3')->getFont()->setBold(true)->setName('Arial')->setSize(20);
$sheet->getStyle('B3')->getFont()->getName(); //字体名
$sheet->getStyle('B3')->getFont()->getColor()->setRGB('#AEEEEE'); //设置颜色
$sheet->getStyle('B3')->getFont()->getColor()->getRGB(); //获取颜色值
$sheet->getCell('C3')->setValue('2021-03-27 23:22:59');
//$sheet->getStyle('D2')->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_DATE_DDMMYYYY);//设置日期格式 
$sheet->getStyle('D3')->getNumberFormat()->setFormatCode('dd/mm/yyyy'); //设置日期格式 与上文相同


//设置单元格背景色
$sheet->getStyle('E3')->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB(Color::COLOR_GREEN);

//设置单元格对齐方式
$sheet->getStyle('B2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
$sheet->getStyle('B2')->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);

//设置单元格边框
$sheet->getStyle('C2:E2')->getBorders()->getBottom()->setBorderStyle(Border::BORDER_THIN);

//富文本
$html = '<strong>bold</strong>, <em>italic</em>, <strong><em>bold+italic</em></strong>';;
$wizard = new HtmlHelper();
$richText = $wizard->toRichTextObject($html);
$sheet->setCellValue('D5', $richText);

//公式
$sheet->setCellValue('A4', '=IF(C4>500,"profit","loss")');
// $formula = $sheet->getCell('A4')->getValue();
// $value = $sheet->getCell('A4')->getCalculatedValue();

//插入删除行列
$sheet->insertNewRowBefore(7, 2);
$sheet->removeRow(7, 2);

//写入图片
$drawing = new Drawing();
$drawing->setName('Logo')->setDescription('Logo')->setPath('../files/1.jpg')->setHeight(30)->setCoordinates('D6')->setOffsetX(50)->setOffsetY(6);
$drawing->setRotation(25);
$drawing->getShadow()->setVisible(true);
$drawing->getShadow()->setDirection(45);

$drawing->setWorksheet($sheet);

//设置单元格数据类型
$sheet->getCell('A1')->setValueExplicit('25', DataType::TYPE_NUMERIC);

//格式
$styleArray = [
    'font' => [
        'bold' => true,
    ],
    'alignment' => [
        'horizontal' => Alignment::HORIZONTAL_RIGHT,
    ],
    'borders' => [
        'top' => [
            'borderStyle' => Border::BORDER_THIN,
        ],
    ],
    'fill' => [
        'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_GRADIENT_LINEAR,
        'rotation' => 90,
        'startColor' => [
            'argb' => 'FFA0A0A0',
        ],
        'endColor' => [
            'argb' => 'FFFFFFFF',
        ],
    ],
];
$filename = '01simple.xlsx';
$sheet->getStyle('A5:E5')->applyFromArray($styleArray);

// // 保存xlsx在本地
// $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
// $writer->save('01simple.xlsx');

// 下载xlsx
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $filename . '"');
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
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
exit;

 实例

require_once __DIR__ . './phpoffice/vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Helper\Html as HtmlHelper;

$spreadsheet = new Spreadsheet(); //新建文件
$sheet = $spreadsheet->getActiveSheet();
//富文本
$html = '<strong>bold</strong>, <em>italic</em>, <strong><em>bold+italic</em></strong>';;
$wizard = new HtmlHelper();
$richText = $wizard->toRichTextObject($html);
$sheet->setCellValue('D5', $richText);
$filename = 'aa.xlsx';
// 下载xlsx
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $filename . '"');
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
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
exit;

  

$filename = 'aa.xlsx';
$htmlString = '<table border="1" style="width: 100%; margin-bottom: 1rem; color: #212529;vertical-align: top;border-color: #dee2e6;border-collapse: collapse;border: 1px solid black;">
            <thead>
                <tr style="height: 4rem;">
                    <th>#</th>
                    <th>First</th>
                    <th>Last</th>
                    <th>Handle</th>
                </tr>
            </thead>
            <tbody>
                <tr style="height: 3rem;">
                    <th scope="row"><input type="checkbox"></th>
                    <td>Mark</td>
                    <td>Otto</td>
                    <td>@mdo</td>
                </tr>
                <tr style="height: 3rem;">
                    <th scope="row"><input type="checkbox"></th>
                    <td>Jacob</td>
                    <td>Thornton</td>
                    <td>@fat</td>
                </tr>
                <tr style="height: 3rem;">
                    <th><input type="checkbox"></th>
                    <td colspan="2">Larry the Bird</td>
                    <td>@twitter</td>
                </tr>
            </tbody>
        </table>';

$reader = new \PhpOffice\PhpSpreadsheet\Reader\Html();
$spreadsheet = $reader->loadFromString($htmlString);
// 下载xlsx
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $filename . '"');
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
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
exit;
<?php

require_once __DIR__ . '/phpoffice/vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\IOFactory; //用于载入已有的模板文件

$inputFileName = '../files/temp-sample-v0.xlsx'; //一个空的excel文件
$spreadsheet = IOFactory::load($inputFileName);
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('B5', '12345677');

header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="myfile.xls"');
header('Cache-Control: max-age=0');

$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
$writer->save('php://output');
exit;

 

标签:基本,sheet,单元格,spreadsheet,PhpSpreadsheet,header,getStyle,设置,使用
From: https://www.cnblogs.com/caroline2016/p/16905664.html

相关文章

  • 使用马尔可夫链构建文本生成器
    本文中将介绍一个流行的机器学习项目——文本生成器,你将了解如何构建文本生成器,并了解如何实现马尔可夫链以实现更快的预测模型。文本生成器简介文本生成在各个行业都很......
  • 使用yum查询系统安装的软件及可以更新的软件并单独指定升级某一个软件
    Linux系统下yum命令查看安装了哪些软件包: $yumlistinstalled//列出所有已安装的软件包 yum针对软件包操作常用命令: 1.使用YUM查找软件包 命令:yumsearchphp......
  • 使用JSZIP打包下载多个echarts图片
    JSZIP的github地址:https://github.com/Stuk/jszip多个echarts图一键下载charts_all.map(([index,myChart])=>{constimgContent=myChart.getDataURL({......
  • Mysql命令行使用source执行.sql文件报错
    问题描述在windows上,使用命令行登录mysql,使用source命令执行xxx.sql文件,报错。将文件里的内容粘贴在命令行可以正确执行。原因连接mysql时没有设置编码解决mysql-u......
  • 使用xlxs.js读取上传xlsx文件
    xlsx的github地址:https://github.com/SheetJS/sheetjs<!DOCTYPEhtml><html><head><metacharset="utf-8"/><scriptsrc="jquery/jquery-1.9.1.min.js"><......
  • js使用FileReader读取上传csv文件
    <script>functionreadCsv(){constfile=$("#uploadFile")[0].files[0];if(file.type!="text/csv"){alert("文件类型错误");return;......
  • js网络请求插件和FormData简单使用
    <!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"/><metahttp-equiv="X-UA-Compatible"content="IE=edge"/><metaname="viewport"c......
  • vba的xmlhttp对象的使用
    1、xmlhttp:早期用于远程数据库管理;传送XML数据格式的超长文本传输协议;不仅仅是XML格式;还可以是字符串,二进制流等。2、引用方式(1)直接引用:MicrosoftXML......
  • Bash 脚本 命令使用详解
    什么是Bash简介Bash(GNUBourne-AgainShell)是一个为GNU计划编写的Unixshell,它是许多Linux平台默认使用的shell。shell是一个命令解释器,是介于操作系统内核与用户......
  • html生成pdf的js插件的简单使用
    <!DOCTYPEhtml><html><head><metacharset="utf-8"/><title>jspdf</title><linkhref="./plugins/bootstrap-5.1.3-dist/css/bootstrap.min.css"re......