PhpSpreadsheet export specific format - advertising payment request

Statement of needs

Recently the need to achieve an export Excel spreadsheet format, you have used before export Excel function, but mostly in the form header + data is only used to retrieve data, there is not much style requirements, do not merge cells, merge center etc., we do not have specific data for each line of custom, so PhpSpreadsheet extensions for advanced understanding.

Resolution process

From github-> Official Documents -> api documentation -> CSDN article (end of the article there is a link), followed by operations will have been finished after an error, the article csdn in style once called method returns an object becomes a style-related , can not continue to specify the unit of work, so still not too practical, only as a reference.

Finally, by looking at the source code + api documentation to achieve a functional point of this section.

Methods need to use

  1. mergeCells (): merged cell, the parameter cell as a starting cell to the end
  2. getCellByColumnAndRow (): Get the specified cell object location
  3. setValueExplicit (): cell contents, and specify the style
  4. getStyle (): Get cell style objects
  5. applyFromArray (): Specifies the cell style

Fragment Interpretation

1, a data filling cells

$sheet->mergeCells('A1:K2')->getCellByColumnAndRow(1, 1)->setValueExplicit('广告请款单', $contentType);
  1. mergeCells('A1:K2'): Merge from K2 to A1
  2. getCellByColumnAndRow(1, 1): Obtaining a first row, first column cell object
  3. setValueExplicit('广告请款单', $contentType): Filler content 广告请款单, type and specified as a string ($ contentType = DataType :: TYPE_STRING)

2, specify the style

$styleArray = [
    'alignment' => [
        // 水平居中
        'horizontal' => Alignment::HORIZONTAL_CENTER,
        // 垂直居中
        'vertical' => Alignment::VERTICAL_CENTER,
        // 自动换行
        'wrapText' => true
    ],
];
$sheet->getStyle('A1:K21')->applyFromArray($styleArray);
  1. 'wrapText' => trueSUMMARY specified cell wrap, will automatically parse the text \n, \r\nline breaks
  2. applyFromArray()Method in \PhpOffice\PhpSpreadsheet\Style\Alignmentclass parameters can be specified according to the need;
  3. NOTE: To specify style data is provided after all the cells, because the result is returned after setting the style \PhpOffice\PhpSpreadsheet\Style\Alignmentobjects, no mergeCells()other method for setting the cell

The remaining trouble spots is to calculate the position of each particular cell is a merged

Violence to achieve

Initially During the test, the theoretical basis is not sufficient, so we calculate the position of each style by violence and set up.

$contentType = DataType::TYPE_STRING;
$sheet->mergeCells('A1:K2')->getCellByColumnAndRow(1, 1)->setValueExplicit('广告请款单', $contentType);

$sheet->mergeCells('A3:B4')->getCellByColumnAndRow(1, 3)->setValueExplicit('申请时间', $contentType);
$sheet->mergeCells('C3:E4')->getCellByColumnAndRow(3, 3)->setValueExplicit(date('Y-m-d H:i:s', $data['apply_clear_time']), $contentType);
$sheet->mergeCells('F3:G4')->getCellByColumnAndRow(6, 3)->setValueExplicit('广告编号', $contentType);
$sheet->mergeCells('H3:K4')->getCellByColumnAndRow(8, 3)->setValueExplicit($data['ad_no'], $contentType);

$sheet->mergeCells('A5:B6')->getCellByColumnAndRow(1, 5)->setValueExplicit('收款单位', $contentType);
$sheet->mergeCells('C5:K6')->getCellByColumnAndRow(3, 5)->setValueExplicit($data['real_name'], $contentType);

$sheet->mergeCells('A7:B8')->getCellByColumnAndRow(1, 7)->setValueExplicit('银行账户', $contentType);
$sheet->mergeCells('C7:K8')->getCellByColumnAndRow(3, 7)->setValueExplicit($data['bank_no'], $contentType);

$sheet->mergeCells('A9:B10')->getCellByColumnAndRow(1, 9)->setValueExplicit('开户行', $contentType);
$sheet->mergeCells('C9:K10')->getCellByColumnAndRow(3, 9)->setValueExplicit($data['bank_name'], $contentType);

$sheet->mergeCells('A11:B12')->getCellByColumnAndRow(1, 11)->setValueExplicit('金额', $contentType);
$sheet->mergeCells('C11:E12')->getCellByColumnAndRow(3, 11)->setValueExplicit($data['amount'], $contentType);
$sheet->mergeCells('F11:G12')->getCellByColumnAndRow(6, 11)->setValueExplicit('大写金额', $contentType);
$sheet->mergeCells('H11:K12')->getCellByColumnAndRow(8, 11)->setValueExplicit($data['amount_desc'], $contentType);

$sheet->mergeCells('A13:B14')->getCellByColumnAndRow(1, 13)->setValueExplicit('备注', $contentType);
$sheet->mergeCells('C13:K14')->getCellByColumnAndRow(3, 13)->setValueExplicit($data['desc'], $contentType);

$sheet->mergeCells('A15:D16')->getCellByColumnAndRow(1, 15)->setValueExplicit('广告BD审核', $contentType);
$sheet->mergeCells('E15:H16')->getCellByColumnAndRow(5, 15)->setValueExplicit('广告主管审核', $contentType);
$sheet->mergeCells('I15:K16')->getCellByColumnAndRow(9, 15)->setValueExplicit('总经理审核', $contentType);

