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包含路径, 然后查找当前目录. 因此会 ...
随机推荐
- 【藏】使用Entity Framework时要注意的一些性能问题
这篇文章写的很好: http://diaosbook.com/Post/2012/12/9/performance-issue-in-select-one-or-few-colums-via-enti ...
- [已解决]pycharm报错:AttributeError: module 'pip' has no attribute 'main'
> 更新pip后,pycharm更新模块报错,经过一番查找,现提供两种解决办法. 报错片段信息如下: AttributeError: module 'pip' has no attribute ...
- PHP : ActiveRecord实现示例
先简单介绍一下Active Record: Active Record(中文名:活动记录)是一种领域模型模式,特点是一个模型类对应关系型数据库中的一个表,而模型类的一个实例对应表中的一行记录.Acti ...
- Spring MVC生成RSS源
下面的示例演示如何使用Spring Web MVC框架生成RSS源. 首先使用Eclipse IDE,并按照以下步骤使用Spring Web Framework开发基于动态表单的Web应用程序: 创建 ...
- char * const p和const char *p的区别
1. 前者定义P为常量,即只能单向赋值一次,P++展开为p=p+1,重复赋值给常量,出错,后者P为地址变量,地址变量是指向该变量的存储地址值如:4B3F6A,不能赋给一个字符值(字符相当于ascii表 ...
- 关于Linq to Sql 中的left join 中defaultifempty的相关注意事项
在使用Linq to Sql的时候,进行两个表的左连接的时候要注意defaultifempty的使用,这个函数本来的意思即是:如果为空则使用默认值代替,默认值为 NULL ,当然也可以使用defaul ...
- windows共享文件夹给centOS
服务器使用的是CentOS系统,而本机使用的win7系统.考虑到是临时使用,所以就不打算搭建FTP和Samba服务器,直接通过CentOS挂载windows共享文件夹的方式来达到此目的. 既然是使用w ...
- NGINX快速部署
NGINX快速部署 #!/bin/bash ############################################################################## ...
- 关于java类加载器的一些概念
顾名思义,类加载器(class loader)用来加载 Java 类到 Java 虚拟机中.一般来说,Java 虚拟机使用 Java 类的方式如下:Java 源程序(.java 文件)在经过 Java ...
- "无法加载 DLL“oramts.dll”: 找不到指定的模块。 (异常来自 HRESULT:0x8007007E)。" —— 的解决方法
Oramts.dll 文件公开登记 Oracle 连接所涉及到在通过 Microsoft 分布式事务处理协调器 (MSDTC) 启动的事务中的公共 API. 在事务处理环境中运行时, Syste ...