导出Excel文件中的记录 [英] Export records in excel file

查看:81
本文介绍了导出Excel文件中的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个Web应用程序,我想添加一个功能,例如用户可以导出选定的记录...

I created a web application and I want to add a feature like user can export selected records...

Check Box   Name    Email

            Sumit   sumit@gmail.com
            Karan   karan@gmail.com

我想将此记录导出到excel文件中,但仅应导出选定的记录.

I want to export this records into an excel file, but only the selected records should be exported.

预先感谢

推荐答案

无需下载外部库-您所需的一切已内置在PHP中.

There's no need to download external libraries - everything you need for this is already built into PHP.

步骤:

  1. 在php中查询以获取要输出的行
    您可以使用SELECT * FROM table WHERE id IN (1,2,...)
  2. 使用mysql_fetch_array()mysql_fetch_assoc()一次获取一行
  3. 使用fputcsv()将它们输出到以csv结尾的文件-这样可以正确地转义数据
  1. Do query in php to get the rows you want to output
    You can use SELECT * FROM table WHERE id IN (1,2,...)
  2. Use mysql_fetch_array() or mysql_fetch_assoc() to get the rows one at a time
  3. Use fputcsv() to output them to a file ending in csv - this will properly escape your data

http://www.php.net/manual/zh/function.mysql-fetch-array.php
http://php.net/manual/en/function.fputcsv.php

Excel将能够读取该文件.

Excel will be able to read the file.

覆盖fputcsv的默认值以使用制表符作为分隔符,Excel将更轻松地读取文件.如果使用逗号(默认设置),则可能需要选择逗号作为Excel导入的定界符.

Override the defaults for fputcsv to use tabs for delimiters and Excel will have an even easier time reading the file. If you use commas (the default) you may need to pick commas as the delimiter on Excel import.

这是一个工作示例,假设您已经设置了行:

Here's a working example assuming you already have rows set up:

$rows; // predefined
$filename = 'webdata_' . date('Ymd') . '.csv';

header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/octet-stream"); 
// that indicates it is binary so the OS won't mess with the filename
// should work for all attachments, not just excel

$out = fopen("php://output", 'w');  // write directly to php output, not to a file
foreach($rows as $row)
{
  fputcsv($out, $row);
}
fclose($out);

这篇关于导出Excel文件中的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