1

我需要创建一个 csv 以将数据导入数据库,但我有一个困惑

我的 csv 数据与 3 个表相关

那么如何分离以及创建类似 csv 的可能方法 1)如果表 1 中的数据已经存在,则检查所需的数据是否插入或更新了该数据 2)我还要求如果数据未插入结果也显示在同一时间插入未插入ETC...

4

3 回答 3

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>-->
于 2013-12-11T07:54:11.527 回答
1

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

您必须遵循一些规则:-

1.你的csv文件根据数据库表名(例如:db表名是users然后csv应该是users.csv)

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

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.";
    }
}

?>
于 2012-08-09T05:30:28.980 回答
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);
}

根据打印的数据,您可以执行进一步的步骤。

于 2012-08-09T06:20:25.947 回答