thinkphp5 匯入/匯出 Csv檔案
1,在thinkphp/library/think下新建Csv.php檔案,
Csv.php 程式碼
<?php
namespace Think;
class Csv
{
//匯出csv檔案
public function put_csv($list,$title)
{
$file_name = "exam".time().".csv";
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename='.$file_name );
header('Cache-Control: max-age=0');
$file = fopen('php://output',"a");
$limit = 1000;
$calc = 0;
foreach ($title as $v){
$tit[] = iconv('UTF-8', 'GB2312//IGNORE',$v);
}
fputcsv($file,$tit);
foreach ($list as $v){
$calc++;
if($limit == $calc){
ob_flush();
flush();
$calc = 0;
}
foreach($v as $t){
$tarr[] = iconv('UTF-8', 'GB2312//IGNORE',$t);
}
fputcsv($file,$tarr);
unset($tarr);
}
unset($list);
fclose($file);
exit();
}
// csv匯入,此格式每次最多可以處理1000條資料
public function input_csv($csv_file) {
$result_arr = array ();
$i = 0;
while($data_line = fgetcsv($csv_file,10000)) {
if ($i == 0) {
$GLOBALS ['csv_key_name_arr'] = $data_line;
$i ++;
continue;
}
foreach($GLOBALS['csv_key_name_arr'] as $csv_key_num => $csv_key_name ) {
$result_arr[$i][$csv_key_name] = $data_line[$csv_key_num];
}
$i++;
}
return $result_arr;
}
}
?>
2,控制器中呼叫
<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
use think\Db;
use think\Paginator;
use think\Validate;
use think\Csv; //此處是csv檔案實現的關鍵
class Index extends Controller
{
public function _initialize()
{
header("Content-type:text/html;charset=utf-8");
}
/*
* CSV試題匯出
*/
public function downQuestions()
{
$condition['qu_status'] = array('gt','-1');
$csv = new Csv(); //例項化後才可以呼叫之前類檔案定義好的方法
$list = Db::table('gw_questions')->field('qu_name,qu_options,qu_answer,qu_describe,gw_topic.to_name,qu_time,te_name')->join('gw_topic','gw_topic.to_id=gw_questions.to_id')->join('gw_teacher','gw_teacher.te_id=gw_questions.te_id','LEFT')->where($condition)->select();
$csv_title = array('題幹內容','選項詳情','參考答案','答案解析','題型','錄入時間','錄入人');
$csv->put_csv($list,$csv_title);
}
/*
* CSV試題匯入
*/
public function upQuestionsWrite()
{
// 獲取表單上傳檔案
$file = request()->file('examfile');
if(empty($file)) {
$this->error('請選擇上傳檔案');
}
// 移動到框架應用根目錄/public/uploads/ 目錄下
$info = $file->move(ROOT_PATH.'public'.DS.'upload');
//獲取檔案(日期/檔案),$info->getFilename();
$filename = ROOT_PATH.'public'.DS.'upload/'.$info->getSaveName();
$handle = fopen($filename,'r');
$csv = new Csv();
$result = $csv->input_csv($handle); // 解析csv
$len_result = count($result);
if($len_result == 0){
$this->error('此檔案中沒有資料!');
}
$data_values = '';
for($i = 1;$i < $len_result+1;$i ++) { // 迴圈獲取各欄位值
$arr = array_values($result[$i]);
$qu_name = iconv('gb2312','utf-8',$arr[0] ); // 中文轉碼
$qu_options = iconv('gb2312','utf-8',$arr[1]);
$qu_answer = $arr[2];
$qu_describe = iconv('gb2312','utf-8',$arr[3]);
$to_id = $arr[4];
$te_id = 1; //新增試題的教師
$data_values .= "('$qu_name','$qu_options','$qu_answer','$qu_describe','$to_id','$te_id'),";
}
$data_values = substr($data_values,0,- 1 ); // 去掉最後一個逗號
fclose($handle); // 關閉指標
// 批量插入資料表中
$result = DB::execute("insert into gw_questions (qu_name,qu_options,qu_answer,qu_describe,to_id,te_id) values $data_values" );
if($result){
$this->success('檔案上傳成功,資料已經匯入!','exampaper',3);
}else{
// 上傳失敗獲取錯誤資訊
$this->error($file->getError());
}
}
}
?>
3,HTML與JavaScript部分
<form action="{:url('index/index/upQuestionsWrite')}" method="post" class="form form-horizontal" enctype="multipart/form-data" id="addform">
<div class="row cl">
<label class="form-label col-xs-4 col-sm-2">選擇試題檔案:</label>
<div class="btn-upload form-group">
<input type="text" name="uploadfile" id="uploadfile" class="input-text upload-url radius" readonly> <a href="javascript:void();" class="btn btn-primary radius"><i class="Hui-iconfont"></i>瀏覽檔案</a>
<input type="file" name="examfile" class="input-file" multiple>
</div>
<a class="btn btn-success btn-submit">匯入試題</a>
</div>
</form>
<script type="text/javascript">
$(function(){
//表單提交時判斷是否有檔案存在
$(".btn-submit").click(function(){
if($("input[name='uploadfile']").val() == ''){
alert("請選擇CSV檔案!");
return false;
}else{
$("#addform").submit();
}
});
});
</script>