org.dbunit.dataset.excel.XlsDataSetWriterCustom Maven / Gradle / Ivy
package org.dbunit.dataset.excel;
import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Date;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.dbunit.dataset.Column;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.ITable;
import org.dbunit.dataset.ITableIterator;
import org.dbunit.dataset.ITableMetaData;
import org.dbunit.dataset.datatype.DataType;
import org.springframework.util.ReflectionUtils;
public class XlsDataSetWriterCustom extends org.dbunit.dataset.excel.XlsDataSetWriter {
public void write(IDataSet dataSet, Workbook workbook) throws IOException, DataSetException {
CellStyle dateCellStyle = createDateCellStyle(workbook);
Field field = ReflectionUtils.findField(getClass(), "dateCellStyle");
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(field, this, dateCellStyle);
// if (dateCellStyle != null && !dateCellStyle.equals(ReflectionUtils.getField(field, this))) {
// ReflectionUtils.setField(field, this, dateCellStyle);
// }
int index = 0;
ITableIterator iterator = dataSet.iterator();
while (iterator.next()) {
// create the table i.e. sheet
ITable table = iterator.getTable();
ITableMetaData metaData = table.getTableMetaData();
Sheet sheet = workbook.createSheet(metaData.getTableName());
// write table metadata i.e. first row in sheet
workbook.setSheetName(index, metaData.getTableName());
Row headerRow = sheet.createRow(0);
Column[] columns = metaData.getColumns();
for (int j = 0; j < columns.length; j++) {
Column column = columns[j];
Cell cell = headerRow.createCell(j);
cell.setCellValue(column.getColumnName());
}
// write table data
for (int j = 0; j < table.getRowCount(); j++) {
Row row = sheet.createRow(j + 1);
for (int k = 0; k < columns.length; k++) {
Column column = columns[k];
Object value = table.getValue(j, column.getColumnName());
if (value != null) {
Cell cell = row.createCell(k);
if (value instanceof Date) {
setDateCell(cell, (Date) value, workbook);
}
else if (value instanceof BigDecimal) {
setNumericCell(cell, (BigDecimal) value, workbook);
}
else if (value instanceof Long) {
setDateCell(cell, new Date(((Long) value).longValue()), workbook);
}
else {
cell.setCellValue(DataType.asString(value));
}
}
}
}
index++;
}
}
}