Yii2导出列表到csv文件示例

来源:互联网 发布:星星知多少的自频道 编辑:程序博客网 时间:2024/06/05 17:13

项目开发中,很多时候要将外部CSV文件导入到数据库中或者将数据导出为CSV文件,那么具体该如何实现呢?本文将使用yii,实现了CSV格式数据的导入和导出功能。代码如下:

/**     * 导出列表.     */    public function actionRankedexport()    {        $ids = Yii::$app->request->get('ids');        $arrId = empty($ids) ? []:explode(',', $ids);        $title = '姓名,手机号码,二维码,个人/公司'."\n";        $fileName = '用户信息'.date('Ymd').'.csv';        // 列表        $dataArr = WechatPosterUsers::find()->andFilterWhere(['in', 'id', $arrId])->asArray()->all();        $wrstr = '';        if(!empty($dataArr)){            foreach ($dataArr as $key => $value) {                $imageurl = Yii::$app->params['frontendurl'].$value['qr_code'];                $wrstr .= $value['name'] . ',' . $value['phone'] . ',' . $imageurl . ',' . WechatPosterUsers::getTypeName($value['type']);                $wrstr .= "\n";            }        }        $this->Csvexport( $fileName, $title, $wrstr);    }    /**     * 导出文件.     */    public function Csvexport($file = '', $title = '', $data)    {        header("Content-Disposition:attachment;filename=".$file);        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');        header('Content-Transfer-Encoding: binary');        header('Cache-Control: must-revalidate');        header('Pragma: public');        // ob_start();        //表头        $wrstr = $title;        //内容        $wrstr .= $data;        $wrstr = iconv("utf-8", "GBK//ignore", $wrstr);         // ob_end_clean();        echo $wrstr;    }
0 0
原创粉丝点击