PHPExcel 简单封装类 [ [ Excel.class ] ]_class.excel_ppxin的博客-程序员资料

技术标签: PHPExcel  PHP笔记  封装类  

实现功能:

(1)读出read();

(2)写入数据write(),可以连续写入。

(3)导出或保存export();

<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Excel {

	public  $is_down = FALSE;
	public  $file_name = '';
	public  $save_path = './';
	private $excel;
	private $_row = 1;
	private $cell_name = array(
		'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
		'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV',
		'AW', 'AX', 'AY', 'AZ'
	);

	public function __construct() {
		require_once APPPATH . 'third_party/PHPExcel.php';
		$this->excel = new PHPExcel();
	}

	function reset()
	{
		$this->_row = 1;
		return $this;
	}

	function write($title = array(), $data = array(), $options = array())
	{
		if (isset($options['sheet_name']) && $options['sheet_name'])
		{
			$this->excel->getActiveSheet(0)->setTitle($options['sheet_name']);
		}
		if (isset($options['export_time']) && $options['export_time'])
		{
			$_cnt = count($title);
			$this->excel->getActiveSheet(0)->mergeCells('A' . $this->_row . ':' . $this->cell_name[$_cnt - 1] . $this->_row);
			$this->excel->setActiveSheetIndex(0)->setCellValue('A' . $this->_row, 'Data Export Time:' . date('Y-m-d H:i:s'));
			$this->_row++;
		}
		if ($title) {
			$i = 0;
			foreach ($title AS $v) {
				$this->excel->setActiveSheetIndex(0)->setCellValue($this->cell_name[$i] . $this->_row, $v);
				$i++;
			}
			$this->_row++;
		}
		if ($data) {
			foreach ($data AS $_v) {
				$j = 0;
				foreach ($_v AS $_cell) {
					$this->excel->getActiveSheet(0)->setCellValue($this->cell_name[$j] . $this->_row, $_cell);
					$j++;
				}
				$i++;
				$this->_row++;
			}
		}
		return $this;
	}
	function export()
	{
		if (empty($this->file_name)) {
			$this->file_name = uniqid(time(), true);
		}
		$objWrite = PHPExcel_IOFactory::createWriter($this->excel, 'Excel2007');
		if ($this->is_down) {
			header('pragma:public');
			header("Content-Disposition:attachment;filename={$this->file_name}.xls");
			$objWrite->save('php://output');
			exit;
		}
		$_savePath = $this->save_path . $this->file_name . '.xlsx';
		$objWrite->save($_savePath);
	}

	function read($file = '', $sheet = 0){
		if(empty($file) OR !file_exists($file)) {
			die('file not exists!');
		}
		$objRead = new PHPExcel_Reader_Excel2007();
		if(!$objRead->canRead($file)){
			$objRead = new PHPExcel_Reader_Excel5();
			if(!$objRead->canRead($file)){
				die('No Excel!');
			}
		}
		$obj = $objRead->load($file);
		$currSheet = $obj->getSheet($sheet);
		$columnH = $currSheet->getHighestColumn();
		$columnCnt = array_search($columnH, $this->cell_name);
		$rowCnt = $currSheet->getHighestRow();
		$data = array();
		for($_row = 1; $_row <= $rowCnt; $_row++){
			for($_column = 0; $_column <= $columnCnt; $_column++){
				$cellId = $this->cell_name[$_column].$_row;
				$cellValue = $currSheet->getCell($cellId)->getValue();
				if($cellValue instanceof PHPExcel_RichText){
					$cellValue = $cellValue->__toString();
				}
				$data[$_row][$this->cell_name[$_column]] = $cellValue;
			}
		}
		return $data;
	}
} // end of class.

参考如下:http://www.php.cn/php-weizijiaocheng-391228.html

<?php

if (!defined('BASEPATH'))
	exit('No direct script access allowed');

class Excel {

	private $excel;

	public function __construct() {
		require_once APPPATH . 'third_party/PHPExcel.php';
		$this->excel = new PHPExcel();
	}

