将从数据库中查的数据导成Excel表格上传OSS或者保存到本地
List<LinkedHashMap<Object, Object>> list = testService.test(); //字段对应列名 HashMap<String, String> columnMap = new HashMap<>(); columnMap.put("aname","a名字"); columnMap.put("asex","a性别"); columnMap.put("bname","b名字"); columnMap.put("bsex","b性别"); columnMap.put("baddress","b地址"); //创建一个工作簿 XSSFWorkbook workbook = new XSSFWorkbook(); //创建一个sheet Sheet sheet = workbook.createSheet("测试表"); //创建单元格样式 CellStyle style = workbook.createCellStyle(); style.setAlignment(HorizontalAlignment.CENTER); //文字水平居中 style.setVerticalAlignment(VerticalAlignment.CENTER);//文字垂直居中 style.setBorderBottom(BorderStyle.THIN); //底边框加黑 style.setBorderLeft(BorderStyle.THIN); //左边框加黑 style.setBorderRight(BorderStyle.THIN); // 有边框加黑 style.setBorderTop(BorderStyle.THIN); //上边框加黑 XSSFFont font = workbook.createFont(); //创建一行填充表名title Row headRow = sheet.createRow(0); headRow.createCell(0).setCellStyle(style); // //创建行和列用于填充数据 for(int i=1;i<=list.size()+1;i++){ Row row = sheet.createRow(i); for(int j=0;j<list.get(1).size();j++){ row.createCell(j).setCellStyle(style); } } //合并第一行的单元格 sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, (list.get(1).size())-1)); //填充数据 headRow.getCell(0).setCellValue("test表名"); for(int i=1;i<=list.size()+1;i++){ Row row = sheet.getRow(i); //i=1,第二行,根据遍历map中的key拿到columnMap中的value填充到第二行的单元格中 if(i==1){ Iterator<Object> keyIt = list.get(0).keySet().iterator(); int count = 0; while (keyIt.hasNext()){ row.getCell(count).setCellValue(columnMap.get(keyIt.next())); count++; } continue; } Map<Object, Object> map = list.get(i-2); Iterator<Object> it = map.keySet().iterator(); int num=0; while (it.hasNext()){ Object key = it.next(); row.getCell(num).setCellValue(map.get(key).toString()); num++; } }
try { //FileOutputStream fos = new FileOutputStream("f:/git/test.xlsx"); //保存到本地 //workbook.write(fos); //fos.close(); ByteArrayOutputStream ba= new ByteArrayOutputStream(); workbook.write(ba); ba.flush(); ba.close(); FileVo fvo = new FileVo(); fvo.setFileName("test10.xlsx"); fvo.setBt(ba.toByteArray()); workbook.close(); //将字节数组转换成输入流 ByteArrayInputStream bio = new ByteArrayInputStream(fvo.getBt()); String fileName = fvo.getFileName(); OSSClient client = new OSSClient("地址", "key", "秘钥"); PutObjectResult result = client.putObject(new PutObjectRequest("oss文件夹名字", fileName, bio)); if(result!=null){ System.out.println("成功"); } }catch (Exception e){ }
原文作者:后来v
原文地址: https://blog.csdn.net/weixin_42437243/article/details/86583852
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
原文地址: https://blog.csdn.net/weixin_42437243/article/details/86583852
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
相关文章