Table of Contents
Instantiation
Usage examples
Set the table style" >Set the table style
Operation text alignment" >Operation text alignment
Operation border
Operation font
Operation column
Complete and directly runable example
Home Backend Development PHP Tutorial Detailed explanation of how to write a beautiful form in PhpOffice

Detailed explanation of how to write a beautiful form in PhpOffice

Jan 25, 2021 pm 12:03 PM
phpoffice

Recommended: "PHP Video Tutorial"

The article is not long, the article is not long, the article is not long

This form It is made by imitating the Orange Heart Selection group leader’s face sheet

First enter the form

PhpOffice 写一个漂亮的表格

Idea

  • To determine how many columns there are in total, you need to determine how many cells to merge in the header. You can reserve 1~2 more columns. If they are not used, finally set the width to 0
  • The rest is to merge cells and set cell styles

excel partial class structure

Note that the columns inside Some of what comes out are method names, and some are class attributes, and only the attributes used in this article are listed. For details, you have to look at the corresponding class file

Speadsheet      // 实例化 excel
    Sheet           // 当前活动 sheet   PhpOffice\PhpSpreadsheet\Worksheet\Worksheet
        getColumnDimension  // 操作列
            width               // 设置列宽
            autoSize            // 自动大小
        getRowDimension     // 操作行
            height              // 设置行高
        getCell             // 获取要操作的单元格(An:Gn),如 (A2:G7)
            style
                同Speadsheet 下的 Style
            setValue            // 设置值
        mergeCell           // 合并单元格
        pageSetup           // 页面设置,包含纸张大小,比如 A4
            ...
        pageMargins         // 页边距
            ...
        headerFooter        // 页眉页脚
            ...
        ...
    Style           // 处理样式             PhpOffice\PhpSpreadsheet\Style\Style
        Font                // 处理字体
            size                // 字体大小
            bold                // 加粗
            underline           // 下划线
            color               // 处理颜色
                argb                // 带透明度颜色
                rgb                 // 颜色
        Fill                // 处理填充
            fillType            // 填充方式
            startColor          // 开始颜色(不清楚用处)
            endColor            // 结束颜色(不清楚用处)
            color           // 处理颜色
                argb                // 带透明度颜色 背景色带透明
                rgb                 // 颜色         背景色
        Borders
        Alignment
        NumberFormat
        Protection
Copy after login

Instantiation

The following examples will use the following variables

$spreadsheet = new Spreadsheet();       // 实例化 excel 操作类,默认初始化 sheet 序号为 0

$sheet = $spreadsheet->getActiveSheet(0);       // 拿到要操作的 sheet,必须是已存在的

// 获取操作表格样式的类(全局样式)
$defaultStyle = $spreadsheet->getDefaultStyle();        // PhpOffice\PhpSpreadsheet\Style\Style 实例
Copy after login

Usage examples

// 获取操作对齐方式 类
$align = $defaultStyle->getAlignment();

// 设置 Horizontal(水平) 和 Vertical(垂直) 都居中,一个类中的方法,可以连贯操作
$align->setHorizontal(Alignment::HORIZONTAL_CENTER)->setVertical(Alignment::VERTICAL_CENTER)

// 仅水平居中
$align->setHorizontal(Alignment::HORIZONTAL_CENTER);
// 仅垂直居中
$align->setVertical(Alignment::VERTICAL_CENTER);
Copy after login
Operation border
// 获取操作对齐方式 类
$border = $defaultStyle->getBorders();
// 设置底部边框
$border->getBottom()->setBorderStyle(Border::BORDER_THIN)
Copy after login
Operation font
// 获取字体操作类
$font = $defaultStyle->getFont()

// 设置字体 18, 加粗,加下划线
$font->setSize(18)->setBold(true)->setUnderline(Font::UNDERLINE_SINGLE);
// 操作颜色,需要先获取颜色操作 类
$font->getColor()->setRGB('333333');
Copy after login
Operation column
$column = $sheet->getColumnDimension('A')

// 设置列宽
$column->setWidth(7);
Copy after login

Complete and directly runable example

