laravel使用xlswriter实现导出10万条数据以及导出成功发送邮件

Song899 次浏览0个评论2023年07月11日

最近需要开发Excel批量导出系统,客户可以主动导出访问数据,每次可能都有十多万条数据;使用 laravelxlswriter 实现分块批量导出。

一、安装版本xlswriter

pecl install xlswriter
# 添加 extension = xlswriter.so 到 ini 配置

安装过程中遇到了问题是因为服务器安装了两个php版本,卸载老的版本解决了;其他方式参考: xlswriter官方文档

二、快速上手

导出Excel文件案例

$config = [
    path => /home/viest // xlsx文件保存路径
];
$excel = new \Vtiful\Kernel\Excel($config);
// fileName 会自动创建一个工作表,你可以自定义该工作表名称,工作表名称为可选参数
$filePath = $excel->fileName(tutorial01.xlsx, sheet1)
->header([Item, Cost])
->data([
    [Rent, 1000],
    [Gas, 100],
    [Food, 300],
    [Gym, 50],
])
->output();

读取Excel案例

$config = [path => ./tests];
$excel = new \Vtiful\Kernel\Excel($config);
// 导出测试文件
$filePath = $excel->fileName(tutorial.xlsx)->header([Item, Cost])->output();
// 读取测试文件
$data = $excel->openFile(tutorial.xlsx)->openSheet()->getSheetData();
var_dump($data); // [[Item, Cost]]

三、分块批量导出Excel数据文件

本处大概提供思路,我们可以添加到队列然后交给后端处理,具体您根据您的业务来:

$excel = new \Vtiful\Kernel\Excel($config);
$fileObject = $excel->constMemory($this->order_id.".xlsx", NULL, false);
$this->excel = $fileObject->header([订单ID,订单名称,订单金额]);
$starttime = time();
DB::table("orders")->where("order_id",$this->order_id)->orderBy("id","ASC")->chunk(1000, function ($orders) {
    foreach ($orders as $order) {
        $this->excel->insertText($this->row, 0, $order->order_id);
        $this->excel->insertText($this->row, 1, $order->name);
        $this->excel->insertText($this->row, 2, $order->price);
        $this->row += 1;
    }
});
$this->excel->output();

测试导出10万条数据花费1分钟左右。

更多您参考官方文档即可:php-xlswriter官方文档

提交评论

请登录后评论

用户评论

    当前暂无评价,快来发表您的观点吧...

更多相关好文