Yii2导出列表到csv文件示例
项目开发中,很多时候要将外部CSV文件导入到数据库中或者将数据导出为CSV文件,那么具体该如何实现呢?本文将使用yii,实现了CSV格式数据的导入和导出功能。代码如下:
/**
* 导出列表.
*/
public function actionRankedexport()
{
$ids = Yii::$app->request->get("ids");
$arrId = empty($ids) ? []:explode(",", $ids);
$title = "姓名,手机号码,二维码,个人/公司"."
";
$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 .= "
";
}
}
$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;
}
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
- 上一篇: yii2 多维数组指定多字段排序
- 下一篇:没有了