【问题标题】:Problem with exporting data to excell with Symfony 4 [closed]使用 Symfony 4 将数据导出到 excel 时出现问题 [关闭]
【发布时间】:2020-02-11 10:58:45
【问题描述】:

我有一个问题。我想将我的数据簿从我的数据库中导出到 symfony 的 Excel 中。 我尝试使用 phpSpreadSheet 。我的函数有效,但仅适用于一个值(最后一个值)。我不明白为什么我无法检索所有值。如果您有任何想法,那就太好了。

/** * @Route("/create",name="createE") * * */

public function createSpreadsheet(){
    $this->allExcel();
    return $this->render('admin/book/sendExcelOk.html.twig');


}
public function allExcel(){

    $books =$this->getDoctrine()->getRepository(Book::class)->findAll();
    $spreadsheet = new Spreadsheet();

    $sheet = $spreadsheet->getActiveSheet()->setTitle('Export Books');

    $sheet->setCellValue('C1', 'Book')->mergeCells('C1:D1');
    $columnNames = [
        'Title',
        'Author',
        'PublicationDate',
        'Format',
        'Language'
    ];
    $columnLetter = 'A';
    foreach ($columnNames as $columnName) {
        // Allow to access AA column if needed and more
        $columnLetter++;
        $sheet->setCellValue($columnLetter.'3', $columnName);
    }


    foreach ($books as $book) {
        $columnValues = [
            [$book->getTitle(),
            $book->getAuthor(),
           $book ->getPublicationDate(),
           $book->getFormat(),
           $book->getLanguage()],

        ];
    }

    $i = 4; // Beginning row for active sheet
    $columnLetter = 'A';
    foreach ($columnValues as $columnValue) {

        foreach ($columnValue as $value) {
            $columnLetter++;
            $sheet->setCellValue($columnLetter.$i, $value);

        }
        $i++;

    }

    $writer = new Xlsx($spreadsheet);
    $nombre =Book::$nombreExcell++;
    $name ="Book ".$nombre;
    $writer->save($name.'.xlsx');
    return $spreadsheet;

}

【问题讨论】:

    标签: php symfony symfony4


    【解决方案1】:

    您正在覆盖变量$columnValues,而不是向数组追加新值。尝试先初始化数组并将值添加到数组 ($columnValues[] = …),如下所示:

    $columnValues = [];
    
    foreach ($books as $book) {
        $columnValues[] = [
            $book->getTitle(),
            $book->getAuthor(),
            $book ->getPublicationDate(),
            $book->getFormat(),
            $book->getLanguage(),
        ];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-06
      • 1970-01-01
      • 2011-10-18
      • 2011-09-28
      • 1970-01-01
      • 1970-01-01
      • 2020-11-19
      • 2021-01-11
      相关资源
      最近更新 更多