	/**
	 * 数据导出
	 * @param array $title   标题行名称
	 * @param array $data   导出数据
	 * @param string $fileName 文件名
	 * @param string $savePath 保存路径
	 * @param $type   是否下载  false--保存   true--下载
	 * @return string   返回文件全路径
	 * @throws PHPExcel_Exception
	 * @throws PHPExcel_Reader_Exception
   *
	 * php```
	 * $this->exportExcel(array('姓名','年龄'), array(array('a',21),array('b',23)), $filename, $path);
	 * ```
	 */
	function exportExcel($title = array(), $data = array(), $fileName = '', $savePath = './', $isDown = FALSE)
	{
		//横向单元格标识
		$cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
		$this->excel->getActiveSheet(0)->setTitle('sheet名称');   //设置sheet名称
		$_row = 1;   //设置纵向单元格标识
		if ($title) {
			$_cnt = count($title);
			$this->excel->getActiveSheet(0)->mergeCells('A' . $_row . ':' . $cellName[$_cnt - 1] . $_row);   //合并单元格
			$this->excel->setActiveSheetIndex(0)->setCellValue('A' . $_row, '数据导出:' . date('Y-m-d H:i:s'));  //设置合并后的单元格内容
			$_row++;
			$i = 0;
			foreach ($title AS $v) {   //设置列标题
				$this->excel->setActiveSheetIndex(0)->setCellValue($cellName[$i] . $_row, $v);
				$i++;
			}
			$_row++;
		}
		//填写数据
		if ($data) {
			$i = 0;
			foreach ($data AS $_v) {
				$j = 0;
				foreach ($_v AS $_cell) {
					$this->excel->getActiveSheet(0)->setCellValue($cellName[$j] . ($i + $_row), $_cell);
					$j++;
				}
				$i++;
            $_row++;
			}
		}
		//文件名处理
		if (!$fileName) {
			$fileName = uniqid(time(), true);
		}
		$objWrite = PHPExcel_IOFactory::createWriter($this->excel, 'Excel2007');
		if ($isDown) {   //网页下载
			header('pragma:public');
			header("Content-Disposition:attachment;filename=$fileName.xls");
			$objWrite->save('php://output');
			exit;
		}
		$_fileName = iconv("utf-8", "gb2312", $fileName);   //转码
		$_savePath = $savePath . $_fileName . '.xlsx';
		$objWrite->save($_savePath);
		return $savePath . $fileName . '.xlsx';
	}

	/**
	 *  数据导入
	 * @param string $file excel文件
	 * @param string $sheet
	 * @return string   返回解析数据
	 * @throws PHPExcel_Exception
	 * @throws PHPExcel_Reader_Exception
	 */
	function importExecl($file = '', $sheet = 0){
		$file = iconv("utf-8", "gb2312", $file);   //转码
		if(empty($file) OR !file_exists($file)) {
			die('file not exists!');
		}
		$objRead = new PHPExcel_Reader_Excel2007();   //建立reader对象
		if(!$objRead->canRead($file)){
			$objRead = new PHPExcel_Reader_Excel5();
			if(!$objRead->canRead($file)){
				die('No Excel!');
			}
		}
		$cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');

		$obj = $objRead->load($file);  //建立excel对象
		$currSheet = $obj->getSheet($sheet);   //获取指定的sheet表
		$columnH = $currSheet->getHighestColumn();   //取得最大的列号
		$columnCnt = array_search($columnH, $cellName);
		$rowCnt = $currSheet->getHighestRow();   //获取总行数
		$data = array();
		for($_row=1; $_row<=$rowCnt; $_row++){  //读取内容
			for($_column=0; $_column<=$columnCnt; $_column++){
				$cellId = $cellName[$_column].$_row;
				$cellValue = $currSheet->getCell($cellId)->getValue();
				//$cellValue = $currSheet->getCell($cellId)->getCalculatedValue();  #获取公式计算的值
				if($cellValue instanceof PHPExcel_RichText){   //富文本转换字符串
					$cellValue = $cellValue->__toString();
				}
				$data[$_row][$cellName[$_column]] = $cellValue;
			}
		}
		return $data;
	}
} // end of class.

