PhpSpreadsheet 导入、导出数据

先引入

use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;

导出数据

/**
* 导出Excel
 * @param $datas    导出数据
 * @param $param    导出标题及每列对应的数据键名 ['数据键名' => '列标题']
 * @param $commonField  每列公共的数据
 * @param string $fileName  文件名称--保存目录为空时有效
 * @param string $options    保存目录--为空时直接唤醒浏览器下载
 * @return bool|mixed|string    失败则
 */
function exportExcel($datas, $param, $commonField, $fileName = '', $options = '')
{
    $commonColumn = []; //字段名称数组
    try {
        if (empty($datas)) {
            return false;
        }
        if (empty($param)) {
            return false;
        }
        //列名  字段名有多少个  列名就有多少
        $rows = 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',
            'BA', 'BB', 'BC', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BK', 'BL', 'BM', 'BN', 'BO', 'BP', 'BQ', 'BR', 'BS', 'BT', 'BU', 'BV', 'BW', 'BX', 'BY', 'BZ'
        );
        set_time_limit(50);

        /** @var Spreadsheet $objSpreadsheet */
        $objSpreadsheet = new Spreadsheet();
        //设置默认文字居左,上下居中
        $styleArray = [
            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_LEFT,
                'vertical'   => Alignment::VERTICAL_CENTER,
            ],
        ];
        $objSpreadsheet->getDefaultStyle()->applyFromArray($styleArray);
        //设置Excel Sheet
        $activeSheet = $objSpreadsheet->setActiveSheetIndex(0);
        $startRow = 2;
        //默认文本格式
        $pDataType = DataType::TYPE_STRING;
        $sort_id = 1;
        //行数据处理
        foreach ($datas as $sKey => $sItem) {
            $starColumn = 0;
            foreach ($param as $key => $value) {
                $activeSheet->setCellValueExplicit($rows[$starColumn] .$startRow, $val, $pDataType);
                $starColumn ++;
            }
            $startRow++;
        }
        $titleRow = 1;
        $titleColumn = 0;
        $pDataType = DataType::TYPE_STRING2;
        // 设置标题
        foreach ($param as $key => $title) {
            $activeSheet->setCellValueExplicit($rows[$titleColumn] . $titleRow, $title, $pDataType );
            if ($key == 'address') {
                $activeSheet->getColumnDimension($rows[$titleColumn])->setWidth(70);
            } else {
                $activeSheet->getColumnDimension($rows[$titleColumn])->setWidth(30);
            }
            $titleColumn ++;
        }
        unset($datas);
        $fileName = !empty($fileName) ? $fileName : (date('YmdHis') . '.xls');
        if (empty($options)) {
            header("Content-Type: application/force-download");
            header("Content-Type: application/octet-stream");
            header("Content-Type: application/download");
            header('Content-Disposition:inline;filename="'.$fileName.'"');
            header("Content-Transfer-Encoding: binary");
            header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
            header("Pragma: no-cache");
            $savePath = 'php://output';
        } else {
            $savePath = $options . $fileName;
        }
        ob_clean();
        ob_start();
        $objWriter = IOFactory::createWriter($objSpreadsheet, 'Xls');
        $objWriter->save($savePath);
        //释放内存
        $objSpreadsheet->disconnectWorksheets();
        unset($objSpreadsheet);
        ob_end_flush();
        return $savePath;
    } catch (Exception $e) {
        returnError($e->getMessage());
    }
}

导入数据 公共处理

/**
 * 导入Excel表取出需要的内容
 * @param $excelPath    excel表路径
 * @param $param    每列对应数据键名及标题 ['A' => ['key' => 'A',title => '标题名称']] 标题名为空则不验证
 * @param $startRow 内容开始的行
 * @return array    返回数据内容 [['A' => 'content']];
 * @throws \PhpOffice\PhpSpreadsheet\Calculation\Exception
 * @throws \PhpOffice\PhpSpreadsheet\Exception
 * @throws \think\Exception
 */
function importExcel($excelPath, $param, $startRow) {
    $excelObj = IOFactory::load($excelPath);
    if (!$excelObj) {
        returnError('加载Excel表失败,请检查Excel内容');
    }
    $excelWorkSheet = $excelObj->getActiveSheet();
    $rowCount = $excelWorkSheet->getHighestRow();
    if ($rowCount <= 0) {
        returnError('Excel表内容为空。');
    }
    //验证标题
    foreach ($param as $column => $content) {
        $item = $excelWorkSheet->getCell($column . ($startRow - 1))->getCalculatedValue();
        if ($item != $content['title'] && !empty($content['title'])) {
            returnError('请检查模板标题是否正确。');
        }
    }
    $excelData = array();
    for ($row = $startRow; $row <= $rowCount; $row++ ) {
        $rowData = array();
        foreach ($param as $column => $content) {
            $item = $excelWorkSheet->getCell($column . $row)->getCalculatedValue();
            $rowData[$content['key']] = $item;
        }
        if(!implode('',$rowData)){
            continue;//删除空行
        }
        $excelData[] = $rowData;
    }
    return $excelData;
}

进行导入数据处理

public function importData(){
    $name = $_FILES['file']["name"];//上传文件的文件名
    $size = $_FILES['file']["size"];//上传文件的大小
    $tmp_name = $_FILES['file']["tmp_name"];//上传文件的临时存放路径
    if ($size <= 0){
        returnError('文件内容读取失败');
    }

    $exts = strtolower(strstr($name,'.'));
    if ($exts != ".xls" && $exts != ".xlsx") {
        returnError('文件格式错误,请上传EXCEL文件');
    }

    $filename = time().$exts;
    $path = dirname(__FILE__) . '/../../../public/uploads/' . date('ymd');
    if (!is_dir($path)) {
        mkdir( $path, 0777, true);
    }
    $excelPath = $path . '/' . $filename;
    move_uploaded_file($tmp_name, $excelPath);

    $startRow = 2;
    $param = [
        'A' => ['key' => '数据库字段名', 'title' => '导入的excel字段名'],
        'B' => ['key' => '数据库字段名', 'title' => '导入的excel字段名'],
        'C' => ['key' => '数据库字段名', 'title' => '导入的excel字段名'],
    ];
    
    $excelData = $this->importExcel($excelPath, $param, $startRow);
    if(count($excelData)==0){
        returnError('获取数据失败');
    }
    $file_path = 'uploads/' . date('ymd') . '/' . $filename;
    
    unlink($excelPath);	
	
	//接下来进行 数据库读取数据的操作
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值