[moka同学笔记]PHPexcel之excel导出和导入

原案例来自http://www.sucaihuo.com/      有修改      

1.目录结构(文件不用解释,应该都可以看得懂,直接看代码)

2.注意数据库表(需要在connect.php中修改数据库配置)

创建数据库表

CREATE TABLE `user` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(15) NOT NULL,
  `email` varchar(20) DEFAULT NULL,
  `grade` int(11) DEFAULT NULL,
  `password` varchar(32) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=16 DEFAULT CHARSET=utf8;

3.代码

   视图index.php

            <div class="demo">
                <h2 class="title"><a href="http://www.sucaihuo.com/js/140.html">教程:PHPexcel之excel导出和导入</a></h2>
                <p style="margin:10px 0"><a href="export.php" class="btn">导出</a></p>
                <form action="import.php" method="post" enctype="multipart/form-data">
                    <div class="control-group">
                        <label>Excel表格:</label>
                        <input type="file"  name="file"/>
                    </div>
                    <div class="control-group">
                        <input type="submit"  value="导入" />
                    </div>
                </form>
            </div>

4.导入(import.php)

<?php

include_once('connect.php');
$tmp = $_FILES['file']['tmp_name'];
if (empty($tmp)) {
    echo '请选择要导入的Excel文件!';
    exit;
}

$save_path = "uploads/";
$filename = $save_path . date('Ymdhis') . ".xls"; //上传后的文件保存路径和名称 
if (copy($tmp, $filename)) {
    require_once 'PHPExcel.class.php';
    require_once 'PHPExcel/Reader/Excel5.php';


    $PHPReader = new PHPExcel_Reader_Excel5(); //PHPExcel_Reader_Excel2007 PHPExcel_Reader_Excel5
    //载入文件
    $PHPExcel = $PHPReader->load($filename);

    //获取表中的第一个工作表,如果要获取第二个,把0改为1,依次类推
    $currentSheet = $PHPExcel->getSheet(0);
    //获取总列数
    $allColumn = $currentSheet->getHighestColumn();
    //获取总行数
    $allRow = $currentSheet->getHighestRow();
    //循环获取表中的数据,$currentRow表示当前行,从哪行开始读取数据,索引值从0开始
    for ($currentRow = 1; $currentRow <= $allRow; $currentRow++) {
        //从哪列开始,A表示第一列
        for ($currentColumn = 'A'; $currentColumn <= $allColumn; $currentColumn++) {
            //数据坐标
            $address = $currentColumn . $currentRow;
            //读取到的数据,保存到数组$arr中
            $data[$currentRow][$currentColumn] = $currentSheet->getCell($address)->getValue();
        }
    }

    $add_time = date('Y-m-d H:i:s', time());
    foreach ($data as $k => $v) {
        if ($k > 1) {
            $sql = "insert into user (username,email,password) values ('" . $v['B'] . "', '" . $v['C'] . "', '" . $v['D'] . "')";

            mysql_query($sql);
        }
    }

    $sql = "SELECT * FROM user";
    $result = mysql_query($sql);
    $tip = '用户导入成功' . ',现在' . mysql_num_rows($result) . '条数据了!';
    echo "<script>alert('" . $tip . "');history.go(-1);</script>";
    exit;
} 

5.导出(export.php)

<?php

/**
 * PHPEXCEL生成excel文件
 * @author:素材火  http://blog.csdn.net/winter13292/article/details/8123755
 * @desc 支持任意行列数据生成excel文件,暂未添加单元格样式和对齐
 */

include_once('connect.php');

//$list = array(
//    array('id' => '1', 'email' => "87423050@qq.com", 'password' => 'sucaihuo.com'),
//    array('id' => '2', 'email' => '41614@qq.com', 'password' => 'hjl666666'),
//    array('id' => '3', 'email' => 'zhangliao@163.com', 'password' => 'zhangqirui'),
//);
$query = mysql_query("select * from user limit 50"); 
$i =0;
$list = array();
while($row=mysql_fetch_array($query)){ 
    $list[$i]['id'] = $row['id']; 
    $list[$i]['username'] = $row['username'];
    $list[$i]['email'] = $row['email'];
    $list[$i]['password'] = $row['password'];
    $i++;
} 

$title = array('ID', '姓名','邮箱','密码'); //设置要导出excel的表头
exportExcel($list, '名单表', $title);

function exportExcel($data, $savefile = null, $title = null, $sheetname = 'sheet1') {
    require_once 'PHPExcel.class.php';
    //若没有指定文件名则为当前时间戳
    if (is_null($savefile)) {
        $savefile = time();
    }
    //若指字了excel表头,则把表单追加到正文内容前面去
    if (is_array($title)) {
        array_unshift($data, $title);
    }
    $objPHPExcel = new PHPExcel();
    //Excel内容
    $head_num = count($data);

    foreach ($data as $k => $v) {
        $obj = $objPHPExcel->setActiveSheetIndex(0);
        $row = $k + 1; //
        $nn = 0;

        foreach ($v as $vv) {
            $col = chr(65 + $nn); //
            $obj->setCellValue($col . $row, $vv); //列,行,值
            $nn++;
        }
    }
    //设置列头标题
    for ($i = 0; $i < $head_num - 1; $i++) {
        $alpha = chr(65 + $i);
        $objPHPExcel->getActiveSheet()->getColumnDimension($alpha)->setAutoSize(true); //单元宽度自适应 
        $objPHPExcel->getActiveSheet()->getStyle($alpha . '1')->getFont()->setName("Candara");  //设置字体
        $objPHPExcel->getActiveSheet()->getStyle($alpha . '1')->getFont()->setSize(12);  //设置大小
        $objPHPExcel->getActiveSheet()->getStyle($alpha . '1')->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_BLACK); //设置颜色
        $objPHPExcel->getActiveSheet()->getStyle($alpha . '1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); //水平居中
        $objPHPExcel->getActiveSheet()->getStyle($alpha . '1')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER); //垂直居中
        $objPHPExcel->getActiveSheet()->getStyle($alpha . '1')->getFont()->setBold(true); //加粗
    }

    $objPHPExcel->getActiveSheet()->setTitle($sheetname); //题目
    $objPHPExcel->setActiveSheetIndex(0); //设置当前的sheet  
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="' . $savefile . '.xls"');//文件名称
    header('Cache-Control: max-age=0');
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); //Excel5
    $objWriter->save('php://output');
}


?>

6.其他文件

源码地址:http://share.weiyun.com/590da4cea5e53e679fe52e013ab38f6e (密码:oJzV)

有问题,请联系QQ1727728211

posted @ 2016-09-26 17:05  mokal同学  阅读(565)  评论(0编辑  收藏  举报