另一个类如下:

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Excel {

  private $excel;

  public function __construct() {
    require_once APPPATH . 'third_party/PHPExcel.php';
    $this->excel = new PHPExcel();
  }

  public function load($path) {
    $objReader = PHPExcel_IOFactory::createReader('Excel5');
    $this->excel = $objReader->load($path);
	  return $this->excel;
  }

  public function save($path) {
    $objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');
    $objWriter->save($path);
  }

  public function stream($filename, $data = null, $datetime_columns = array(), $amount_columns = array()) {
    $this->write($data, $datetime_columns, $amount_columns);
    header('Content-type: application/ms-excel');
    header("Content-Disposition: attachment; filename=\"" . $filename . "\"");
    header("Cache-control: private");
    $objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');
    $objWriter->save('php://output');
  }

  public function write($data = null, $datetime_columns = array(), $amount_columns = array()) {
    if ($data == null) {
      return;
    }
    $col = 'A';
    foreach ($data[0] as $key => $val) {
      $objRichText = new PHPExcel_RichText();
      $objPayable = $objRichText->createTextRun(str_replace("_", " ", $key));
      $this->excel->getActiveSheet()->getCell($col . '1')->setValue($objRichText);
      $col++;
    }
    $rowNumber = 2;
    foreach ($data as $row) {
      $col = 'A';
      foreach ($row as $cell) {
        // format the first column in DateTime format
        if (!empty($datetime_columns) && in_array($col, $datetime_columns)) {
          $dateValue = PHPExcel_Shared_Date::PHPToExcel($cell + date('Z', $cell));
          $this->excel->getActiveSheet()
              ->setCellValue($col . $rowNumber, $dateValue)
              ->getStyle($col . $rowNumber)
              ->getNumberFormat()
              ->setFormatCode(PHPExcel_Style_NumberFormat::toFormattedString('MM/DD/YYYY HH:MM:SS'));
        } else if (!empty($amount_columns) && in_array($col, $amount_columns)) {
          // format amount columns in two decimal float type
          $this->excel->getActiveSheet()
              ->setCellValue($col . $rowNumber, $cell)
              ->getStyle($col . $rowNumber)
              ->getNumberFormat()
              ->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER_00);
        } else {
          $this->excel->getActiveSheet()->setCellValueExplicit($col . $rowNumber, $cell, PHPExcel_Cell_DataType::TYPE_STRING);
        }
        $col++;
      }
      $rowNumber++;
    }
  }

  public function __call($name, $arguments) {
    if (method_exists($this->excel, $name)) {
      return call_user_func_array(array($this->excel, $name), $arguments);
    }
    return null;
  }
}

 

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/ppxin/article/details/92822400

智能推荐

