3

我有一个脚本,可以在 excel 文件的一行中输入表单数据。每次发送表单时,都会将新数据附加到同一个 Excel 文件中。

问题是新数据附加了两行。所以在每行之间插入一个空白行。

这是代码。$data 包含 $_POST 数据。

function generateExcel($data) {
    $filename = dirname(__FILE__).'/myexcelfile.xlsx';

    // this is shortened
    $columns = array(
        'fieldname1' => 'Column 1', 
        'fieldname2' => 'Column 2', 
    );

    // check if file exist
    if(file_exists($filename)) {

        // load existing excel file
        $objPHPExcel = PHPExcel_IOFactory::load($filename);

    } else {

        // Create new PHPExcel object
        $objPHPExcel = new PHPExcel();
        $objWorksheet = $objPHPExcel->getActiveSheet();

        $objWorksheet->insertNewRowBefore(1, 1);

        // Set column names
        $columnIndex = 0;
        foreach($columns as $columnName) {
            $objWorksheet->setCellValueByColumnAndRow($columnIndex, 1, $columnName);
            $columnIndex++;
        }
    }

    // get sheet and highest row
    $objWorksheet = $objPHPExcel->getActiveSheet();
    $numberOfRows = $objPHPExcel->getActiveSheet()->getHighestRow();

    // Insert a new row after highest row
    $objWorksheet->insertNewRowBefore($numberOfRows + 1, 1);

    // Get the highest row again (should be one more since last time)
    // $numberOfRows2 = $objPHPExcel->getActiveSheet()->getHighestRow();

    // Insert data for each column
    $columnIndex = 0;
    foreach($columns as $fieldName => $columnName) {
        $fieldValue = $data[$fieldName];

        $objWorksheet->setCellValueByColumnAndRow($columnIndex, $numberOfRows + 1, $fieldValue);

        $columnIndex++;
    }

    // Save Excel 2007 file
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    $objWriter->save($filename);
}

这就是我使用的: https ://stackoverflow.com/a/12417477

http://i.imgur.com/eYIIktZ.png

4

1 回答 1

0

我只是猜测,我们可以试试这个

$objWorksheet->setCellValueByColumnAndRow($columnIndex,"",$columnName);

代替

$objWorksheet->setCellValueByColumnAndRow($columnIndex, 1, $columnName);
于 2013-05-10T10:09:22.110 回答