PHP

php xlswriter怎样设置边框

小樊
89
2024-11-23 13:19:23
栏目: 编程语言

在PHP中使用PHPExcel(现在已经被更名为PhpSpreadsheet)库来操作Excel文件时,你可以使用以下方法为单元格或整个工作表设置边框:

首先,确保已经安装了PhpSpreadsheet库。如果没有安装,可以使用Composer进行安装:

composer require phpoffice/phpspreadsheet

接下来,创建一个简单的PHP脚本来设置边框:

<?php
// 引入PhpSpreadsheet库
require 'vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Cell\DataType;

// 创建一个新的电子表格对象
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();

// 设置单元格边框
$styleArray = [
    'borders' => [
        'allborders' => [
            'style' => Border::BORDER_THIN,
            'color' => ['argb' => 'FF000000'],
        ],
    ],
];

// 应用样式到单元格
$sheet->setCellValue('A1', 'Hello World !');
$sheet->getStyle('A1')->applyFromArray($styleArray);

// 设置整个工作表的边框
$sheet->getSheetView()->setZoomScale(80);
$sheet->getSheetView()->setZoom(1);
$sheet->getSheetView()->setGridLines(true);
$sheet->getSheetView()->setShowZeros(false);

// 设置工作表标题边框
$styleArrayTitle = [
    'borders' => [
        'top' => [
            'style' => Border::BORDER_THIN,
            'color' => ['argb' => 'FF000000'],
        ],
        'left' => [
            'style' => Border::BORDER_THIN,
            'color' => ['argb' => 'FF000000'],
        ],
        'bottom' => [
            'style' => Border::BORDER_THIN,
            'color' => ['argb' => 'FF000000'],
        ],
        'right' => [
            'style' => Border::BORDER_THIN,
            'color' => ['argb' => 'FF000000'],
        ],
    ],
];

$sheet->getStyle('A1:D1')->applyFromArray($styleArrayTitle);

// 保存Excel文件
$writer = new Xlsx($spreadsheet);
$fileName = 'example.xlsx';
$writer->save($fileName);

echo "Excel file with borders has been created: " . $fileName;
?>

这个脚本将创建一个包含边框的简单Excel文件。你可以根据需要修改样式、颜色和边框类型。更多关于PhpSpreadsheet库的信息和示例,请参考官方文档:https://phpspreadsheet.readthedocs.io/

0
看了该问题的人还看了