Skip to content

Instantly share code, notes, and snippets.

@hubsgz
Created March 13, 2014 01:23
Show Gist options
  • Save hubsgz/9520206 to your computer and use it in GitHub Desktop.
Save hubsgz/9520206 to your computer and use it in GitHub Desktop.
php 导出数据至excel
<?php
//php 导出数据至excel
class ExportExcel
{
/**
* 导出信息
*
* @return null
*/
public function export_data()
{
$page = 1;
$pageSize = 1;
$this->exportToExcelHeader();
echo "姓名\t密码" . PHP_EOL;
while (true) {
$limit = ($page-1) * $pageSize;
$sql = "select username, passwd ".
"from table order by id asc limit $limit, $pageSize";
$list = $this->query($sql);
if (empty($list)) {
break;
} else {
$page++;
}
echo $this->exportToExcelData($list);
}
}
/**
* 生成导出数据至excel的数据
* 注:使用此函数前后都不应有任何数据输出
*
* @param $data Array 下载的数据
*
* @return null
*/
private function exportToExcelData($data)
{
$csv_data = '';
foreach ($data as $line) {
foreach ($line as $key => &$item) {
$item = str_replace(',', '', str_replace(PHP_EOL,'',$item)); //过滤生成文件中的(,)逗号和换行
//$item = mb_convert_encoding($item, 'gbk', 'utf-8');
}
$csv_data .= implode("\t", $line) . PHP_EOL;
}
return $csv_data;
}
/**
* 导出excel的header
*
* @param string $file_name 文件名
*
* @return null
*/
private function exportToExcelHeader($file_name = 'export')
{
//$str = mb_convert_encoding($file_name, 'gbk', 'utf-8');
header("Content-type:application/vnd.ms-excel");
header("Content-Disposition:attachment; filename=".$file_name.".xls");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment