您现在的位置是:首页 > 文章详情

Java与Excel的交互!-

日期:2018-10-28点击:481

-1. Excel (POI)

1.1 导入poi报表需要的jar包

<poi.version>3.11</poi.version> <!-- <!-- Excel解析工具类 <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>${poi.version}</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>${poi.version}</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>${poi.version}</version> </dependency> --> <!-- excel2003使用的包 --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.11</version> </dependency> <!-- excel2007+使用的包 --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.11</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>3.11</version> </dependency>

1.2.访问

$("#exportXlsBtn").click(function(){ // 下载效果 不能是ajax异步 <!-- $.ajax({ type: "GET", url: "/report/exportXls" }); --> location.href = "/excelInpost/downLoad?filename=运单模板表.xlsx"; }); 

1.3 用法(页面)

 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>运单批量导入</title> <!-- 导入jquery核心类库 --> <script type="text/javascript" src="../../js/jquery-1.8.3.js"></script> <!-- 导入easyui类库 --> <link rel="stylesheet" type="text/css" href="../../js/easyui/themes/default/easyui.css"> <link rel="stylesheet" type="text/css" href="../../js/easyui/themes/icon.css"> <link rel="stylesheet" type="text/css" href="../../js/easyui/ext/portal.css"> <link rel="stylesheet" type="text/css" href="../../css/default.css"> <script type="text/javascript" src="../../js/easyui/jquery.easyui.min.js"></script> <script type="text/javascript" src="../../js/easyui/ext/jquery.portal.js"></script> <script type="text/javascript" src="../../js/easyui/ext/jquery.cookie.js"></script> <script src="../../js/easyui/locale/easyui-lang-zh_CN.js" type="text/javascript"></script> <script type="text/javascript" src="../../js/jquery.ocupload-1.1.2.js"></script> <script type="text/javascript"> $(function(){ $("#grid").datagrid({ url : '/wayBill/pageQuery', method:"GET", toolbar : [ { id : 'btn-download', text : '模板下载', iconCls : 'icon-save', handler : function(){ $.messager.confirm("提示","您确定下载模板吗?",function () { location.href = "/excelInpost/downLoad?filename=运单模板表.xlsx"; }) } },{ id : 'btn-upload', text : '批量导入', iconCls : 'icon-redo' },{ id : 'btn-refresh', text : '刷新', iconCls : 'icon-reload', handler : function(){ $("#grid").datagrid('reload'); } } ], columns : [[ { field : 'id', title : '编号', width : 120 , align : 'center' },{ field : 'goodsType', title : '产品', width : 120 , align : 'center' },{ field : 'sendProNum', title : '快递产品类型', width : 120 , align : 'center' },{ field : 'sendName', title : '发件人姓名', width : 120 , align : 'center' },{ field : 'sendMobile', title : '发件人电话', width : 120 , align : 'center' },{ field : 'sendAddress', title : '发件人地址', width : 120 , align : 'center' },{ field : 'recName', title : '收件人姓名', width : 120 , align : 'center' },{ field : 'recMobile', title : '收件人电话', width : 120 , align : 'center' },{ field : 'recCompany', title : '收件人公司', width : 120 , align : 'center' },{ field : 'recAddress', title : '收件人地址', width : 120 , align : 'center' } ]], pageList: [10,20,30], pagination : true, striped : true, singleSelect: true, rownumbers : true, fit : true // 占满容器 }); /*// 一键上传 $("#btn-upload").upload({ name: 'upload', // <input name="file" /> action: '/excelInpost/excelUp', // 提交请求action路径 enctype: 'multipart/form-data', // 编码格式 autoSubmit: true, // 选中文件提交表单 onComplete: function(response) { if(response=="success"){ $.messager.alert("提示信息","数据导入成功!","info"); $("#grid").datagrid("reload"); }else{ $.messager.alert("错误提示",response,"error"); } }// 请求完成时 调用函数 });*/ $("#btn-upload").upload({ action:"/excelInpost/excelUp", name:"myFile", onComplete:function () { $.messager.alert("提示信息","数据导入成功!","info"); $("#grid").datagrid("reload"); }, onSelect:function () { // 如果文件名字不符合要求,就阻止提交, // 1 关闭默认的自动提交 this.autoSubmit = false; // 2 获取文件名 var filename = this.filename(); // 3 正则表达式校验 // . 1个换行符意外的任意字符 // * 0-n个任意字符 // \. 标识. // (a|b) 只能出现a或者b var regex = /^.*\.(xls|xlsx)$/; // 校验 if (regex.test(filename)) { // 手动提交 this.submit(); }else{ // 不符合规则,不提交,给出提醒 $.messager.alert("提示","请选择xls或者xlsx结尾的文件") } } }) }); </script> </head> <body class="easyui-layout"> <div region="center"> <table id="grid"></table> </div> </body> </html>

1.4 用法(后台) --->自定义模板下载

 /** * 模板下载 * @param filename 文件名 * @return * @throws Exception */ @GetMapping("/downLoad") public ResponseEntity<String> downLoadExcel(String filename) throws Exception { System.out.println(filename+"-------------------------------------------------------"); /** * 查找数据之后,下面只需要将内容写进xls中,然后下载 */ //1 创建工作簿 Workbook wb = new XSSFWorkbook(); //2 创建工作表 Sheet sheet = wb.createSheet(); /** * 定义公共变量 */ int rowNo=0,cellNo=0;//行号 和 列号 Row nRow = null;// 行对象通用变量 Cell nCell = null;// 单元格对象通用变量 /****************大标题打印****************/ //3 创建行 nRow = sheet.createRow(rowNo); // 设置行高 nRow.setHeightInPoints(36); //4 创建单元格 nCell = nRow.createCell(cellNo); //5 设置内容 nCell.setCellValue("运单数据"); //6 设置内容格式 // 合并单元格 //参数1:起始行 参数2:终止行 参数3:起始列 参数4:终止列 sheet.addMergedRegion(new CellRangeAddress(0, 0, (short) 0, (short) 9)); // 样式 CellStyle bigTitleCellStyle = bigTitleStyle(wb); nCell.setCellStyle(bigTitleCellStyle); rowNo++; nRow = sheet.createRow(rowNo); //小标题 String[] titles={"编号","产品","快递产品类型","发件人姓名","发件人电话","发件人地址","收件人姓名","收件人电话","收件人公司","收件人地址"}; for (int i = 0;i<titles.length;i++){ String title = titles[i]; //4 创建单元格 nCell = nRow.createCell(cellNo++);// 先创建单元格,然后在新增 //5 设置内容 nCell.setCellValue(title); //6 设置内容格式 nCell.setCellStyle(titleStyle(wb)); //设置列宽 -->自动 sheet.autoSizeColumn(i); sheet.setColumnWidth(i,sheet.getColumnWidth(i)*17/10); } //下载 DownloadUtil downloadUtil = new DownloadUtil(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); wb.write(byteArrayOutputStream); downloadUtil.download(byteArrayOutputStream,response,filename); return new ResponseEntity<>(HttpStatus.OK); }

1.5 上传导入

/** * 导入 * @return */ @RequestMapping("/excelUp") public ResponseEntity<Void> batchImport(@RequestParam("myFile") MultipartFile file){ try { // 1.1 获取文件名 String originalFilename = file.getOriginalFilename();// 文件名 String name = file.getName();//此名字对应<input> 文本框的name属性的值 // 1.2 设置保存的path String path = "d:\\"+ UUID.randomUUID().toString()+originalFilename; // 1.3 创建File--path File myFile = new File(path); // 1.4 复制 file.transferTo(myFile); // 解析xls,将数据存入数据库 // 2 创建Workbook // 2.1 创建输入流 FileInputStream is = new FileInputStream(myFile); // InputStream is = file.getInputStream(); // 2.2 创建Workbook Workbook wb = new XSSFWorkbook(is); // 3 获取Sheet Sheet sheet = wb.getSheetAt(0); // 定义List集合存放数据,最后一次性保存 List<WayBill> list = new ArrayList<>(); // 4 获取row for(Row row:sheet){ // 5 获取单元格数据 // 跳过第一行 if(row.getRowNum()==0 || row.getRowNum()==1){ continue; } // 如果第一列为空,整条数据都不读取 if(row.getCell(0)==null || (int) row.getCell(0).getNumericCellValue()==0){ continue; } WayBill wayBill = new WayBill(); //编号 int value0 = (int) row.getCell(0).getNumericCellValue(); wayBill.setId(value0); //产品 wayBill.setGoodsType(row.getCell(1).getStringCellValue()); //快递产品类型 wayBill.setSendProNum(row.getCell(2).getStringCellValue()); //发件人姓名 wayBill.setSendName(row.getCell(3).getStringCellValue()); //发件人电话 String value4 =""+ (int) row.getCell(4).getNumericCellValue(); wayBill.setSendMobile(value4); //发件人地址 wayBill.setSendAddress(row.getCell(5).getStringCellValue()); //收件人姓名 wayBill.setRecName(row.getCell(6).getStringCellValue()); //收件人电话 wayBill.setRecMobile(""+ (int) row.getCell(7).getNumericCellValue()); //收件人公司 wayBill.setRecCompany(row.getCell(8).getStringCellValue()); //收件人地址 wayBill.setRecAddress(row.getCell(9).getStringCellValue()); list.add(wayBill); } // 6 保存至数据库 wayBillService.saveWayBillAll(list); }catch (Exception e){ e.printStackTrace(); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } return new ResponseEntity<>(HttpStatus.OK); } public CellStyle bigTitleStyle(Workbook wb){ // 创建格式 CellStyle cellStyle = wb.createCellStyle(); // 水平对齐方式 cellStyle.setAlignment(CellStyle.ALIGN_CENTER); // 垂直居中 cellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER); // 设置字体 Font font = wb.createFont(); // 是数值的1/20 大小 font.setFontHeight((short) 480); font.setBold(true); font.setColor(Font.COLOR_RED); cellStyle.setFont(font); return cellStyle; } public CellStyle titleStyle(Workbook wb){ CellStyle cellStyle = wb.createCellStyle(); cellStyle.setBorderTop(CellStyle.BORDER_THIN); cellStyle.setBorderRight(CellStyle.BORDER_THIN); cellStyle.setBorderBottom(CellStyle.BORDER_THIN); cellStyle.setBorderLeft(CellStyle.BORDER_THIN); Font font = wb.createFont(); font.setFontHeight((short)300); cellStyle.setFont(font); return cellStyle; } 
原文链接:https://yq.aliyun.com/articles/658478
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章