7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PhpSpreadsheetでセル内改行する

Last updated at Posted at 2019-02-12

PhpSpreadSheetでExcelファイルを出力する際、セル内改行が必要な場面に遭遇。
とりあえず\nを織り交ぜてみたが、半角スペースみたいなスペースが空くのみで改行されず。

色々試した結果、以下のような記述で実装可能。

hoge.php
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx as XlsxReader;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx as XlsxWriter;
hoge.php
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();

//セル内改行指定
$sheet->getStyle('A1:C3')->getAlignment()->setWrapText(true);
$sheet->setCellValue("A1","hello\nhello\n");
$sheet->setCellValue("B2","hello\nhello\n");
$sheet->setCellValue("C3","hello\nhello\n");

$writer = new XlsxWriter($spreadsheet);
$fileName = 'test.xlsx';
header("Content-Description: File Transfer");
header('Content-Disposition: attachment; filename="'.$fileName.'"');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
ob_end_clean();
$writer->save('php://output');

getStyle('A1:C3') のところだけ書き換えればOKですね。

【追記】
DLしたファイルが「破損している」的なことを言われる時は、最後の行に

hoge.php
$writer->save('php://output');
exit;

と、exit; を入れてみて下さい。

7
6
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?