php 用 PHPExcel 添加新行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11416934/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:28:31  来源:igfitidea点击:

Adding a new row with PHPExcel?

phpphpexcel

提问by Novak

How can I add a new row to an existing .xls file using PHPExcel?

如何使用 PHPExcel 向现有的 .xls 文件添加新行?

Do I have to calculate the number of rows that already exist?

我是否必须计算已经存在的行数?

If so, how can I do that for an excel file?

如果是这样,我该如何处理 excel 文件?

回答by Daniel Li

Assuming this setup:

假设此设置:

$objPHPExcel = PHPExcel_IOFactory::load("foo.xlsx");
$objWorksheet = $objPHPExcel->getActiveSheet();

You can get the number of rows like so:

您可以像这样获得行数:

$num_rows = $objPHPExcel->getActiveSheet()->getHighestRow();

$num_rows = $objPHPExcel->getActiveSheet()->getHighestRow();

Following this, you can look into inserting a row by using the following statement:

在此之后,您可以使用以下语句来研究插入一行:

$objWorksheet->insertNewRowBefore($num_rows + 1, 1);

$objWorksheet->insertNewRowBefore($num_rows + 1, 1);

This adds 1 new row before $num_rows.

这在 之前添加了 1 个新行$num_rows

回答by Faraderegele

The example above only adds a blank row. The example below adds data coming from a form.

上面的例子只添加了一个空行。下面的示例添加来自表单的数据。

<?php

        require_once '../inc/phpexcel/Classes/PHPExcel.php';
        require_once '../inc/phpexcel/Classes/PHPExcel/IOFactory.php';
        $objPHPExcel = PHPExcel_IOFactory::load("myExcelFile.xlsx");
        $objWorksheet = $objPHPExcel->getActiveSheet();

        //add the new row
        $num_rows = $objPHPExcel->getActiveSheet()->getHighestRow();
        $objWorksheet->insertNewRowBefore($num_rows + 1, 1);
        $name = isset($_POST['name']) ? $_POST['name'] : '';
        if($submit){
    //SAVING THE NEW ROW - on the last position in the table
        $objWorksheet->setCellValueByColumnAndRow(0,$num_rows+1,$name);
        }

        //display the table
        echo '<table>'."\n";
        echo '<thead>
        <tr>
            <th>Company Name</th>
        </tr>
        </thead>'."\n";
        echo '<tbody>'."\n";
        foreach ($objWorksheet->getRowIterator() as $row) {
        echo '<tr>'."\n";
        $cellIterator = $row->getCellIterator();
        $cellIterator->setIterateOnlyExistingCells(false);
        foreach ($cellIterator as $cell) {
        echo '<td>'.$cell->getValue().'</td>'."\n";
        }
        echo '</tr>'."\n";
        }
        echo '</tbody>'."\n";
        echo '</table>'."\n";
        ?>