我这里使用php的form表单。
当我点击表单按钮时,自动跳到exportDate.php页面,并执行exportDate.php页面的代码。
显示下载按钮的页面:
<form method="post" action="exportDate.php">
<input type="submit" value="下载表格">
</form>
exportDate.php 文件的代码:
<?php require_once(dirname(__FILE__) . '/inc/config.inc.php');
// 1、打开文件
$fp = fopen("产品信息列表.csv", "w");
// 2、插入表头列名称
$header = array('名称', '型号/料号', '品牌', '对应机', '类别', '制程', '部门', '提供服务', '备注', '上传时间');
fputcsv($fp, $header);
// 3、查询数据,并把数据写入表格内
$row = $dosql->Execute("SELECT * FROM pmw_goods WHERE delstate='' ORDER BY id DESC;");
while ($row = $dosql->GetArray()) {
// 转化一下时间格式
$row['posttime'] = GetDateTime($row['posttime']);
// 产品品牌 ,并判断没有品牌的情况下的值
$row2 = $dosql->GetOne("SELECT * FROM pmw_goodsbrand WHERE id=" . $row['brandid']);
// 产品类别
$row3 = $dosql->GetOne("SELECT `classname` FROM `#@__goodstype` WHERE `id`=" . $row['typeid']);
$item = array(
"name" => $row['title'], // 产品名称
"xinghao" => $row['description'], //型号 料号
"pinpai" => $row2['classname'], // 品牌
"jitai" => $row['keywords'], // 机台
"class" => $row3['classname'], // 类别
"zhicheng" => $row['weight'],// 制程
"dept" => $row['goodsid'],// 部门
"service" => $row['linkurl'],// 提供服务
"remark" => $row['content'],// 备注
"time" => $row['posttime'] // 上传时间
);
// 5、将数据转换成csv格式,并写入csv文件
fputcsv($fp, $item);
}
// 6、写入完成,关闭文件
fclose($fp);
// 7、利用header函数下载文件到本地。注意使用header前,不能有任何的输出操作。否则会报错。且这种方式卸载不会在服务器上生成文件。
header('Content-Type: application/octet-stream');//设置内容类型 声明PHP与浏览器交互的文件类型和编码
header('Content-Disposition: attachment; filename="产品信息列表.csv"'); //设置MIME用户作为附件下载 如果将attachment换成inline意思为在线打开
header('Content-Transfer-Encoding: binary');//设置传输方式
header('Content-Length: ' . filesize('产品信息列表.csv'));//设置内容长度
readfile('产品信息列表.csv');//读取需要下载的文件
?>