將從數據庫中查的數據導成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){

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章