<?

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','"',"&lt;?_("), $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读写封装的更多相关文章

  1. leveldb.net对象读写封装

    leveldb是一个非常高效的可嵌入式K-V数据库,在.NET下有着基于win实现的包装leveldb.net;不过leveldb.net只提供了基于byte[]和string的处理,这显然会对使用的 ...

  2. C# Socket流数据大小端读写封装

      网络数据是大端模式,而c#中的数据小端结构,那么在读写网络数据的时候需要进行转换.c#类库IPAddress已经封装了大小端的转换. 封装代码如下: using System.IO; using  ...

  3. phpExcel在封装

    <?php /** * 数组生成Excel * @author zouhao zouhao619@gmail.com * 使用示例 * $excel =new Excel(); $data=ar ...

  4. 简单的cookie读写封装

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  5. php中使用PHPExcel读写excel(xls)文件的方法

    首先从GitHub上下载 excel的相关类库 下载地址:https://github.com/PHPOffice/PHPExcel 以下是从excel中获取数据 <?php /** * * @ ...

  6. [置顶] 无名管道的C++封装

    xpipe-无名管道的C++封装类 无名管道的C++封装类,用于父子进程进行通信 基础介绍 unix下一切皆文件,管道也不例外.无名管道pipe定义在<unistd.h>中. #inclu ...

  7. 基于sqlitecpp的sqlite3 c++封装

    Github: 人富水也甜 感谢GitHub大佬: sqlitecpp github:  https://github.com/SRombauts/SQLiteCpp sqlite: https:// ...

  8. 提高PHP代码质量的36个技巧

    1.不要使用相对路径 常常会看到: require_once('../../lib/some_class.php'); 该方法有很多缺点: 它首先查找指定的php包含路径, 然后查找当前目录. 因此会 ...

  9. php注意事项2

    1.不要使用相对路径 常常会看到: require_once('../../lib/some_class.php'); 该方法有很多缺点: 它首先查找指定的php包含路径, 然后查找当前目录. 因此会 ...

随机推荐

  1. hud项目lcd调试过程的一些见解

    1.帧缓冲(FrameBuffer)设备驱动帧缓冲设备为标准的字符型设备,在Linux中主设备号29,定义在/include/uapi/linux/major.h中的FB_MAJOR,次设备号定义帧缓 ...

  2. openwrt固件编译过程

    主Makefile分析 注:1)make -n可打印makefile执行的命令,而不执行. 2)可以在规则的命令中增加echo跟踪执行进度. 顶层目录的Makefile是openert的总Makefi ...

  3. Mybatis学习手记(二)

    要点一.如果字段名与类的属性名不一致,要在*Mapper.xml文件中,新建resultMap 配置对应关系,如下图:

  4. poj 3469(网络流模版)

    题目链接:http://poj.org/problem?id=3469 思路:终于把网络流的模版测试好了,在Dinic和Sap之间还是选择了Sap,事实证明Sap确实比Dinic效率高,在此贴出自己的 ...

  5. PHP中常用的输出语句比较?

    面试中经常问到这个,可以看下. 面试问题:比较echo print() print_r()  var_dump()? echo(): 可以一次输出多个值,多个值之间用逗号分隔.echo是语言结构(la ...

  6. jodis遇到的问题

    1. Caused by: java.lang.ClassNotFoundException: com.fasterxml.jackson.databind.ObjectMapper java找jar ...

  7. 循环遍历完成后再进行else判断

    有时需要在循环遍历完后再进行else操作,通常的办法是在循环前设置一个flag,用于判断.具体例子如下:

  8. JSP -> f:loadBundle用法

    jsp中出现<f:loadBundle basename="messages_zh_CN" var="msgs" /> 还有src目录下有messa ...

  9. 《从零开始学Swift》学习笔记(Day 47)——final关键字

    原创文章,欢迎转载.转载请注明:关东升的博客 在类的定义中使用final关键字声明类.属性.方法和下标.final声明的类不能被继承,final声明的属性.方法和下标不能被重写. 下面看一个示例: f ...

  10. angularjs 发送ajax请求的问题

    在angularjs中使用 ajax 如果使用 jquery的 ajax发送请求会遇到结果返回了,但是页面的值却没有改变,如: $scope.queryNameMatch = function() { ...