用于CodeIgniter的CSV导入库

时间:2013-03-16 07:35:26

标签: php csv codeigniter-2 helper xls

需要将csv或xls导入到使用CodeIgniter创建的Application中。这有什么图书馆吗?任何建议都表示赞赏。

5 个答案:

答案 0 :(得分:22)

这是一种简单的方法。我不知道人们做了什么,但我使用了这个

这是我的csv阅读器库

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class CSVReader {

    var $fields;            /** columns names retrieved after parsing */ 
    var $separator = ';';    /** separator used to explode each line */
    var $enclosure = '"';    /** enclosure used to decorate each field */

    var $max_row_size = 4096;    /** maximum row size to be used for decoding */

    function parse_file($p_Filepath) {

        $file = fopen($p_Filepath, 'r');
        $this->fields = fgetcsv($file, $this->max_row_size, $this->separator, $this->enclosure);
        $keys_values = explode(',',$this->fields[0]);

        $content    =   array();
        $keys   =   $this->escape_string($keys_values);

        $i  =   1;
        while( ($row = fgetcsv($file, $this->max_row_size, $this->separator, $this->enclosure)) != false ) {            
            if( $row != null ) { // skip empty lines
                $values =   explode(',',$row[0]);
                if(count($keys) == count($values)){
                    $arr    =   array();
                    $new_values =   array();
                    $new_values =   $this->escape_string($values);
                    for($j=0;$j<count($keys);$j++){
                        if($keys[$j] != ""){
                            $arr[$keys[$j]] =   $new_values[$j];
                        }
                    }

                    $content[$i]=   $arr;
                    $i++;
                }
            }
        }
        fclose($file);
        return $content;
    }

    function escape_string($data){
        $result =   array();
        foreach($data as $row){
            $result[]   =   str_replace('"', '',$row);
        }
        return $result;
    }   
}
?> 

和控制器方法

function readExcel()
{
        $this->load->library('csvreader');
        $result =   $this->csvreader->parse_file('Test.csv');

        $data['csvData'] =  $result;
        $this->load->view('view_csv', $data);  
}

这是观点

<table cellpadding="0" cellspacing="0" width="100%">
    <tr>
            <td width = "10%">ID</td>
            <td width = "20%">NAME</td>
            <td width = "20%">SHORT DESCRIPTION</td>
            <td width = "30%">LONG DESCRIPTION</td>
            <td width = "10%">STATUS</td>
            <td width = "10%">PARENTID</td>
    </tr>

            <?php foreach($csvData as $field){?>
                <tr>
                    <td><?php echo $field['id']?></td>
                    <td><?php echo $field['name']?></td>
                    <td><?php echo $field['shortdesc']?></td>
                    <td><?php echo $field['longdesc']?></td>
                    <td><?php echo $field['status']?></td>
                    <td><?php echo $field['parentid']?></td>
                </tr>
            <?php }?>
</table>

参考Here

答案 1 :(得分:3)

这是raheel shan接受的答案的改进版本 - 我编辑了他的答案,但我的编辑被拒绝,但这是一个重要的变化......

在解析每个数据行时,在逗号上使用for el in xl: print el for iel in el: print ' '*4 + str(iel) for iiel in iel: print ' '*8 + str(iiel) >>> [[0, 0], [-1, 1], [-2, 2]] [0, 0] 0 0 [-1, 1] -1 1 [-2, 2] -2 2 [[-3, 3], [-4, 4], [-5, 5]] [-3, 3] -3 3 [-4, 4] -4 4 [-5, 5] -5 是不明智的,因为这不会处理包含逗号的引用包含的字符串。爆炸将这些字符串分解为子字符串并在explode()中提供额外的数组元素,因此此检查失败:

$values

相反,PHP有一个专用的方法来处理这个问题; str_getcsv()。我已相应更新了原始答案代码。

CSV阅读器库:

if (count($keys) == count($values)) {

控制器方法:

<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class CSVReader {

    var $fields;/** columns names retrieved after parsing */
    var $separator = ';';/** separator used to explode each line */
    var $enclosure = '"';/** enclosure used to decorate each field */
    var $max_row_size = 4096;/** maximum row size to be used for decoding */

    function parse_file($p_Filepath) {

        $file = fopen($p_Filepath, 'r');
        $this->fields = fgetcsv($file, $this->max_row_size, $this->separator, $this->enclosure);
        $keys = str_getcsv($this->fields[0]);

        $i = 1;
        while (($row = fgetcsv($file, $this->max_row_size, $this->separator, $this->enclosure)) != false) {
            if ($row != null) { // skip empty lines
                $values = str_getcsv($row[0]);
                if (count($keys) == count($values)) {
                    $arr = array();
                    for ($j = 0; $j < count($keys); $j++) {
                        if ($keys[$j] != "") {
                            $arr[$keys[$j]] = $values[$j];
                        }
                    }

                    $content[$i] = $arr;
                    $i++;
                }
            }
        }
        fclose($file);
        return $content;
    }

}
?>

这就是观点:

function readExcel() {
    $this->load->library('csvreader');
    $result = $this->csvreader->parse_file('Test.csv');
    $data['csvData'] = $result;
    $this->load->view('view_csv', $data);
}

答案 2 :(得分:2)

好吧不要介意我,我只是修改了ajmedway的库以包含分隔符,以防万一你想从TSV或管道分隔文件中获取数据。如果你想要普通的旧CSV,他就可以了。

class CSVReader {

var $fields;/** columns names retrieved after parsing */
var $separator = ';';/** separator used to explode each line */
var $enclosure = '"';/** enclosure used to decorate each field */
var $max_row_size = 4096;/** maximum row size to be used for decoding */

function parse_file($p_Filepath, $delimiter = FALSE ) {

    $file = fopen($p_Filepath, 'r');
    $this->fields = fgetcsv($file, $this->max_row_size, $this->separator, $this->enclosure);
    if ($delimiter==FALSE)
    {
    $keys = str_getcsv($this->fields[0]);

    $i = 1;
    while (($row = fgetcsv($file, $this->max_row_size, $this->separator, $this->enclosure)) != false) {
        if ($row != null) { // skip empty lines
            $values = str_getcsv($row[0]);
            if (count($keys) == count($values)) {
                $arr = array();
                for ($j = 0; $j < count($keys); $j++) {
                    if ($keys[$j] != "") {
                        $arr[$keys[$j]] = $values[$j];
                    }
                }

                $content[$i] = $arr;
                $i++;
            }
        }
    }
    }
    else{
        $keys = str_getcsv($this->fields[0],$delimiter);

        $i = 1;
        while (($row = fgetcsv($file, $this->max_row_size, $this->separator, $this->enclosure)) != false) {
            if ($row != null) { // skip empty lines
                $values = str_getcsv($row[0],$delimiter);
                if (count($keys) == count($values)) {
                    $arr = array();
                    for ($j = 0; $j < count($keys); $j++) {
                        if ($keys[$j] != "") {
                            $arr[$keys[$j]] = $values[$j];
                        }
                    }

                    $content[$i] = $arr;
                    $i++;
                }
            }
        }
    }

    fclose($file);
    return $content;
}}?>

答案 3 :(得分:0)

这是空行和额外空格和标签的改进版本......

类CSVReader {

function csv_to_array($Filepath)
{
    //Get csv file content
    $csvData = file_get_contents($Filepath);

    //Remove empty lines
    $csvData = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\r\n", $csvData);

    //String convert in array formate and remove double quote(")
    $array = array();
    $array = $this->escape_string(preg_split('/\r\n|\r|\n/', $csvData));
    $new_content_in_array = array();
    if($array)
    {
        //Get array key
        $array_keys = array();
        $array_keys = array_filter(array_map('trim', explode(';',$array[0])));

        //Get array value
        $array_values = array();
        for ($i=1;$i<count($array);$i++)
        {
            if($array[$i])
            {
                $array_values[] = array_filter(array_map('trim', explode(';',$array[$i])));
            }
        }

        //Convert in associative array
        if($array_keys && $array_values)
        {
            $assoc_array = array();
            foreach ($array_values as $ky => $val)
            {           
                for($j=0;$j<count($array_keys);$j++){
                    if($array_keys[$j] != "" && $val[$j] != "" && (count($array_keys) == count($val)))
                    {
                        $assoc_array[$array_keys[$j]] = $val[$j];
                    }
                }
                $new_content_in_array[] = $assoc_array;
            }
        }
    }
    return $new_content_in_array;
}

function escape_string($data){
    $result =   array();
    foreach($data as $row){
        $result[]   = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "", str_replace('"', '',$row));
    }
    return $result;
}   

} ?&GT;

答案 4 :(得分:-1)

呼叫控制器:

$this->load->library('csvreader');
$import_csv_data = $this->csvreader->csv_to_array($path);
print_r($import_csv_data );
exit;