将从数据库中查的数据导成Excel表格上传OSS或者保存到本地

List> list = testService.test();
//字段对应列名
HashMap 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 keyIt = list.get(0).keySet().iterator();
        int count = 0;
        while (keyIt.hasNext()){
            row.getCell(count).setCellValue(columnMap.get(keyIt.next()));
            count++;
        }
        continue;
    }
    Map map = list.get(i-2);
    Iterator 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){

}

你可能感兴趣的:(java)