PHP 生成.csv 文件并下载到浏览器

最近做了一个项目需要把订单的信息显示出来,并且能够把相关信息放到一个.csv 文件中,下载到浏览器。首先我要说明的是.csv 文件,PHP 有专门的函数去解析该类型的文件,相关函数大家可以去官网查看。注意.csv 文件内容的编码格式是gbk格式的,所以有必要对字符格式进行转码。文件的样式如下。

一、首先要定义header 头

               // 输出Excel文件头,可把user.csv换成你要的文件名
		header ( 'Content-Type: application/vnd.ms-excel' );
		header ( 'Content-Disposition: attachment;filename="订单数据.csv"' );
		header ( 'Cache-Control: max-age=0' );
		// 打开PHP文件句柄,php://output 表示直接输出到浏览器
		$fp = fopen ( 'php://output', 'a' );
		// 输出Excel列名信息

二 、下面是文件的头部

               $head = array ('订单号','','订单名称','','业务ID','','渠道ID','','渠道类型','','产品线名称','','原始订单号','','订单金额',
				'','From值','','订单时间','','收款合同号','','渠道名称','','付款合同号','','供应商名称','','运营平台','','产品类型',
				'','记账时间','','渠道成本比例','','渠道成本','','应收账款','','结算比例','','应付结算','','是否已回款','','是否已提批次',
				'','备注');
		foreach ( $head as $i => $v ) {
			// CSV的Excel支持GBK编码,一定要转换,否则乱码
			$head [$i] = iconv ( 'utf-8', 'gbk', $v );
		}
		// 将数据通过fputcsv写到文件句柄
		fputcsv ( $fp, $head );

