Advertisement
Guest User

Untitled

a guest
Jun 18th, 2018
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.17 KB | None | 0 0
  1. public static void write(PreparedExcelData preparedExcelData) {
  2.         File file = new File(preparedExcelData.getFileName());
  3.         String sheetName = preparedExcelData.getSheetName();
  4.  
  5.         try (Workbook book = new XSSFWorkbook(); ByteArrayOutputStream bos = new ByteArrayOutputStream()){
  6.             Sheet sheet = book.createSheet(sheetName);
  7.             Row titleRow = sheet.createRow(0);
  8.  
  9.             RowContext headers = preparedExcelData.getHeader().getData();
  10.  
  11.             if(headers.getRowStyle() != null){
  12.                 titleRow.setRowStyle(headers.getRowStyle());
  13.             }
  14.  
  15.             for (int i = 0; i < headers.size(); i++) {
  16.                 Cell nameColumn = titleRow.createCell(i);
  17.                 CellContext cellContext = headers.getCell(i);
  18.  
  19.                 if(cellContext.getCellStyle() != null){
  20.                     nameColumn.setCellStyle(cellContext.getCellStyle());
  21.                 }
  22.  
  23.                 nameColumn.setCellValue(cellContext.getValue());
  24.             }
  25.  
  26.             List<RowContext> data = preparedExcelData.getBody().getData();
  27.  
  28.             for (int i = 0; i < data.size(); i++) {
  29.                 Row row = sheet.createRow(i + 1);
  30.                 RowContext rowContext = data.get(i);
  31.  
  32.                 if(rowContext.size() != headers.size()){
  33.                     throw new IllegalArgumentException("Body size don't equals with header size");
  34.                 }
  35.  
  36.                 if(rowContext.getRowStyle() != null){
  37.                     row.setRowStyle(rowContext.getRowStyle());
  38.                 }
  39.  
  40.                 for (int j = 0; j < headers.size(); j++){
  41.                     Cell cell = row.createCell(j);
  42.                     CellContext cellContext = rowContext.getCell(j);
  43.  
  44.                     if(cellContext.getCellStyle() != null){
  45.                         cell.setCellStyle(cellContext.getCellStyle());
  46.                     }
  47.  
  48.                     cell.setCellValue(cellContext.getValue());
  49.                 }
  50.             }
  51.            
  52.             book.write(bos);
  53.  
  54.             FileUtils.writeByteArrayToFile(file, bos.toByteArray());
  55.         } catch (IOException e) {
  56.             e.printStackTrace();
  57.         }
  58.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement