保存excel文件 1. [代码] 保存/导出 ?php/** * @author chenweijie * excel Tool */class excel_tool{public static $readerObj; public static $charset = 'utf-8';/** * 输出切换编码 */public static function excelExportIconv($output){
1. [代码]保存/导出
<?php
/**
* @author chenweijie
* excel Tool
*/
class excel_tool
{
public static $readerObj;
public static $charset = 'utf-8';
/**
* 输出切换编码
*/
public static function excelExportIconv($output){
return iconv(self::$charset, 'GBK', $output);
}
/**
* 文件保存
*/
public static function saveFile($filePath, $title = '', $firstRow = array(), $data = array())
{
ob_start();
self::outputData($title, $firstRow, $data);
$content = ob_get_contents();
ob_clean();
if ($fp = @fopen($filePath, 'w+')) {
if (fwrite($fp, $content)) {
fclose($fp);
return true;
}
fclose($fp);
}
return false;
}
/**
* 数据输出
*/
protected static function outputData($title = '', $firstRow = array(), $data = array())
{
if (!empty($title)) {
echo self::excelExportIconv($title) . "\t\n";
}
/**
* 第一行与后面的数据以键名关联
*/
if (!empty($firstRow) && is_array($firstRow)) {
//输出第一行内容
foreach ($firstRow as $first) {
echo self::excelExportIconv($first) . "\t";
}
echo "\n";
if (!empty($data) && is_array($data)) {
foreach ($data as $item) {
foreach ($firstRow as $_key => $_val) {
if (isset($item[$_key])) {
echo self::excelExportIconv($item[$_key]) . "\t";
} else {
echo self::excelExportIconv('') . "\t";
}
}
echo "\n";
}
}
} else {
if (!empty($data) && is_array($data)) {
foreach ($data as $item) {
foreach ($item as $val) {
echo self::excelExportIconv($val) . "\t";
}
echo "\n";
}
echo "\n";
}
}
}
}
?>
2. [代码]粟子
Excel_tool::saveFile(
dirname(__FILE__) . '/example.xls',
'This is title',
array('id'=>'id','name'=> '名字','title'=> '标题'),
array(
array('id' => '1', 'name'=>'名字1','title'=> '标题1'),
array('id' => '2', 'name'=>'名字2','title'=> '标题2'),
array('id' => '3', 'name'=>'名字3','title'=> '标题3'),
array('id' => '4', 'name'=>'名字4', 'title'=> '标题4'),
array('id' => '5', 'name'=>'名字5','title'=> '标题5'),
)
);
