简体   繁体   English

如何在php中组织可下载的csv文件

[英]how do I organise a downloadable csv file in php

What I am doing is allowing my client to download a CSV file of all their orders in the database. 我正在做的是允许我的客户在数据库中下载所有订单的CSV文件。 That I can do, but what I can't seem to figure out if how to organise that file so that the information is clear and easy to understand in the file itself. 我可以做到,但是我似乎无法弄清楚如何组织该文件,以便使信息清晰易懂,并且在文件本身中也很容易理解。

Here is my working code that creates the file for download: 这是我的工作代码,用于创建要下载的文件:

$today = date("d-m-Y");
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=orders_' . $today . '.csv');

// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');

// output the column headings
fputcsv($output, array('Product ID & Qty','First Name', 'Last Name', 'Total Spent', 'Payment Date'));

// fetch the data
include('../storescripts/connect_to_mysql.php');
$rows = mysql_query('SELECT product_id_array, first_name, last_name, mc_gross, payment_date FROM transactions ');

// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);

The columns are being created with the headings listed above, but almost all the information is squeezed into the first column and the rest is just spread over the other columns. 这些列是使用上面列出的标题创建的,但是几乎所有信息都被压缩到第一列中,其余信息仅分布在其他列中。 It looks a mess and wouldn't make much sense to anyone. 看起来一团糟,对任何人都没有多大意义。

I was wondering if there was a way to force which row of data goes into each column. 我想知道是否有一种方法可以强制哪一行数据进入每一列。 Thanks in advance. 提前致谢。

默认情况下,当Excel读取CSV时,它不会自动展开所有列,因此,实际上只需要配置Excel或手动展开它们时,数据看起来就好像CSV内容本身有问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM