利用PHPExcel读取Excel的和导出数据到Excel

导出数据到Excel

query('set names utf8');
$sql = "SELECT * from ecs_order_goods ORDER BY order_id ASC;";

$res_zz = $pdo->query($sql);
$result = $res_zz->fetchAll();

$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(15);

date_default_timezone_set("Asia/Shanghai"); //时区
$filename = date('YmdHis');
//定义第一行内容

$objPHPExcel->getActiveSheet()->SetCellValue('A1', '订单商品信息自增id');
$objPHPExcel->getActiveSheet()->SetCellValue('B1', '订单商品信息对应的详细信息id');
$objPHPExcel->getActiveSheet()->SetCellValue('C1', '商品id');
$objPHPExcel->getActiveSheet()->SetCellValue('D1', '商品名称');


$excelRow = 2; //从第二行开始插入数据
foreach ($result as $data) {
    $objPHPExcel->getActiveSheet()->setCellValueExplicit('A' . $excelRow, $data['rec_id']);
    $objPHPExcel->getActiveSheet()->setCellValueExplicit('B' . $excelRow, $data['order_id']);
    $objPHPExcel->getActiveSheet()->setCellValueExplicit('C' . $excelRow, $data['goods_name']);
    $objPHPExcel->getActiveSheet()->setCellValueExplicit('D' . $excelRow, $data['goods_sn']);
    $excelRow++;
}

$objPHPExcel->setActiveSheetIndex(0);
header('Pragma:public');
header('Content-Type:application/x-msexecl;name="' . $filename . '.xls"');
header("Content-Disposition:inline;filename=\"$filename.xls\"");
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;

读取Excel

function read($filename, $encode = 'utf-8') {
    require_once getcwd() . "/exportexcel/PHPExcel/IOFactory.php";
    //include '../exportexcel/PHPExcel/IOFactory.php';
    $objReader = PHPExcel_IOFactory::createReader('Excel5');
    $objReader->setReadDataOnly(true);
    $objPHPExcel = $objReader->load($filename);
    $objWorksheet = $objPHPExcel->getActiveSheet();
    $highestRow = $objWorksheet->getHighestRow();
    //echo $highestRow;
    $highestColumn = $objWorksheet->getHighestColumn();
    $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
    $excelData = array();
    for ($row = 1; $row <= $highestRow; $row++) {
        for ($col = 0; $col < $highestColumnIndex; $col++) {
            $excelData[$row][] = (string) $objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
        }
    }
    return $excelData;
}

你可能感兴趣的:(php)