com.formkiq.server.service.ExportServiceImpl Maven / Gradle / Ivy
/*
* Copyright (C) 2016 FormKiQ Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.formkiq.server.service;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.formkiq.server.service.dto.FormJSON;
import com.formkiq.server.service.dto.FormJSONField;
import com.formkiq.server.service.dto.FormJSONSection;
/**
* Implementation of Export Service.
*
*/
@Service
public class ExportServiceImpl implements ExportService {
@Override
public void writeToXLS(final FormJSON form, final OutputStream os)
throws IOException {
Workbook wb = new HSSFWorkbook();
try {
writeToExcel(os, form, wb);
} finally {
wb.close();
}
}
@Override
public void writeToXLSX(final FormJSON form, final OutputStream os)
throws IOException {
Workbook wb = new XSSFWorkbook();
try {
writeToExcel(os, form, wb);
} finally {
wb.close();
}
}
/**
* Writes to Excel.
* @param os OutputStream
* @param form FormJSON
* @param wb Workbook
* @throws IOException IOException
*/
private void writeToExcel(final OutputStream os, final FormJSON form,
final Workbook wb) throws IOException {
int count = 1;
for (FormJSONSection section : form.getSections()) {
String title = getSectionTitle(section, count);
Sheet sheet = wb.createSheet(title);
// header row
Row headerRow = sheet.createRow(0);
int column = 0;
for (FormJSONField field : section.getFields()) {
Cell cell = headerRow.createCell(column);
cell.setCellValue(field.getLabel());
column++;
}
column = 0;
Row dataRow = sheet.createRow(1);
for (FormJSONField field : section.getFields()) {
Cell cell = dataRow.createCell(column);
cell.setCellValue(field.getValue());
column++;
}
count++;
}
wb.write(os);
}
/**
* Gets Section Title.
* @param section FormJSONSection
* @param count int
* @return {@link String}
*/
private String getSectionTitle(final FormJSONSection section,
final int count) {
String title = !StringUtils.isEmpty(section.getTitle()) ? section
.getTitle() : "sheet " + count;
return title;
}
}