$sheet->mergeCells('A17:D19')->getCellByColumnAndRow(1, 17)->setValueExplicit($data['auth_log_list'][0]['auth_desc'], $contentType);
$sheet->mergeCells('E17:H19')->getCellByColumnAndRow(5, 17)->setValueExplicit($data['auth_log_list'][1]['auth_desc'], $contentType);
$sheet->mergeCells('I17:K19')->getCellByColumnAndRow(9, 17)->setValueExplicit($data['auth_log_list'][2] ? $data['auth_log_list'][2]['auth_desc'] : '无需审核', $contentType);

$sheet->mergeCells('A20:B21')->getCellByColumnAndRow(1, 20)->setValueExplicit('财务', $contentType);
$sheet->mergeCells('C20:K21')->getCellByColumnAndRow(3, 20)->setValueExplicit('', $contentType);

Package

More complex

The only need to calculate what is the mergeCells()method and the getCellByColumnAndRow()method parameters

$sheet->mergeCells($start.':'.$end)->getCellByColumnAndRow($column_start, $row_start)->setValueExplicit($column[2], $contentType);

But by brute force process is also very good to get the law.

General Method

public static function exportSpecialExcel($data, $filename='', $post=false)
{
    // 此处只需要导出单条数据,对内存没要求,
    // ini_set('memory_limit', '3072M');

    if (empty($filename)) {
        $filename = date('Y-m-d') . '导出表格';
    }

    $pathinfo = pathinfo($filename);
    if (empty($pathinfo['extension']) || !in_array($pathinfo['extension'], ['xls', 'xlsx'])) {
        $filename = $filename . '.xlsx';
    }

    $spreadsheet = new Spreadsheet();
    $sheet= $spreadsheet->getActiveSheet();

    $contentType = DataType::TYPE_STRING;

    /**
     * column
     *  0 - 行高
     *  1 - 列宽
     *  2 - 数据内容
     */
    $row_start = 1;
    foreach ($data as $row) {
        $column_start = 1;
        foreach ($row as $column) {
            $start = (static::$column_header[$column_start]) . $row_start;
            $end = (static::$column_header[$column_start + $column[1] - 1]).($row_start + $column[0] - 1);
            $sheet->mergeCells($start.':'.$end)->getCellByColumnAndRow($column_start, $row_start)->setValueExplicit($column[2], $contentType);
            $column_start += $column[1];
        }
        $row_start += $row[0][0];
    }

    $styleArray = [
        'alignment' => [
            'horizontal' => Alignment::HORIZONTAL_CENTER,
            'vertical' => Alignment::VERTICAL_CENTER,
            'wrapText' => true
        ],
    ];
    $sheet->getStyle('A1:K21')->applyFromArray($styleArray);

    header('Content-Description: File Transfer');
    header('Expires: 0');
    header('Pragma: public');
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');//告诉浏览器输出07Excel文件
    header('Content-Disposition: attachment;filename="' . $filename . '"');
    header('Cache-Control: max-age=0');
    $writer = new Xlsx($spreadsheet);
    $writer->save('php://output');
    //删除清空:
    LogHelper::access(memory_get_peak_usage(), 'export_memory');
    $spreadsheet->disconnectWorksheets();
    unset($spreadsheet);
    exit;
}

Business Data

Each sub-element array of row height, column width, composed of three content data

$showData = [
    [
        [2, 11, '广告请款单'],
    ],
    [
        [2, 2, '申请时间'],
        [2, 3, date('Y-m-d H:i:s', $data['apply_clear_time'])],
        [2, 2, '广告编号'],
        [2, 4, $data['ad_no']],
    ],
    [
        [2, 2, '收款单位'],
        [2, 9, $data['real_name']],
    ],
    [
        [2, 2, '银行账户'],
        [2, 9, $data['bank_no']],

    ],
    [
        [2, 2, '开户行'],
        [2, 9, $data['bank_name']],
    ],
    [
        [2, 2, '金额'],
        [2, 3, $data['amount']],
        [2, 2, '大写金额'],
        [2, 4, $data['amount_desc']],
    ],
    [
        [2, 2, '备注'],
        [2, 9, $data['desc']],
    ],
    [
        [2, 4, '广告BD审核'],
        [2, 4, '广告主管审核'],
        [2, 3, '总经理审核'],
    ],
    [
        [3, 4, $data['auth_log_list'][0]['auth_desc']],
        [3, 4, $data['auth_log_list'][1]['auth_desc']],
        [3, 3, isset($data['auth_log_list'][2]) ? $data['auth_log_list'][2]['auth_desc'] : '无需审核'],
    ],
    [
        [2, 2, '财务'],
        [2, 9, ''],
    ],
];

So we achieved this business needs, but also facilitate future business-related functions

Reference material

  1. PhpSpreadsheet-GitHub : GitHub source code library, you can learn to install
  2. phpspreadsheet Documents in English Documents
  3. phpspreadsheet api library classes and methods described
  4. CSDN- Detailed PhpSpreadsheet Set cell : sorting out the parts of the document by the official use cases, but too simple, direct use is still a problem occurs

Guess you like

Origin www.cnblogs.com/zqunor/p/11712075.html