// 引入必要类
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Border;

$spreadsheet = new Spreadsheet();

// 获取活动 sheet
$sheet = $spreadsheet->getActiveSheet(0);
// 设置表格全部上下居中
$defaultStyle = $spreadsheet->getDefaultStyle();
$defaultStyle->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER)->setVertical(Alignment::VERTICAL_CENTER);
$defaultStyle->getFont()->getColor()->setRGB('333333');

// 设置列宽
$sheet->getColumnDimension('A')->setWidth(7);
$sheet->getColumnDimension('B')->setWidth(35);
$sheet->getColumnDimension('C')->setWidth(11);
$sheet->getColumnDimension('D')->setWidth(12);
$sheet->getColumnDimension('E')->setWidth(12);
$sheet->getColumnDimension('F')->setWidth(0);           // 预留列
$sheet->getColumnDimension('G')->setWidth(14);

$line = 1;
// 大标题
// 合并单元格
$sheet->mergeCells('A'. $line .':G'. $line);            // 合并单元格
$sheet->getRowDimension($line)->setRowHeight(40);       // 设置行高
$ATitle = $sheet->getCell('A' . $line);                 // 获取单元格
$ATitle->getStyle('A' . $line)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);        // 内容水平居中
$ATitle->getStyle('A' . $line)->getFont()->setSize(22)->setBold(true);                              // 字体大小,加粗
$ATitle->setValue('Smallnews - 门店订单');

$line ++;
// 店长信息
$sheet->mergeCells('A' . $line . ':G' . $line);
$sheet->getStyle('A' . $line . ':G' . $line)->getBorders()->getBottom()->setBorderStyle(Border::BORDER_THIN);       // 下边框样式
$AStore = $sheet->getCell('A' . $line);
$AStore->getStyle('A' . $line)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);                          // 内容水平居左
$AStore->getStyle('A' . $line)->getFont()->setSize(16)->setBold(true);                                              // 字体大小,加粗
$AStore->setValue('Smallnews/157****1560');

$line ++;
// 门店地址
$sheet->mergeCells('A' . $line . ':G' . $line);
$AAddress = $sheet->getCell('A' . $line);
$AAddress->getStyle('A' . $line)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
$AAddress->getStyle('A' . $line)->getFont()->setSize(14);
$AAddress->setValue('北京望京 SOHO');

$line ++;
// 运单统计
$sheet->mergeCells('A' . $line . ':B' . $line);         // AB 合并
$sheet->getRowDimension($line)->setRowHeight(40);       // 设置行高
$ATotalOrder = $sheet->getCell('A' . $line);
$ATotalOrder->getStyle('A' . $line)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT)->setVertical(Alignment::VERTICAL_BOTTOM);        // 内容水平居左,垂直居下
$ATotalOrder->getStyle('A' . $line)->getFont()->setSize(12);
$ATotalOrder->setValue('订单数量:5');

$sheet->mergeCells('C' . $line . ':D' . $line);         // CD 合并
$CTotalGoods = $sheet->getCell('C' . $line);
$CTotalGoods->getStyle('C' . $line)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT)->setVertical(Alignment::VERTICAL_BOTTOM);        // 内容水平居左,垂直居下
$CTotalGoods->getStyle('C' . $line)->getFont()->setSize(12);
$CTotalGoods->setValue('商品总量:20');

$sheet->mergeCells('E' . $line . ':G' . $line);         // EFG 合并
$ESend = $sheet->getCell('E' . $line);
$ESend->getStyle('E' . $line)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT)->setVertical(Alignment::VERTICAL_BOTTOM);             // 内容水平居左,垂直居下
$ESend->getStyle('E' . $line)->getFont()->setSize(12);
$ESend->setValue('发货时间:' . date('Y-m-d'));

$line ++;
// 增加一个空行,充当上下内容的 margin
$sheet->mergeCells('A' . $line . ':G' . $line);
$sheet->getRowDimension($line)->setRowHeight(6);

$line ++;

// 模拟订单数据
$orders = [
    ['items' => [
        ['goods_title' => '这是个名字很长的商品,真的很长, 不信你看,肯定超过了表格宽度'],
        ['goods_title' => '这是个名字比较短的商品'],
    ]],
    ['items' => [
        ['goods_title' => '转向 卫衣秋季潮牌新款宽松时尚套头紫橘色橙色短款连帽卫衣女'],
        ['goods_title' => '芙清医美面膜医用男女淡化痘印抗菌敷料水光针术后修复皮炎祛痘'],
        ['goods_title' => '经典麻辣锅底'],
    ]]
];

// 订单数据 
foreach ($orders as $order) {
    // 购买信息
    $sheet->getRowDimension($line)->setRowHeight(30);
    $sheet->getStyle('A' . $line . ':G' . $line)->getFont()->setSize(14);
    $sheet->getStyle('A' . $line . ':G' . $line)->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB('CCCCCC');
    $sheet->mergeCells('A' . $line . ':B' . $line);
    $AUser = $sheet->getCell('A' . $line);
    $AUser->getStyle('A' . $line)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
    $AUser->getStyle('A' . $line)->getFont()->setSize(15)->setBold(true);

    // 模拟用户数据
    $user = [ 'nickname' => 'Smallnews', 'mobile' => '15788881560' ];
    $nickname = mb_strlen($user['nickname']) > 7 ? mb_substr($user['nickname'], 0, 6) . '**' : $user['nickname'];
    $AUser->setValue($nickname . ($user['mobile'] ?  ' /  ' .substr($user['mobile'], 0, 3) . '****' . substr($user['mobile'], 7) : ''));

    $sheet->mergeCells('C' . $line . ':G' . $line);
    $CTotal = $sheet->getCell('C' . $line);
    $CTotal->getStyle('C' . $line)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT);
    $CTotal->getStyle('C' . $line)->getFont()->setSize(14);
    $CTotal->setValue('共 2 种商品,共 3 件,实付 200 元');

    $line++;
    // 增加一个空行,充当上下内容的 margin
    $sheet->mergeCells('A' . $line . ':G' . $line);
    $sheet->getRowDimension($line)->setRowHeight(6);

    $line ++;
    // 订单商品信息
    $sheet->getStyle('A' . $line . ':G' . ($line + count($order['items'])))->getBorders()->getAllBorders()->setBorderStyle(Border::BORDER_THIN);     // 根据商品数量, 设置区域的边框

    $sheet->setCellValue('A' . $line, '序号');
    $sheet->setCellValue('B' . $line, '商品名称');
    $sheet->setCellValue('C' . $line, '单价');
    $sheet->setCellValue('D' . $line, '优惠');
    $sheet->setCellValue('E' . $line, '数量');
    $sheet->setCellValue('F' . $line, '');
    $sheet->setCellValue('G' . $line, '是否提货');

    foreach ($order['items'] as $key => $item) {
        $line ++;
        $sheet->setCellValue('A' . $line, ($key + 1));
        $sheet->getStyle('B' . $line)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);               // 商品名称 水平居左
        $goods_title = mb_strlen($item['goods_title']) > 16 ? mb_substr($item['goods_title'], 0, 14) . '**' : $item['goods_title'];
        $sheet->setCellValue('B' . $line, $goods_title);
        $sheet->setCellValue('C' . $line, '22.22');
        $sheet->setCellValue('D' . $line, '11.11');
        $sheet->setCellValue('E' . $line, 3);
        $sheet->setCellValue('F' . $line, '');
        $sheet->setCellValue('G' . $line, '');
    }

    $line++;
    $sheet->mergeCells('A' . $line . ':G' . $line);
    $sheet->getRowDimension($line)->setRowHeight(6);
    $line++;
}

ob_end_clean();
header('pragma:public');
header('Content-type:application/vnd.ms-excel;charset=utf-8;name="' . '门店面单' . '.xls"');
header("Content-Disposition:attachment;filename=门店面单.xls"); //attachment新窗口打印inline本窗口打印
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
Copy after login

The above is the detailed content of Detailed explanation of how to write a beautiful form in PhpOffice. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1668
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles