年后上班,在摸鱼了一个礼拜之后,又开始了漫漫码农之路。
今天领导提出了新的需求,要在网页端进行文件上传更新数据库的内容,功能比较简单,查看了刚入职时写的类似功能,粘贴复制之后发现不能用......
于是抄起键盘重新写了一遍,由于类似的代码写的不多,因此也是顺便深究一下这方面的业务技能。
实现很简单:
HTML:
<li style="width:200px;"><a id="in" class="toolsA" style="display: none;"><input name="userfile" type="file" accept="application/application/vnd.ms-excel" id="orderIn" value="导入" style="width:200px"></a></li>
<li style="width:140px;"><a id="order-in" title="导入" class="toolsA" style="display: none;"><input type="button" id="orderInt" value="导入"></a></li>
注意在选择上传文件的格式
JS:
var fd = new FormData();
??????????? fd.append("upload", 1);
??????????? fd.append("upfile", $("#orderIn").get(0).files[0]);
??????????? $.ajax({
??????????????? url: "../php/order.php",
??????????????? type: "POST",
??????????????? processData: false,
??????????????? contentType: false,
??????????????? async : true,
??????????????? data: fd,
})
PHP
PHP中使用了PFPExcel库
$uploadfile =‘文件路劲‘;
??????? $objReader = PHPExcel_IOFactory::createReader(‘Excel2007‘);/*Excel5 for 2003 excel2007 for 2007*/
??????? $objPHPExcel = $objReader->load($uploadfile); //Excel 路径
??????? $sheet = $objPHPExcel->getSheet(1);
??????? $objWorksheet = $objPHPExcel->getActiveSheet();
??????? $highestRow = $objWorksheet->getHighestRow(); ??// 取得总行数
??????? $highestColumn = $objWorksheet->getHighestColumn();
??????? $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);//总列数
读
for ($row = 2;$row <=$highestRow;$row++) {
??????????? //注意highestColumnIndex的列数索引从0开始
??????????? for ($col = 0; $col < $highestColumnIndex; $col++) {
??????????????? $strs[$col] = $objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
写:
$objWorksheet->setCellValue(‘M1‘,$value);
$objWorksheet->setCellValue(‘N1‘,$value);
??????????????????? $objWorksheet->setCellValue(‘O1‘.$value);
??????????????????? $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel,‘Excel2007‘); ??//设定写入excel的类型
??????????????????? $objWriter->save($uploadfile); // 保存
??????????? }
}
实现文件上传
原文地址:https://www.cnblogs.com/zxyblogs/p/8525005.html