php导入导出excle(csv)格式
最近在开发一个项目,需要用导出excel文件这个功能,于是结合网上搜索到的资料及自己的体会,用以下方法实现了。
1、phpexcel类方法
<?php
// load library
require 'php-excel.class.php';
// create a simple 2-dimensional array
$data = array(
1 => array ('Name', 'Surname'),
array('Schwarz', 'Oliver'),
array('Test', 'Peter')
);
// generate file (constructor parameters are optional)
$xls = new Excel_XML('UTF-8', false, 'My Test Sheet');
$xls->addArray($data);
$xls->generateXML('my-test');
?>
下载链接:http://php-excel.googlecode.com/files/php-excel-v1.1-20090910.zip
说明:这个是导出excel文件用的。
2、一个phper自用的函数
导出到CSV:
<?php
export_csv();
/**
*导出到CSV文件
*/
function export_csv()
{
$filename = date('YmdHis').".csv";
header("Content-type:text/csv");
header("Content-Disposition:attachment;filename=".$filename);
header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
header('Expires:0');
header('Pragma:public');
echo array_to_string(get_export_data());
}
/**
*导出数据转换
* @param $result
*/
function array_to_string($result)
{
if(empty($result)){
return i("没有符合您要求的数据!^_^");
}
$data;
$size_result = sizeof($result);
for($i = 0 ; $i < $size_result ; $i++) {
$data .= i($result[$i]['name']).','.i($result[$i]['option'])."\n";
}
return $data;
}
/**
*获取导出报表的数据
* @return
*/
function get_export_data()
{
$link = mysql_connect('localhost','root','root') or die(mysql_error());
mysql_select_db('joomla');
$sql = 'select a.name,a.option from jos_components a limit 10';
$result = mysql_query($sql);
$res = array();
$i = 0;
while($row = mysql_fetch_array($result)){
$res[$i][name] = $row[name];
$res[$i][option] = $row[option];
$i++;
}
return $res;
}
/**
*编码转换
* @param <type> $strInput
* @return <type>
*/
function i($strInput)
{
return iconv('utf-8','gb2312',$strInput);//页面编码为utf-8时使用,否则导出的中文为乱码
}
?>
导入csv:
<?php
header("Content-type:text/html;charset=utf-8");
//定义文件路径、文件名
$file = 'test.csv';
//打开csv文件
$handle = fopen($file,'r');
//循环读取CSV文件内容,并返回
//利用php函数fgetcsv,第一个参数为文件句柄,第二个为读取行数,第三个函数为字段分界符,第四个参数为字段环绕符
function inputCsv($handle){
$out = array();
$n = 0;
while($data = fgetcsv($handle,10000)){
$num = count($data);
for($i=0;$i<$num;$i++){
$out[$n][$i] = $data[$i];
}
$n++;
}
return $out;
}
$result = inputCsv($handle);
for($i=0;$i<count($result);$i++){
for($j=0;$j<count($result[$i]);$j++){
echo iconv('gb2312','utf-8',$result[$i][$j]).' '; //页面编码为utf-8时使用,否则中文会出现乱码
}
echo '<br />';
}
?>