【问题标题】:Delete blank lines in CSV file with PHP or PHPExcel?使用 PHP 或 PHPExcel 删除 CSV 文件中的空行?
【发布时间】:2018-03-20 01:11:23
【问题描述】:

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

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

编辑: 这是当前使用 PHPExcel 转换它的方式的 sn-p。这是 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);

【问题讨论】:

  • 考虑显示您使用的代码的相关部分...使用 PHPExcel 转换为 CSV。
  • echo str_replace("\r\n\r\n", "\r\n", $csv); 不起作用? :)
  • 你在使用 FTP 吗?如果你在文本模式下传输,你可以得到双行尾stackoverflow.com/questions/11938942/…
  • 此转换处理来自不同来源的文件,然后使用 HighCharts 库将 CSV 文件可视化。最近的一位消息人士试图以这种格式提交文件,但由于空白行而导致可视化失败。

标签: php csv phpexcel


【解决方案1】:

如果你想使用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;
        }

【讨论】:

    【解决方案2】:

    在 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",因为每个空白处都有一个空格-行。

    【讨论】:

    • 我不得不稍微调整一下正则表达式,但这种方法效果很好。谢谢!
    【解决方案3】:

    试试这个:

    <?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
    

    【讨论】:

    • 谢谢,稍后我会试一试并报告。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-17
    • 1970-01-01
    • 2017-06-21
    • 1970-01-01
    • 2019-03-21
    • 2021-09-27
    • 1970-01-01
    相关资源
    最近更新 更多