利用phpexcel把excel导入数据库和数据库导出excel实现

代码如下:

<?php
/*
*author zhy
*date 2012 06 12
*for excel
*/
date_default_timezone_set("PRC");
error_reporting(E_ALL);
error_reporting(0);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />');

require_once ('../Classes/PHPExcel.php');
require_once("config.php");
require_once("mysql.class.php");

//根据时间生成采购报表
$time = date("a");
$minute = date("i");
$apm  = "";
if($time=='pm'){
    $apm     = $time;
    $stime   = mktime(12,00,00,date('m'),date('d')-1,date('Y'));
    $etime   = mktime(11,59,59,date('m'),date('d'),date('Y'));
}else{
  $apm     = $time;
    $stime   = mktime(12,00,00,date('m'),date('d')-1,date('Y'));
    $etime   = mktime(11,59,59,date('m'),date('d'),date('Y'));
}

//实例化excel类
$objPHPExcel = new PHPExcel();

////////获取文档信息
////////$objProps = $objPHPExcel->getProperties();
///////print_r($objProps);
///////echo "<br/>";
///////$objProps->setDescription("test_123456");
///////print_r($objProps);

$objPHPExcel->setActiveSheetIndex(0)
    ->setCellValue('A5','商品编码')
                ->setCellValue('B5','货号')
                ->setCellValue('C5','商品名称')
                ->setCellValue('D5','采购量');

//设置选定sheet表名
$objPHPExcel->getActiveSheet()->setTitle('祖名');
//设置字体样式
$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setName('Arial')->setSize(25);//////->setUnderline(true);/////->getColor()->setARGB('FFFF0000');///->setBold(true);
//合并单元格 给单元格赋值(数值,字符串,公式)
$objPHPExcel->getActiveSheet()->mergeCells('A1:D3')->setCellValue('A1', 'zhongyi清单');
///////$objPHPExcel->getActiveSheet()->mergeCells('A4:D4')->setCellValue('A4', "=SUM(E4:F4)");

$date_now  = date("Y-m-d");
$objPHPExcel->getActiveSheet()->mergeCells('A4:D4')->setCellValue('A4', "采购日期:".$date_now." ".$apm." ");
//设置单列宽度
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);//$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setRowHeight(50);/
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(44);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(15);

//大边框样式 边框加粗
$lineBORDER = array(
 'borders' => array(
  'outline' => array(
   'style' => PHPExcel_Style_Border::BORDER_THICK,
   'color' => array('argb' => '000000'),
  ),
 ),
);
//表头样式
$head = array(
    'font'    => array(
    'bold'      => true
  ),
 'alignment' => array(
    'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
    'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER
   ),

);
//标题样式
$title = array(
    'font'    => array(
    'bold'      => true
    ),
);
//居中对齐
$CENTER = array(
    'alignment' => array(
      'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
      'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER
     ),
);
//靠右对齐
$RIGHT = array(
    'alignment' => array(
      'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_RIGHT,
      'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER
     ),
);
//细边框样式
$linestyle = array(
 'borders' => array(
  'outline' => array(
   'style' => PHPExcel_Style_Border::BORDER_THIN,
   'color' => array('argb' => 'FF000000'),
  ),
 ),
);

$objPHPExcel->getActiveSheet()->getStyle('A1:D3')->applyFromArray($head);///->getAlignment()->getHorizontal('');///->getBorders()->getTop()->setBorderStyle('');
//->setWrapText(true);自动换行
$objPHPExcel->getActiveSheet()->getStyle('A4:D4')->applyFromArray($RIGHT);
$objPHPExcel->getActiveSheet()->getStyle('A5:D5')->applyFromArray($title);

//填充色
/////$objPHPExcel->getActiveSheet()->getStyle('A1')->getFill()->getStartColor()->setARGB('FFFF0000');/

//插入数据
$dsql->Execute('omebrand_list',"select i.goods_id , sum( `nums` ) AS num, i.name,i.addon,i.price,g.bn as b,i.bn as h,
g.goods_id,i.goods_id,i.order_id
FROM `sdb_b2c_order_items` as i,sdb_b2c_goods as g
WHERE i.order_id in (select order_id from sdb_b2c_orders where status ='active' and createtime between $stime and $etime) and i.goods_id=g.goods_id and g.cat_id=173 GROUP BY h");
$m = 0;
  unset($re);
  while($row=$dsql->GetObject('omebrand_list'))
  {   $re[$m] = get_object_vars($row);
  $m++;
  }
$row_count = 5;
$objPHPExcel->setActiveSheetIndex(0)
   ->setCellValue('A6', 12325416541)
            ->setCellValue('B6', 4962132165262)
            ->setCellValue('C6', 121515212515241521)
            ->setCellValue('D6', 96215465415);
foreach($re as $r => $dataRow) {
 $baseRow = 6;
 $row = $baseRow + $r;
 $bn=$dataRow[h];
 $goods_id = $dataRow[goods_id];
   $spec_value = "";
   $aa = unserialize($dataRow[addon]);
   if ($aa['product_attr']){
    foreach ($aa['product_attr'] as $arr_special_info)  {
     $spec_value = $arr_special_info['value'];
    }
   }

preg_match_all('/\-?\d+\.?\d*/i',$spec_value,$row1);
   $num = $row1[0][0];
   $all = $num*$dataRow[num];
   if($spec_value==''){
    $all=$dataRow['num'];
    //$prce=$dataRow[price];
   }
 $objPHPExcel->setActiveSheetIndex(0)
    ->setCellValue('A'.$row, $dataRow['b'])
                ->setCellValue('B'.$row, $bn)
             ->setCellValue('C'.$row, $dataRow['name'])
             ->setCellValue('D'.$row, $all);
    $objPHPExcel->getActiveSheet()->getStyle('A'.$row_count)->applyFromArray($linestyle);            
    $objPHPExcel->getActiveSheet()->getStyle('B'.$row_count)->applyFromArray($linestyle);
    $objPHPExcel->getActiveSheet()->getStyle('C'.$row_count)->applyFromArray($linestyle);
    $objPHPExcel->getActiveSheet()->getStyle('D'.$row_count)->applyFromArray($linestyle);

$baseRow++;
    $row_count++;
}
$objPHPExcel->getActiveSheet()->getStyle('A'.$row_count)->applyFromArray($linestyle);            
$objPHPExcel->getActiveSheet()->getStyle('B'.$row_count)->applyFromArray($linestyle);
$objPHPExcel->getActiveSheet()->getStyle('C'.$row_count)->applyFromArray($linestyle);
$objPHPExcel->getActiveSheet()->getStyle('D'.$row_count)->applyFromArray($linestyle); 
$objPHPExcel->getActiveSheet()->getStyle('A5:D'.$row_count)->applyFromArray($CENTER); 
$objPHPExcel->getActiveSheet()->getStyle('A1:D'.$row_count)->applyFromArray($lineBORDER);

//设置打印页边距
$objPHPExcel->getActiveSheet()->getPageMargins()->setTop(0);
$objPHPExcel->getActiveSheet()->getPageMargins()->setRight(0);
$objPHPExcel->getActiveSheet()->getPageMargins()->setLeft(0);
$objPHPExcel->getActiveSheet()->getPageMargins()->setBottom(0);
//设置纸张类型
$objPHPExcel->getActiveSheet()->getPageSetup()->setPaperSize(PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4);
//设置自动筛选
$objPHPExcel->getActiveSheet()->setAutoFilter('A5:D'.$row_count);
//设置自动换行
$objPHPExcel->getActiveSheet()->getStyle('B6:B'.$row_count)->getAlignment()->setWrapText(true);
//设置格式化数字
$objPHPExcel->getActiveSheet()->getStyle('A6:A'.$row_count)->getNumberFormat()->setFormatCode('0000000000');

//设置安全级别
$md=md5(time());
$md=substr($md,0,8);
$objPHPExcel->getActiveSheet()->getProtection()->setPassword("$md");
$objPHPExcel->getActiveSheet()->getProtection()->setSheet(true);//
$objPHPExcel->getActiveSheet()->getProtection()->setSort(true);
$objPHPExcel->getActiveSheet()->getProtection()->setInsertRows(true);
$objPHPExcel->getActiveSheet()->getProtection()->setFormatCells(true);

//添加图片
/*
$obj=$objPHPExcel->getActiveSheet();
$objDrawing = new PHPExcel_Worksheet_Drawing();  
$objDrawing->setName('wsyImg');  
$objDrawing->setDescription('Image inserted by zhy');  
$objDrawing->setPath('./wsy.jpg');  
$objDrawing->setHeight(50);  
$objDrawing->setCoordinates('H23');  
$objDrawing->setOffsetX(60);  
$objDrawing->setRotation(-10);   /
$objDrawing->getShadow()->setVisible(true);  
$objDrawing->getShadow()->setDirection(-20); /
$objDrawing->setWorksheet($obj);
*/

//页眉页脚
//$objPHPExcel->getActiveSheet()->getHeaderFooter()->setOddHeader('zhy');
//$objPHPExcel->getActiveSheet()->getHeaderFooter()->setOddFooter('end');

$objPHPExcel->setActiveSheetIndex(0);
$tname=date('Y-m-dH',time());
$tnam=iconv('UTF-8','GBK','祖名订单');
$tname=$tnam.$tname;

// Excel 2007保存
//$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
//$objWriter->save(str_replace('.php', '.xlsx', __FILE__));

// Excel 5保存
//$objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
//$objWriter->save(str_replace('.php', '.xls', __FILE__));

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save(str_replace('.php', '.xls', __FILE__));

//$url = "/data/home/htdocs/ec/public/files/".date("Y")."/".date("Ym")."/";
createDir($url);
function createDir($dir) {
 if  (!is_dir ($dir )) {
  mkdir($dir, 0777, true);
  chmod($dir, 0777);  
  chown( $dir, 'daemon' );
  chgrp( $dir, 'daemon' );   
 }
}
$name='forexmple_excel';
rename(str_replace('.php', '.xls', __FILE__), $name.'.xls');

?>

(0)

相关推荐

  • php通过PHPExcel导入Excel表格到MySQL数据库的简单实例

    如下所示: <?php define('BASE_URL', realpath(dirname(__FILE__))); require_once BASE_URL . '/PHPExcel/PHPExcel.php';//引入PHPExcel类文件 //excel文件的地址 $excel_fiel_path = './phpexcel.xls'; $PHPExcel = new PHPExcel();// 实例化PHPExcel工具类 //分析文件获取后缀判断是2007版本还是2003 $ex

  • 使用PHPExcel实现数据批量导出为excel表格的方法(必看)

    首先需要下载PHPExecel类文件,帮助文档可以参考PHPExcel中文帮助手册|PHPExcel使用方法. 下面直接上例子,是我自己写的一个简单的批量导出数据为excel的例子 前台页面 比较简单,就是一个超链接,跳转到处理页面,超链接也可以跟一些参数(看需求)! <a href="./Process1.php" rel="external nofollow" >导出excel表格</a> 后台Process.php页面 /** * 批量

  • 使用phpexcel类实现excel导入mysql数据库功能(实例代码)

    下载phpexcel文件,地址:phpexcel.codeplex.com/ 代码示例 require_once 'phpexcel/Classes/PHPExcel.php'; require_once 'phpexcel/Classes/PHPExcel/IOFactory.php'; require_once 'phpexcel/Classes/PHPExcel/Reader/Excel5.php'; $objReader = PHPExcel_IOFactory::createReade

  • 基于PHPExcel的常用方法总结

    复制代码 代码如下: // 通常PHPExcel对象有两种实例化的方式// 1. 通过new关键字创建空白文档$phpexcel = newPHPExcel();// 2. 通过读取已有的模板创建$phpexcel =PHPExcel_IOFactory::createReader("Excel5")->load("template.xls"); 复制代码 代码如下: <?//设置PHPExcel类库的include pathset_include_pa

  • ThinkPHP与PHPExcel冲突解决方法

    很早之前就知道有一个叫做PHPExcel的类(官方网站)可以用来操作Excel,一直没有机会尝试,今天试用发现无比强大,下载后的源码包里有详细文档,几乎能实现手工操作Excel能实现的一切功能. 一个简单的读取Excel的例子如下: 复制代码 代码如下: $inputFileType = 'Excel2007'; $inputFileName = './public/files/import_user_template.xlsx'; $sheetname = 'Sheet1'; //指定Exce

  • PHPExcel读取Excel文件的实现代码

    涉及知识点: php对excel文件进行循环读取 php对字符进行ascii编码转化,将字符转为十进制数 php对excel日期格式读取,并进行显示转化 php对汉字乱码进行编码转化 复制代码 代码如下: <?php require_once 'PHPExcel.php'; /**对excel里的日期进行格式转化*/ function GetData($val){ $jd = GregorianToJD(1, 1, 1970); $gregorian = JDToGregorian($jd+in

  • thinkPHP+phpexcel实现excel报表输出功能示例

    本文实例讲述了thinkPHP+phpexcel实现excel报表输出功能.分享给大家供大家参考,具体如下: 准备工作: 1.下载phpexcel1.7.6类包: 2.解压至TP框架的ThinkPHP\Vendor目录下,改类包文件夹名为PHPExcel176,目录结构如下图: 编写代码(以一个订单汇总数据为例): 1. 创建数据库及表;   2. 创建tp项目,配置项目的数据库连接,这些基本的就不说了:   3. 在项目的Lib\Action下创建一个新的类文件ExportStatistics

  • 利用phpExcel实现Excel数据的导入导出(全步骤详细解析)

    很多文章都有提到关于使用phpExcel实现Excel数据的导入导出,大部分文章都差不多,或者就是转载的,都会出现一些问题,下面是本人研究phpExcel的使用例程总结出来的使用方法,接下来直接进入正题. 首先先说一下,本人的这段例程是使用在Thinkphp的开发框架上,要是使用在其他框架也是同样的方法,很多人可能不能正确的实现Excel的导入导出,问题基本上都是phpExcel的核心类引用路径出错,如果有问题大家务必要对路劲是否引用正确进行测试. (一)导入Excel 第一,在前台html页面

  • PHPExcel简单读取excel文件示例

    本文实例讲述了PHPExcel简单读取excel文件的方法.分享给大家供大家参考,具体如下: PHP Excel 2007 classes Project providing a set of classes for the PHP programming language, which allow you to write to and read from different file formats, like Excel 2007, PDF, HTML, ... This project

  • PHPExcel冻结(锁定)表头的简单实现方法

    本文实例讲述了PHPExcel冻结(锁定)表头的简单实现方法.分享给大家供大家参考,具体如下: PHPExcel是一款功能比较强大的操作微软excel的PHP插件,在导出数据时为了方便查看,有时需要锁定表头,也就是在滚动查看数据时,表头始终出现在视野中,而不会消失. 调用方法如下: $objPHPExcel = new PHPExcel(); $objPHPExcel->setActiveSheetIndex(0); $objPHPExcel->getActiveSheet()->fre

随机推荐