三、下面是文件的内容,以我的例子是从数据库读出来的,看不懂没关系,原理是把结果查出来放到数组中,循环数组,把每个结果放到一个新的数组并且进行编码。忘了告诉你我用的是CI(codeignite)框架

                     if ($this->input->get () != false) {
			// 从数据库中获取数据,为了节省内存,不要把数据一次性读到内存,从句柄中一行一行读即可
			$sql = "select Charge_final.charge_id,
						   Charge_final.product_name,
					       Charge_final.business_id,
						   Charge_final.channel_id,
					       Charge_final.channel_type,
						   bass_productline.product_line_name,
						   Charge_final.business_linkid,
						   Charge_final.fee,
						   Charge_final.msgfrom,
					       Charge_final.charge_time,
					       Charge_final.income_contract,
					       Charge_final.income_channel_name,
					       Charge_final.payment_contract,
					       Charge_final.merchant_name,
					       Charge_final.platform,
					       Charge_final.product_type,
					       Charge_final.bill_time,
					       Charge_final.channel_rate,
					       Charge_final.channel_fee,
					       (Charge_final.fee-Charge_final.channel_fee) as account,
					       Charge_final.payment_rate,
					       Charge_final.payment_fee,
					       Charge_final.income_id,
					       Charge_final.payment_id,
					       Charge_final.note
						   from {$this->Charge_final} as Charge_final left join
						   {$this->bass_productline} as bass_productline
						   on Charge_final.channel_id=bass_productline.channel_id and
			               Charge_final.channel_type=bass_productline.channel_type
			                where 1=1 $conditions order by Charge_final.charge_time desc";
		   $query = $this->db->query ( $sql );
			// 计数器
			$cnt = 0;
			// 每隔$limit行,刷新一下输出buffer,不要太大,也不要太小
			$limit = 8000;
			foreach ( $query->result_array () as $row ) {
				$cnt ++;
				if ($limit == $cnt) { // 刷新一下输出buffer,防止由于数据过多造成问题
					ob_flush ();
					flush ();
					$cnt = 0;
				}
				$income_id=$row['income_id']==0?'未回款':'回款';
				$payment_id=$row['payment_id']==0?'未提':'已提';
				// 读取表数据
				$content = array ();
				$content [] = iconv ( 'utf-8', 'gbk', $row ['charge_id'] . "\t" );
				$content [] = '';
				$content [] = iconv ( 'utf-8', 'gbk', $row ['product_name'] );
				$content [] = '';
				$content [] = iconv ( 'utf-8', 'gbk', $row ['business_id'] . "\t" );
				$content [] = '';
				$content [] = iconv ( 'utf-8', 'gbk', $row ['channel_id'] . "\t" );
				$content [] = '';
				$content [] = iconv ( 'utf-8', 'gbk', $row ['channel_type'] );
				$content [] = '';
				$content [] = iconv ( 'utf-8', 'gbk', $row ['product_line_name'] );
				$content [] = '';
				$content [] = iconv ( 'utf-8', 'gbk', $row ['business_linkid'] );
				$content [] = '';
				$content [] = iconv ( 'utf-8', 'gbk', $row ['fee'] );
				$content [] = '';
				$content [] = iconv ( 'utf-8', 'gbk', $row ['msgfrom'] );
				$content [] = '';
				$content [] = iconv ( 'utf-8', 'gbk', $row ['charge_time'] . "\t" );
				$content [] = '';
				$content [] = iconv ( 'utf-8', 'gbk', $row ['income_contract'] );
				$content [] = '';
				$content [] = iconv ( 'utf-8', 'gbk', $row ['income_channel_name'] );
				$content [] = '';
				$content [] = iconv ( 'utf-8', 'gbk', $row ['payment_contract'] );
				$content [] = '';
				$content [] = iconv ( 'utf-8', 'gbk', $row ['merchant_name'] );
				$content [] = '';
				$content [] = iconv ( 'utf-8', 'gbk', $row ['platform'] );
				$content [] = '';
				$content [] = iconv ( 'utf-8', 'gbk', $row ['product_type'] );
				$content [] = '';
				$content [] = iconv ( 'utf-8', 'gbk', $row['bill_time'].'\t');
				$content [] = '';
				$content [] = iconv ( 'utf-8', 'gbk', $row ['channel_rate'] );
				$content [] = '';
				$content [] = iconv ( 'utf-8', 'gbk', $row ['channel_fee'] );
				$content [] = '';
				$content [] = iconv ( 'utf-8', 'gbk', $row ['account'] );
				$content [] = '';
				$content [] = iconv ( 'utf-8', 'gbk', $row ['payment_rate'] );
				$content [] = '';
				$content [] = iconv ( 'utf-8', 'gbk', $row ['payment_fee'] );
				$content [] = '';
				$content [] = iconv ( 'utf-8', 'gbk', $income_id );
				$content [] = '';
				$content [] = iconv ( 'utf-8', 'gbk', $payment_id);
				$content [] = '';
				$content [] = iconv ( 'utf-8', 'gbk', $row ['note'] );
				fputcsv ( $fp, $content );
			}

三、文件的尾部

                      $sql="select sum(Charge_final.fee) as amountorder,
			sum(Charge_final.channel_fee) as sumchannel_fee,
			sum(Charge_final.fee-Charge_final.channel_fee) as sumaccout,
			sum(Charge_final.payment_fee) as sumpayfee
			from {$this->Charge_final} as Charge_final
			left join {$this->bass_productline} as bass_productline on
			Charge_final.channel_id=bass_productline.channel_id and
			Charge_final.channel_type=bass_productline.channel_type
			where 1=1 $conditions";
			$querys = $this->db->query ( $sql );
			$ro = $querys->result_array ();
			$this->data ['ro'] = $ro;
			$amountorder=$ro['0']['amountorder'];
			$sumchannel_fee=$ro['0']['sumchannel_fee'];
			$sumaccout=$ro['0']['sumaccout'];
			$sumpayfee=$ro['0']['sumpayfee'];
			 $foot = array ('统计','','','','','','','','','','','','','',"$amountorder",
				'','','','','','','','','','','','','','','','',
				'','','','','',"$sumchannel_fee",'',"$sumaccout",'','','',"$sumpayfee",'','','','',
				'','');
			  foreach ($foot as $i => $v ) {
			  	// CSV的Excel支持GBK编码,一定要转换,否则乱码
			  	$foot[$i] = iconv ( 'utf-8', 'gbk', $v );
			  }
			  // 将数据通过fputcsv写到文件句柄
			  fputcsv ( $fp, $foot);
		}
	}
}

