请教一下:用PHP 从MYsql 中查询数据并导出成cvs 或者xls 怎么实现。如果方便的话给个源代码,尤为感激!

如题所述

csv很简单
数据以,分开
行用\n
存为.csv就行了
生成xls的话稍微复杂一点儿,下面是一个生成xls的类,你可以按照你的需要修改调用一下。
======================================
用PHP生成xls,csv格式文件的类
2008年09月23日 星期二 上午 09:56

fileOperation.php
****************************************************
class fileOperation {//基类
var $fileName='test';
var $extendName='csv';
var $mPath='./report/';
var $mFp;
function fileOperation() {

}
function openFile($mode='w'){
if(empty($this->fileName)){
$this->setTimeFileName();
}
if (empty($this->extendName)){
$this->setExtendName();
}

$fp=fopen($this->mPath.'/'.$this->fileName.'.'.$this->extendName,$mode);
if($fp){
$this->mFp=$fp;
}else{
return 0;
}
}
function closeFile(){
return fclose($this->mFp);
}
function setTimeFileName($type='Ymd'){
if(!empty($type)){
$this->fileName=$type;
}else{
$this->fileName=time();
}
}
function setExtendName($extend='txt'){
if(!empty($extend)){
$this->extendName=$extend;
}else{
$this->extendName='.csv';
}
}
function setPath($path='./'){
$this->mPath=$path;
}
}

xlsHelper.php
****************************************************
require_once 'fileOperation.php';
class xlsHelper extends fileOperation{//具体实现子类
var $mSpace = '';
var $mHead;
var $mBody='';

function addHeader($head=array()){
$this->mHead='<table width="500" border="1" align="center" cellpadding="5"><tr>';
if (is_array($head)){
foreach($head as $hd){
$this->mHead.='<th bgcolor="#A5A0DE">'.$hd.'</th>';
}
}
$this->mHead.='</tr>';
}
function addBodyData($body=array()){
if(is_array($body)){

for($i=0;$i<count($body);$i++){
$childBody=$body[$i];
$this->mBody.='<tr>';
$this->mSpace = '<td align="center">';
for($j=0;$j<count($childBody);$j++){
$this->mBody.=$this->mSpace.$childBody[$j].'</td>';
}
$this->mBody.="</tr>";
}

}
$this->mBody.='</table>';
}
function _construct(){

}
function writeCSVDate(){
return fwrite($this->mFp,$this->mHead.mb_convert_encoding($this->mBody,'sjis','sjis'));
}
function setSpace($type=','){
$this->mSpace=$type;
}
}

test.php
****************************************************
$xls=new xlsHelper();
$xls->fileName='xxx';//设置生成文件的文件名
$xls->extendName='xls';//文件扩展名
$xls->mPath='./';//文件保存路径

$headerarr=array('姓名','年龄','邮箱');//头部字段名
$xls->addHeader($headerarr);

$datasarr=array(//注意:此处的二维数组一定要是数字索引
array('yht',20,'[email protected]'),
array('ktv009',23,'[email protected]'),
);
$xls->addBodyData($datasarr);

$xls->openFile('w');
if($xls->writeCSVDate()) echo "<script language='javascript'>生成文件成功</script>";
else echo ""<script language='javascript'>无法生成文件</script>";
温馨提示:答案为网友推荐,仅供参考
相似回答
大家正在搜