php csv导入可能的方法?

时间:2012-08-09 04:57:46

标签: php yii

我需要创建一个csv来导入数据到数据库,但我有一个混乱

我的csv数据与3个表相关

所以如何分离以及创建csv的可能方式如何 1)如果表1中的数据是如此,那么检查所需的数据插入与否 或更新该数据 2)我还要求如果数据没有插入结果也同时插入未插入等...

3 个答案:

答案 0 :(得分:2)

通过使用phpexcel,您可以在Yii框架中轻松导入excel / csv

1.从http://phpexcel.codeplex.com提取下载最新的phpexcel到扩展文件夹

2.在控制器中创建一个动作,给出正确的基本路径和phpexcelpath

public function actionImport()
            {
                  $message = '';
                  if (!empty($_POST))
                     {
                    $file = CUploadedFile::getInstanceByName('import');
                    $spec = Yii::app()->basePath.'/data/imports/'.$file->name;
                    $file->saveAs($spec);



                    spl_autoload_unregister(array('YiiBase','autoload'));




                     $phpExcelPath = Yii::getPathOfAlias('ext.phpexcel.vender');

                       include($phpExcelPath . DIRECTORY_SEPARATOR . 'PHPExcel.php');

                    spl_autoload_register(array('YiiBase', 'autoload'));


                    try {



                         $inputFileType = PHPExcel_IOFactory::identify($spec); 
                         $objReader = PHPExcel_IOFactory::createReader($inputFileType);

                         if ($inputFileType != 'xls')
                            {
                            $objReader->setReadDataOnly(true);
                            }
                        $objPHPExcel = $objReader->load($spec); 
                        $objWorksheet = $objPHPExcel->setActiveSheetIndex(0);
                        $highestRow = $objWorksheet->getHighestRow();
                        for ($row = 1;$row < $highestRow+1; $row++)
                             {
                             $model= new ExamScores; // Yii AR model
                             $model->id = $objWorksheet->getCellByColumnAndRow(1, $row)->getValue();
                             $model->student_id = $objWorksheet->getCellByColumnAndRow(2, $row)->getValue();
                              $model->exam_id = $objWorksheet->getCellByColumnAndRow(3, $row)->getValue();
                              $model->marks = $objWorksheet->getCellByColumnAndRow(4, $row)->getValue();
                             $model->save(false);
                             $model->detachBehaviors(); // PHP < 5.3 memory management
                             unset($model);
                             Yii::app()->user->setFlash('sucess','Mark saved Successfully');
                             }


                        }
                    catch (Exception $e)
                       {
                       $message = 'There was a problem handling your file. Technical details: '.$e->getMessage();

                       }
                    if (! empty($message))
                       {
                       Yii::app()->user->setFlash('error',$message);

                       }
                    }       
                  $this->render('import');
          }

3.在您的视图文件中

<!--<div class="formCon">
<div class="formConInner">-->

<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td width="247" valign="top">

    <?php $this->renderPartial('left_side');?>

    </td>
    <td valign="top">




<h1>IMPORT EXCEL SHEET</h1>

<?php if(Yii::app()->user->hasFlash('sucess')): ?>

<div class="flash-success">
    <?php echo Yii::app()->user->getFlash('sucess'); ?>
</div>

<?php endif; ?>

<div style="background-color: #E6E4E4;">
<table width="100%" cellspacing="2" cellpadding="2">

<tr>
<?php echo CHtml::beginForm('', 'post', array('enctype'=>'multipart/form-data')); ?>
<tr><td>&nbsp;</td></tr>
<td><?php echo CHtml::label('File to Import', 'fti'); ?> 
<?php echo CHtml::fileField('import', '', array('id'=>'fti')); ?></td>
</tr>


<tr><td>&nbsp;</td></tr>
<tr><td>&nbsp;</td></tr>
<tr><td>&nbsp;</td></tr>


<tr>

<td><?php echo CHtml::submitButton('Submit'); ?> </td>


</tr>

<?php echo CHtml::endForm(); ?>
</tr>
</table>


</div>
    </td>

</table>


<!--</div>
</div>-->

答案 1 :(得分:1)

我已经实现了这段代码,它是经过测试的代码。我认为这是非常充分的使用

您遵循一些规则: -

1.您的csv文件根据数据库表名称(例如:db表名是用户,那么csv应该是users.csv)

2.您的csv文件的第一行应该是db表字段名称(例如:Id,name等),然后再开始输入数据

3.您可以从以下网址下载数据源类: - http://code.google.com/p/php-csv-parser/因为我需要在代码下方:require_once'CSV / DataSource.php';

<?php
ini_set('memory_limit','512M');
$dbhost = "localhost";
$dbname = "excel_import";
$dbuser = "root";
$dbpass = "";

$conn=mysql_connect ($dbhost, $dbuser, $dbpass) or die ("I cannot connect to the database because: " . mysql_error());
mysql_select_db($dbname) or die("Unable to select database because: " . mysql_error());


require_once 'CSV/DataSource.php';

$filename = "Book1.csv";
//$filename = $_POST['filename'];
$ext = explode(".",$filename);

$path = "uploads/".$filename;

$dbtable = $ext[0];


import_csv($dbtable, $path);


function import_csv($dbtable, $csv_file_name_with_path)
{
    $csv = new File_CSV_DataSource;
    $csv->load($csv_file_name_with_path);

    $csvData = $csv->connect();

    $res='';
    foreach($csvData  as $key)
    {
        $myKey ='';
        $myVal='';
        foreach($key as $k=>$v)
        {


            $myKey .=$k.',';
            $myVal .="'".$v."',";

        }
        $myKey = substr($myKey, 0, -1);
        $myVal = substr($myVal, 0, -1); 




        $query="insert into ".$dbtable." ($myKey)values($myVal)";
        $res=  mysql_query($query);

    }

    if($res ==1)
    {

    echo "record successfully Import.";
    }else{

    echo "record not successfully Import.";
    }
}

?>

答案 2 :(得分:0)

$row = 1;

if (($handle = fopen("path to your csv file/data.csv", "r")) !== FALSE) 
{
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) 
    {
        $row++;
        print_r($data);
    }

    fclose($handle);
}

根据打印数据,您可以采取进一步措施。