PHP 生成.csv 文件并下载到浏览器

时间: 2024-12-14 18:04:37

PHP 生成.csv 文件并下载到浏览器的相关文章

django生成CSV文件

生成CSV和Excel文件:有时候我们做的网站,需要将一些数据导出到文件中以方便统计,在导出文件类型中生成CSV文件或者是Excel文件是常用的方式,导出的CSV文件或者Excel文件将以附件的方式下载下来,以下将讲解如何生成CSV文件. 生成小的CSV文件:我们用Python内置的csv模块来处理csv文件,并且使用HttpResponse来将csv文件返回回去,首先来介绍一下把数据写入到CSV文件的一种方法: import csv with open('abc.csv') as fp: wr

使用commons-csv生成.csv文件

做个代码笔记,方便以后看. commons-csv-1.1.jar的源码:https://github.com/apache/commons-csv CsvFileBuilder.java类 package com.huihui.main; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; im

POI以SAX方式解析Excel2007大文件(包含空单元格的处理) Java生成CSV文件实例详解

http://blog.csdn.net/l081307114/article/details/46009015 http://www.cnblogs.com/dreammyle/p/5458280.html . Office2007与Office Open XML 在Office 2007之前,Office一直都是以二进制位的方式存储,但这种格式不易被其它软件拿来使用,在各界的压力下,MicroSoft于2005年发布了基于XML的ooxml开放文档标准.ooxml的xml schema强调减

Java生成CSV文件实例详解

本文实例主要讲述了Java生成CSV文件的方法,具体实现步骤如下: 1.新建CSVUtils.java文件: package com.saicfc.pmpf.internal.manage.utils; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputS

记一次java生成csv文件乱码的解决过程 (GB2312编码)

系统:win7 (格式:中文(简体,中国)) 工具:Eclipse (默认编码utf-8) 服务两个:[restful接口]  和 [服务*** server]. 场景:[服务*** server]多次调用[restful接口],每次[restful接口]会返回一个生成好的csv文件内容.[服务*** server]将每次[restful接口]返回的csv内容保存成一个csv文件.并将生成的多个csv文件打包成一个zip压缩包. [restful接口]:根据一组数据生成csv文件 1. java

php服务器端生成csv文件

/** * 将数组动态输出至 csv 文件[服务器端生成文件] * @param array $data 二维数组 * @param string $filename 文件名 */ function writeCsv($data, $filename = 'file.csv') { $fp = fopen($filename, 'w'); foreach ($data as $fields) { fputcsv($fp, $fields); } fclose($fp); } php服务器端生成c

java将数据生成csv文件

1,httpRequest接口触发进程[或者可以换成其他方式触发] /** * 出入库生成CSV文件 * @param req * @param params * @return */@RequestMapping(value = "explanCsvFileToOrder")ResponseMessage explanCsvFileToOrder(HttpServletRequest req, @RequestParam Map<String, String> param

java生成CSV文件

内容简介 本文内容使用java实现数据生成CSV文件,有关CSV文件知识请参考:CSV (逗号分隔值文件格式) 实现代码(仅供参考,请根据实现情况来修改) /** * 坐标点参数实体类 */ public class PointsParamDto { /** * 坐标id(由1开始,累加1,这样的:1,2,3,4,5...) */ private String pointId; /** * X 坐标点 */ private String x; /** * X 坐标点 */ private Str

Java生成Txt文件及下载

package com.saicfc.pmpf.internal.manage.utils; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import com.saicfc.pmpf.common.enums.ChannelCo