使用PHP或PHPExcel删除CSV文件中的空白行?

时间:2013-10-21 14:19:49

标签: php csv phpexcel

我正在尝试使用PHP以编程方式删除CSV文件中的空白行。文件上传到站点并使用PHPExcel转换为CSV。正在生成一种特殊类型的CSV,数据行之间有空行,我正在尝试用PHP清理它们而没有任何运气。以下是此CSV的示例:https://gist.github.com/vinmassaro/467ea98151e26a79d556

我需要使用PHPExcel或标准PHP函数加载CSV,删除空行并保存。提前谢谢。

编辑: 以下是使用PHPExcel进行转换的代码段。这是Drupal钩子的一部分,作用于刚刚上传的文件。我无法使用PHPExcel removeRow方法,因为它似乎不能用于空白行,只能处理空数据行。

// Load the PHPExcel IOFactory.
require_once(drupal_realpath(drupal_get_path('module', 'custom')) . '/PHPExcel/Classes/PHPExcel/IOFactory.php');

// Load the uploaded file into PHPExcel for normalization.
$loaded_file = PHPExcel_IOFactory::load(drupal_realpath($original_file->uri));
$writer = PHPExcel_IOFactory::createWriter($loaded_file, 'CSV');
$writer->setDelimiter(",");
$writer->setEnclosure("");

// Get path to files directory and build a new filename and filepath.
$files_directory = drupal_realpath(variable_get('file_public_path', conf_path() . '/files'));
$new_filename = pathinfo($original_file->filename, PATHINFO_FILENAME) . '.csv';
$temp_filepath = $files_directory . '/' . $new_filename;

// Save the file with PHPExcel to the temp location. It will be deleted later.
$writer->save($temp_filepath);

3 个答案:

答案 0 :(得分:2)

如果您想使用phpexcel,请搜索CSV.php 并编辑此文件:

// Write rows to file
for ($row = 1; $row <= $maxRow; ++$row) {
    // Convert the row to an array...
    $cellsArray = $sheet->rangeToArray('A'.$row.':'.$maxCol.$row, '', $this->preCalculateFormulas);
    // edit by ger
    //  if last row, then no linebreak will added
    if($row == $maxRow){ $ifMaxRow = TRUE; }else{ $ifMaxRow = False; }
    // ... and write to the file
    $this->writeLine($fileHandle, $cellsArray[0], $ifMaxRow);
}

在文件末尾编辑本

 /**
 *  Write line to CSV file
 *  
 *  edit by ger
 *  
 *  @param    mixed    $pFileHandle    PHP filehandle
 *  @param    array    $pValues        Array containing values in a row
 *  @throws    PHPExcel_Writer_Exception
 */
private function writeLine($pFileHandle = null, $pValues = null, $ifMaxRow = false)
{
...
            // Add enclosed string
            $line .= $this->enclosure . $element . $this->enclosure;
        }

insert this following     

        if($ifMaxRow == false){
           // Add line ending
           $line .= $this->lineEnding;
        }

答案 1 :(得分:1)

在Mihai Iorga的评论中使用str_replace将起作用。类似的东西:

$csv = file_get_contents('path/file.csv');
$no_blanks = str_replace("\r\n\r\n", "\r\n", $csv);
file_put_contents('path/file.csv', $no_blanks);

我复制了您发布的示例中的文字,虽然我必须将“查找”参数更改为"\r\n \r\n"而不是"\r\n\r\n",因为每个帖子都有一个空格。 blank- 寻找行。

答案 2 :(得分:0)

试试这个:

<?php

$handle = fopen("test.csv", 'r'); //your csv file
$clean = fopen("clean.csv", 'a+'); //new file with no empty rows

while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $num = count($data);
    if($num > 1)
    fputcsv($clean, $data ,";");
}
fclose($handle);
fclose($clean);

?>

在我的本地主机上测试过。

输出数据:

初始档案:

col1,col2,col3,col4,col5,col6,col7,col8

0,229.500,7.4,3165.5,62,20.3922,15.1594,0

1,229.600,8.99608,3156.75,62,15.6863,16.882,0

2,229.700,7.2549,3130.25,62,16.8627,15.9633,0

3,229.800,7.1098,3181,62,17.2549,14.1258,0

清理Csv文件:

col1    col2    col3    col4    col5    col6    col7    col8
0       229.500 7.4     3165.5    62    203.922 151.594 0
1       229.600 899.608 3156.75   62    156.863 16.882  0
2       229.700 72.549  3130.25   62    168.627 159.633 0
3       229.800 71.098  3181      62    172.549 141.258 0