php导出数据到多个csv并打包压缩

以下代码都是以yii2框架的语法为示例进行演示,其它写法类似:

1.不压缩直接下载

// 测试php导出大量数据到csv
public function actionExportData()
{
    // 设置不超时
    set_time_limit(0);
    // 设置最大可用内存
    ini_set('memory_limit', '1024M');
    // 设置第一列名标题名称
    $columns = ['id', 'username', 'email'];

    header('Content-Description: File Transfer');
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment; filename="导出数据-'.date('Y-m-d', time()).'.csv"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');

    // 打开output流
    $fp = fopen('php://output', 'a');
    // 把变量从UTF-8转成GBK编码
    mb_convert_variables('GBK', 'UTF-8', $columns);
    // 将数据格式化为CSV格式并写入到output流中
    fputcsv($fp, $columns);

    foreach (User::find()->select('id, username, email')->where(['status' => 10])->batch(100) as $items) {
        foreach ($items as $item) {
            $rowData = [
                'id' => $item->id,
                'username' => $item->username ?: '',
                'email' => $item->email ?: '',
            ];
            mb_convert_variables('GBK', 'UTF-8', $rowData);
            fputcsv($fp, $rowData);
        }
        // 刷新输出缓冲区,防止内存溢出
        ob_flush();
        flush();
    }
    fclose($fp);
    exit();
}

2.导出成多个文件并打包成zip文件

public function actionZip()
{
    // 设置不超时
    set_time_limit(0);
    // 设置最大可用内存
    ini_set('memory_limit', '1024M');
    // 设置第一列名标题名称
    $columns = ['id', 'username', 'email'];
    // 下面以分页形式导出
    // 总记录数
    $countUser = User::find()->where(['status' => 10])->count();
    // 总页数
    $pages = ceil($countUser / 200);
    $fileArr = [];
    for ($i = 0; $i < $pages; $i++) {
        if ($i == 0) {
            // 打开一个临时文件
            $filename = dirname(__DIR__) . '/components/page' . $i . '.csv';
            $fileArr[] = $filename;
            // 打开一个文件句柄
            $fp = fopen($filename, 'w');
            // 把变量从UTF-8转成GBK编码
            mb_convert_variables('GBK', 'UTF-8', $columns);
            fputcsv($fp, $columns);
        }
        $users = User::find()
            ->select('id, username, email')
            ->where(['status' => 10])
            ->asArray()
            ->limit(200)
            ->offset($i * 200)
            ->all();
        foreach ($users as $user) {
            mb_convert_variables('GBK', 'UTF-8', $user);
            fputcsv($fp, $user);
        }
        // 刷新输出缓冲区
        //ob_flush();
        //flush();
        // 当已经输出5页的数据时再新建一个文件
        if ($i != 0 && $i % 10 == 0) {
            // 关闭当前文件
            fclose($fp);
            // 重新打开一个新文件
            // 打开一个临时文件
            $filename = dirname(__DIR__) . '/components/page' . $i . '.csv';
            $fileArr[] = $filename;
            // 打开一个文件句柄
            $fp = fopen($filename, 'w');
            // 把变量从UTF-8转成GBK编码
            mb_convert_variables('GBK', 'UTF-8', $columns);
            fputcsv($fp, $columns);
        }
        if ($i == ($pages - 1)) {
            // 如果是最后一页,执行完就关闭文件
            fclose($fp);
        }
    }
    // 压缩打包
    $zip = new \ZipArchive();
    $zipName = dirname(__DIR__) . '/components/' . time() . '.zip';
    $zip->open($zipName, \ZipArchive::CREATE);
    foreach ($fileArr as $file) {
        $zip->addFile($file, basename($file));
    }
    $zip->close();
    foreach ($fileArr as $file) {
        unlink($file);
    }
    header('Content-disposition: attachment; filename=' . basename($zipName));
    header("Content-Type: application/zip");
    header("Content-Transfer-Encoding: binary");
    header('Content-Length: ' . filesize($zipName));
    readfile($zipName);
    @unlink($zipName);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用Spring Boot将数据导出CSV文件并进行压缩的示例: 1. 添加依赖项 在 pom.xml 文件中添加以下依赖项: ```xml <dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>5.5.2</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-compress</artifactId> <version>1.21</version> </dependency> ``` 2. 创建CSV文件 使用 OpenCSV 库创建 CSV 文件。在本例中,我们将使用以下数据作为示例: ```java List<String[]> data = new ArrayList<>(); data.add(new String[]{"Name", "Age", "Email"}); data.add(new String[]{"John", "30", "[email protected]"}); data.add(new String[]{"Jane", "25", "[email protected]"}); data.add(new String[]{"Mike", "35", "[email protected]"}); ``` 创建 CSV 文件的代码如下: ```java CSVWriter writer = new CSVWriter(new FileWriter("data.csv")); writer.writeAll(data); writer.close(); ``` 3. 压缩CSV文件 使用 Apache Commons Compress 库将生成的 CSV 文件压缩为 zip 文件。以下是将 CSV 文件压缩为 zip 文件的代码: ```java FileInputStream inputStream = new FileInputStream("data.csv"); ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream("data.zip")); ZipEntry zipEntry = new ZipEntry("data.csv"); zipOutputStream.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int length; while ((length = inputStream.read(bytes)) >= 0) { zipOutputStream.write(bytes, 0, length); } zipOutputStream.closeEntry(); zipOutputStream.close(); inputStream.close(); ``` 4. 完整代码 以下是将数据导出CSV 文件并进行压缩的完整代码: ```java import com.opencsv.CSVWriter; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class CsvExporter { public static void main(String[] args) throws IOException { List<String[]> data = new ArrayList<>(); data.add(new String[]{"Name", "Age", "Email"}); data.add(new String[]{"John", "30", "[email protected]"}); data.add(new String[]{"Jane", "25", "[email protected]"}); data.add(new String[]{"Mike", "35", "[email protected]"}); CSVWriter writer = new CSVWriter(new FileWriter("data.csv")); writer.writeAll(data); writer.close(); FileInputStream inputStream = new FileInputStream("data.csv"); ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream("data.zip")); ZipEntry zipEntry = new ZipEntry("data.csv"); zipOutputStream.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int length; while ((length = inputStream.read(bytes)) >= 0) { zipOutputStream.write(bytes, 0, length); } zipOutputStream.closeEntry(); zipOutputStream.close(); inputStream.close(); } } ``` 此代码将生成名为 `data.zip` 的压缩文件,其中包含名为 `data.csv` 的 CSV 文件

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值