PHPExcel读写封装
<?
require_once ('inc/PHPExcel/PHPExcel/IOFactory.php');
/**
* @author lgl
* 使用实例
* $fieldMap=['昵称'=>'username','头像'=>'photo','签名'=>'sign',"性别"=>'sex'];//header和字段映射
* $fieldAttr=['性别'=>'time'];//对应列的字段值转化类型
* $readFile= new ReadExcelBiz(dirname(__FILE__).'/3-26上传.xls',$fieldMap,$fieldAttr,3);
* $rowsNum=$readFile->getRowsNum();
* for($i=1;$i<=$rowsNum;$i++){
* print_r($readFile->getNextRow());
* }
*/
namespace PublicService\Biz;
class ReadExcelBiz
{
private $_objExcel = null;
private $_objReader = null;
private $_objCurSheet = null;
private $_charset = 'utf-8';
private $_head = array();
private $_fieldMap = array();
private $_fieldAttr = array();
private $_cols = 0;
private $_rows = 0;
private $_rowCursor = 0; /**
* ReadExcelBiz constructor.
* @param $filepath excel文件路径
* @param array $fieldMap 字段映射
* @param array $fieldAttr 字段类型转化
* @param int $sheetindex sheet下标
* 例子
* $fieldMap=['昵称'=>'username','头像'=>'photo','签名'=>'sign',"性别"=>'sex'];
* $fieldAttr=['性别'=>'date']; 设置某列值转化的类型 目前只支持 'date' ,'datetime','time'
*/
public function __construct($filepath, $fieldMap = array(), $fieldAttr = array(), $sheetindex = 0)
{
try{ $this->_objReader = \PHPExcel_IOFactory::createReaderForFile($filepath);
$this->_objReader->setReadDataOnly(true);
$this->_objExcel = $this->_objReader->load($filepath);
$this->_objCurSheet = $this->_objExcel->getSheet($sheetindex);
$this->_rows = $this->_objCurSheet->getHighestRow();
$this->_cols = $this->char2num($this->_objCurSheet->getHighestColumn());
$this->_fieldAttr = $fieldAttr;
if(count($fieldMap) > 0 || count($fieldAttr) > 0)
{
$this->getHead();
for($i=0; $i< count($this->_head); $i++)
{
if($fieldMap[$this->_head[$i]])
$this->_fieldMap[$i] = $fieldMap[$this->_head[$i]]; if($fieldAttr[$this->_head[$i]])
$this->_fieldAttr[$i] = $fieldAttr[$this->_head[$i]];
}
}
}
catch(\Exception $e){
echo $e->getMessage();
exit;
}
} /**
* @desc 获取excel头
* @return array|bool
*/
public function getHead()
{
$this->_rowCursor = 1;
$this->_head = $this->getRow($this->_rowCursor, false);
return $this->_head;
} /**
* @desc 获取第一行数据
* @return array|bool
*/
public function getFirstRow()
{
return $this->getRow(1);
} /**
* @desc 获取下一行数据
* @return array|bool
*/
public function getNextRow()
{
$this->_rowCursor++;
return $this->getRow($this->_rowCursor);
} /**
* @desc 获取前一行数据
* @return array|bool
*/
public function getPrevRow()
{
$this->_rowCursor--;
return $this->getRow($this->_rowCursor);
} /**
* @desc 获取行数据
* @param $index 第几行
* @param bool $useFieldMap 是否使用字段映射
* @return array|bool
*/
public function getRow($index, $useFieldMap = true)
{
if($index > $this->_rows)
return FALSE; $row = array();
for($col = 0; $col < $this->_cols; $col++)
{
$objCell = $this->_objCurSheet->getCellByColumnAndRow($col, $index);
if($objCell->getDataType() == \PHPExcel_Cell_DataType::TYPE_FORMULA)
$value = $objCell->getCalculatedValue();
else
$value = $objCell->getFormattedValue(); $value = trim($this->decode($this->transforValue(trim($value), $col)));
if($useFieldMap && $this->_fieldMap[$col])
$row[$this->_fieldMap[$col]] = $value;
else if(!$useFieldMap || count($this->_fieldMap) == 0)
$row[$col] = $value;
} return $row;
} /**
* @desc 获取总列数
* @return int
*/
public function getColsNum()
{
return $this->_cols;
} /**
* @desc 获取总行数
* @return int
*/
public function getRowsNum()
{
return $this->_rows;
} private function char2num($pColumn)
{
$strlen = strlen($pColumn);
$columnNum = 0;
for($i = 0;$i < $strlen; $i++)
{
$str = substr($pColumn, $i, 1);
$columnNum = $columnNum * 26 + (ord($str) - ord('A') + 1);
} return $columnNum;
} /**
* @desc 转码
* @param $str
* @return mixed|string
*/
private function decode($str)
{
if(function_exists('mb_convert_encoding'))
return mb_convert_encoding($str, $this->_charset, "utf-8");
else
return iconv("utf-8", $this->_charset, $str);
} /**
* @desc 单元格值转化
* @param $value
* @param $col
* @return false|string
*/
private function transforValue($value, $col)
{
$formatCode = array('date' => 'Y-m-d', 'datetime' => 'Y-m-d H:i:s', 'time' => 'H:i:s');
$dataType = $this->_fieldAttr[$col];
if($formatCode[$dataType])
{
if(is_numeric($value))
$value = gmdate($formatCode[$dataType], \PHPExcel_Shared_Date::ExcelToPHP($value));
else if($value != "")
$value = date($formatCode[$dataType], strtotime($value));
} return $value;
} }
<?
require_once ('inc/PHPExcel/PHPExcel/IOFactory.php');
class ExcelWriter
{
private $_objExcel = null;
private $_objActSheet = null;
private $_charset = '';
private $_head = array();
private $_rows = 0;
private $_excelClass = 'Excel5';
private $_excelPostfix = '.xls';
public function __construct($config = array())
{
$this->_objExcel = new PHPExcel();
$this->_objActSheet = $this->setActiveSheetIndex(0);
$this->_charset = isset($config['charset']) ? $config['charset'] : MYOA_CHARSET;
}
public function setActiveSheetIndex($index)
{
return $this->_objExcel->setActiveSheetIndex($index);
}
public function setFileName($filename)
{
$this->_filename = $this->encode($filename);
$this->_objActSheet->setTitle($this->encode($filename));
}
public function setTitle($title)
{
$this->_objActSheet->setTitle($this->encode($title));
}
public function addHead($row)
{
$this->_rows++;
$row = $this->row2array($row);
$this->_head = $row;
for($col = 0; $col < count($row); $col++)
{
$data = $this->encode($row[$col]);
$width = ceil(strlen($data)*1.2);
$style = $this->_objActSheet->getStyleByColumnAndRow($col, '1');
$align = $style->getAlignment();
$align->setHorizontal(PHPExcel_Style_Alignment::VERTICAL_CENTER);
$align->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
$this->_objActSheet->getColumnDimensionByColumn($col)->setWidth($width);
$this->_objActSheet->setCellValueExplicitByColumnAndRow($col, $this->_rows, $data, PHPExcel_Cell_DataType::TYPE_STRING);
}
}
public function addRow($row)
{
$this->_rows++;
$row = $this->row2array($row);
for($col = 0; $col < count($row); $col++)
{
$data = $row[$col];
if(substr($data, 0, 1) == '"' && substr($data, -1) == '"')
$data = substr($data, 1, -1);
$data = $this->encode($data);
$this->_objActSheet->setCellValueExplicitByColumnAndRow($col, $this->_rows, $data, PHPExcel_Cell_DataType::TYPE_STRING);
}
}
public function Save()
{
ob_end_clean();
Header("Cache-control: private");
Header("Content-type: application/vnd.ms-excel");
Header("Accept-Ranges: bytes");
Header("Accept-Length: ".ob_get_length());
Header("Content-Disposition: attachment; ".$this->get_filename($this->_filename.$this->_excelPostfix));
$objWriter = PHPExcel_IOFactory::createWriter($this->_objExcel, $this->_excelClass);
$objWriter->save("php://output");
}
private function encode($str)
{
if(function_exists('mb_convert_encoding'))
return mb_convert_encoding($str, "utf-8", $this->_charset);
else
return iconv($this->_charset, "utf-8", $str);
}
private function row2array($row)
{
if(is_array($row))
return $row;
$delimiter = ',';
$enclosure = '"';
$expr_field = '/'.$delimiter.'(?=(?:[^'.$enclosure.']*'.$enclosure.'[^'.$enclosure.']*'.$enclosure.')*(?![^'.$enclosure.']*'.$enclosure.'))/';
$row = preg_split($expr_field, trim($row));
$row = preg_replace(array('/"(.*)"$/s','/""/s',"/\<\?/s"), array('$1','"',"<?_("), $row);
return $row;
}
private function get_filename($filename)
{
$filename_encoded = str_replace("+", "%20", urlencode($filename));
if (preg_match("/msie|trident/i", $_SERVER['HTTP_USER_AGENT']))
return 'filename="' . $filename_encoded . '"';
else if (preg_match("/Firefox/", $_SERVER['HTTP_USER_AGENT']))
return 'filename*="utf8\'\'' . $filename . '"';
else
return 'filename="' . $filename . '"';
}
}
?>
PHPExcel读写封装的更多相关文章
- leveldb.net对象读写封装
leveldb是一个非常高效的可嵌入式K-V数据库,在.NET下有着基于win实现的包装leveldb.net;不过leveldb.net只提供了基于byte[]和string的处理,这显然会对使用的 ...
- C# Socket流数据大小端读写封装
网络数据是大端模式,而c#中的数据小端结构,那么在读写网络数据的时候需要进行转换.c#类库IPAddress已经封装了大小端的转换. 封装代码如下: using System.IO; using ...
- phpExcel在封装
<?php /** * 数组生成Excel * @author zouhao zouhao619@gmail.com * 使用示例 * $excel =new Excel(); $data=ar ...
- 简单的cookie读写封装
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- php中使用PHPExcel读写excel(xls)文件的方法
首先从GitHub上下载 excel的相关类库 下载地址:https://github.com/PHPOffice/PHPExcel 以下是从excel中获取数据 <?php /** * * @ ...
- [置顶] 无名管道的C++封装
xpipe-无名管道的C++封装类 无名管道的C++封装类,用于父子进程进行通信 基础介绍 unix下一切皆文件,管道也不例外.无名管道pipe定义在<unistd.h>中. #inclu ...
- 基于sqlitecpp的sqlite3 c++封装
Github: 人富水也甜 感谢GitHub大佬: sqlitecpp github: https://github.com/SRombauts/SQLiteCpp sqlite: https:// ...
- 提高PHP代码质量的36个技巧
1.不要使用相对路径 常常会看到: require_once('../../lib/some_class.php'); 该方法有很多缺点: 它首先查找指定的php包含路径, 然后查找当前目录. 因此会 ...
- php注意事项2
1.不要使用相对路径 常常会看到: require_once('../../lib/some_class.php'); 该方法有很多缺点: 它首先查找指定的php包含路径, 然后查找当前目录. 因此会 ...
随机推荐
- E - Leading and Trailing 求n^k得前三位数字以及后三位数字,保证一定至少存在六位。
/** 题目:E - Leading and Trailing 链接:https://vjudge.net/contest/154246#problem/E 题意:求n^k得前三位数字以及后三位数字, ...
- VMware-vSphere-5.1--------群集、HA、DRS、FT
VMware vSphere 5.1 高可用性 在本节中主要讲的是集群的一些功能和配置,相比5.0的设置,没有太大的变化.VMware vSphere为虚拟机提供虚拟化的基础架构,将现有的 ...
- [已解决]pycharm报错:AttributeError: module 'pip' has no attribute 'main'
> 更新pip后,pycharm更新模块报错,经过一番查找,现提供两种解决办法. 报错片段信息如下: AttributeError: module 'pip' has no attribute ...
- [浪风前端开发]JS获取当前时间戳的方法
由于最近在研究轻交互式web设计,所以整理了下面的东东,仅供分享测试学习交流之用. JavaScript 获取当前时间戳:第一种方法: var timestamp = Date.parse(new D ...
- Unity3D学习笔记——NGUI之UISlider
UISlider:用于创建简单的滑动块和进度条,并且可以添加一个拇指按钮. 效果图如下: 一:使用步骤 1.从上面的效果看出,这个工具由四部分组成:背景图,进度图,进度lable显示,拇指按钮. 2. ...
- Caffe模型读取
caffe模型最终保存使用过的protobuf形式,将一个已经训练好的caffe模型读取出来,可以参考如下: 1,包含的头文件: #include <google/protobuf/io/cod ...
- iOS - url中文和特殊字符转码###
- (NSString *)generateUrl:(NSString *)url{ /** 第一个参数:NULL 第二个参数:C语言的字符串 第三个参数:NULL 第四个参数:要转义的字符串,不要乱 ...
- day15数据类型
一.浮点数 之前讲过的,有序 : 列表 元组 字符串 数字类 :int flost complex bool 散列累 :集合和字典 浮点数:--包含所有小数 和复数 复数:a +bj 实部和虚部 ...
- IOS 多线程的一些总结
IOS 多线程 有三种主要方法 (1)NSThread (2)NSOperation (3)** 下面简单介绍这三个方法 1.NSThread 调用方法如下: 如函数需要输入参数, ...
- std::vector<std::vector<> >
上次看到这个有点晕了,其实这个vector保存的是std::vector<> #include <vector> #include <iostream> using ...