리스트에 담긴 요소 수 만큼 엑셀파일을 만들고, 이미지 불러오기와 같은 기능을 활용하기 위해 JXL이 아닌 POI를 활용하여 엑셀을 다뤘습니다.
// 임시파일 생성
File tmpZip = File.createTempFile("tmp_", ".zip");
OutputStream os = new FileOutputStream(tmpZip);
// 엑셀 파일 압축 OutputStream
ArchiveOutputStream zos = new 1ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.ZIP, os);
// 품목별 엑셀파일 생성
for (String skuCd : skuCdList) {
// POI 시작
Workbook workbook = new XSSFWorkbook();
// 시트 생성
Sheet sheet = workbook.createSheet("Sku Info")
// 셀 라인 제거
sheet.setDisplayGridlines(false);
// 빈 로우를 생성하지 않으면 업로드시 읽지 못해 빈로우 생성
for (int i = 0; i < 100; i++) {
Row emptyRow = sheet.createRow(i);
Cell emptyCell = emptyRow.createCell(0);
emptyCell.setCellValue("");
}
// 이미지 삽입
Resource resource = new ClassPathResource("image/logo.png");
InputStream is = resource.getInputStream();
byte[] bytes = IOUtils.toByteArray(is);
int picIdx = workbook.addPicture(bytes, XSSFWorkbook.PICTURE_TYPE_PNG);
is.close();
CreationHelper helper = workbook.getCreationHelper();
Drawing drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = helper.createClientAnchor();
anchor.setCol1(8);
anchor.setRow1(1);
Picture pic = drawing.createPicture(anchor, picIdx);
pic.resize(1, 2);
// 폰트 설정
Font font = workbook.createFont();
font.setFontHeightInPoints((short) 22);
font.setFontName("Malgun Gothic);
// 셀 스타일 설정
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFont(font);
cellStyle.setAlignment(HorizantalAliugnment.CENTER);
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
cellStyle.setBorderBottom(BorderStyle.THIN);
cellStyle.setBorderTop(BorderStyle.THIN);
cellStyle.setBorderRight(BorderStyle.THIN);
cellStyle.setBorderLeft(BorderStyle.THIN);
// 셀에 입력
Row headerRow = sheet.createRow(3);
headerRow.setHeight((short) 675);
Cell cell = headerRow.createCell(7);
cell.setCellValue("품목별 납품 계약서");
cell.setCellStyle(cellStyle);
sheet.addMergedRegion(new CellRangeAddress(3, 3, 7, 9)); //셀 병합
// 글씨에 일부분만 다른 글씨색 적용
headerRow = sheet.createRow(4);
headerRow.setHeight((short) 345);
cell = headerRow.createCell(1);
String contents = "일부분에만 다른 글씨를 적용하고 싶어요.";
XSSFRichTextString rich = new XSSFRichTextString(contents);
rich.applyFont(8, 10, redFont);
rich.applyFont(11, 20, font);
cell.setCellValue(rich);
cell.setCellStyle(contLeftCellStyle);
...
}
// 압축 종료
zos.finish();
// 압축 파일 생성
FileInputStream fis = new FileInputStream(tmpZip);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int readcount = 0;
while((readcount = fis.read(buffer)) != -1) {
bos.write(buffer, 0, readcount);
}
// 임시파일 삭제
tmpZip.deleteOnExit();
fis.close();
bos.close();
return bos;