Internet Explorer 编程简述(一)WebBrowser还是WebBrowser_V1收藏_skyremember的博客-程序员资料

 Internet Explorer 编程简述(一)WebBrowser还是WebBrowser_V1收藏新一篇: Internet Explorer 编程简述(二)在IE中编辑OLE嵌入文档 | 旧一篇: Internet Explorer 编程简述(序)function StorePage(){d=document;t=d.selection?(d.selection.type

ServiceComb 开发实战(2)—— Service-Center 服务注册发现对接_servicecenter schema_牧码耕云的博客-程序员资料

文章目录一. 服务注册与发现二. 创建项目三. 请求结构体生成四. 对接接口分析1. 微服务注册:2. 微服务实例注册:3. 服务发现:4. 检测服务是否存在:5. 客户端心跳:五. 服务实现1. 配置文件2. 配置解析3. API 调用实现4. http 简单封装5. provider 代码6. consumer 代码六. 构建编译七. 启动与通讯上一章 ServiceComb 开发实战(1)...

XBK学习day11_追梦娃的博客-程序员资料

XBK(Percona-Xtrabackup)-物理备份工具1.1下载并安装Xtrabackup工具安装依赖包:wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repoyum -y install perl perl-devel libaio libaio-devel perl...

python if else 语句 练习题_ifelse语句练习_Mr_Li1的博客-程序员资料

 请输入成绩:如果大于等于90,输出“优秀”,如果大于等于70,输出“良好”, 如果大于等于60,输出“及格”,否则输出“不及格”a=input(&quot;请输入成绩:&quot;)if len(a)==2: b=int(a) if b&amp;gt;=90: print(&quot;优秀&quot;) elif b&amp;gt;=70 and b&amp;lt;90: print(&quot;良好&quot;) ...

Rasa官方教程翻译9 使用Docker运行Rasa_dingfengen的博客-程序员资料

这是一个关于如何使用Docker构建Rasa智能助手的指南。如果你之前没有使用过Rasa,我们建议你先从Rasa Tutorial开始。安装Docker使用Rasa和Docker构建智能助手设置与智能助手交互自定义模型选择标签使用Docker训练自定义Rasa模型运行Rasa服务使用Docker Compose运行多个服务添加自定义Actions新建一个...

基于JavaWeb的收银台系统_java开源收银系统_Altanter的博客-程序员资料

简介本项目采用WEB+Servlet+HTML+CSS+JS实现,模拟收银台实现基本的操作。重要知识点1、Java类集的使用2、Servlet的使用3、前端部分知识的简单运用。4、数据库的表的设计,尤其是订单和订单项之间的设计5、JDBC编程核心需求实现如下的操作:1、上架商品2、浏览商品3、更新商品信息4、购买商品5、浏览订单数据库设计账户表(account)商品表(goods)订单表(order)订单项表(order_item)创建数据库代码:注意为了避免

随便推点

方阵和行列式_方阵与行列式_Young_Super的博客-程序员资料

方阵 :      行数和列数相等的矩阵叫做方阵行列式 :      行列式用 " |  | " 表示,行列式的实质其实是一个代数运算求得的标量值,而且必须是方阵行列式才有定义。2阶方阵的行列式的求法 :       主对角线的乘积减去次对角线的乘积     3阶方阵的行列式的求法 :    N阶方阵的行列

通过网络给sparc环境安装solaris 10 操作系统_weixin_34336292的博客-程序员资料

一、环境介绍1.目的在没有光驱的情况下客户端服务器进行solaris10 1/13系统重装2.基础环境安装服务器:SUN M8000, 已安装Oracle Solaris 10 1/13,ixgbe0 ip:192.168.0.101e1000g1 ip:192.168.9.10客户端:SUN M8000,无光驱,ixgbe0 ip:192....

前端layui框架分页_layui 前端分页_触不可及的Allen的博客-程序员资料

layui 框架layui官方地址layui是一个前端框架,更好的封装了前端所需要的模块。简化 前端程序员的工作,丰富的样式变化,使界面更加美观,功能更加丰富。分页功能在这里记录一下遇见的问题,后端传输数据给前端,前端进行判断产生分页效果。思路ajax从后端一次性接收数据,然后截断数据分页渲染演示layui Page&lt;!DOCTYPE html&gt;&lt;html&gt;&lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;tit

多任务验证码识别运行问题(tensorflow<=1.15.0)_星辰angel的博客-程序员资料

问题1:ModuleNotFoundError: No module named ‘nets’1.解决方案:在自己的models\research\slim文件下运行命令python setup.py buildpython setup.py install注:python setup.py build可能会出现error: could not create ‘build’: 当文件已存在时,无法创建该文件的问题,此时可以将里面已存在的BUILD文件改名,在执行上面的命令。如果之后依然存在Mo

MyBatis面试题集锦_猿人启示录的博客-程序员资料

1、什么是 Mybatis?(1)Mybatis 是一个半 ORM(对象关系映射)框架,它内部封装了 JDBC,开发时只需要关注 SQL 语句本身,不需要花费精力去处理加载驱动、创建连接、创建statement 等繁杂的过程。程序员直接编写原生态 sql,可以严格控制 sql 执行性能,灵活度高。(2)MyBatis 可以使用 XML 或注解来配置和映射原生信息,将 POJO 映射成数据库...

Posix线程编程指南(1)-线程创建与取消_posix 线程 是用 动态创建_bluemiles的博客-程序员资料

杨沙洲2001 年 10 月 这是一个关于Posix线程编程的专栏。作者在阐明概念的基础上,将向您详细讲述Posix线程库API。本文是第一篇将向您讲述线程的创建与取消。一、线程创建1.1 线程与进程相对进程而言,线程是一个更加接近于执行体的概念,它可以与同进程中的其他线程共享数据,但拥有自己的栈空间,拥有独立的执行序列。在串行程序基础上引入线程和进程是为了提高程序的并发度,从而提高程序运

推荐文章

热门文章

相关标签