org.swiftboot.sheet.exp.CsvExporter Maven / Gradle / Ivy
package org.swiftboot.sheet.exp;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringTokenizer;
import org.swiftboot.sheet.meta.*;
import org.swiftboot.util.IoUtils;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
/**
* Export data into a new or a templated CSV file.
* Note:
* multiple sheets and pictures export are not supported,
* if pictures provides, it will be ignored.
* if multiple sheet id provides, all items for these sheet ids will be exported to one CSV file.
*
* @author swiftech
*/
public class CsvExporter extends BaseExporter {
public CsvExporter(String fileType) {
super(fileType);
}
@Override
public void export(Object dataObject, OutputStream outputStream) throws IOException {
this.export(null, dataObject, outputStream);
}
@Override
public void export(InputStream templateFileStream, Object dataObject, OutputStream outputStream) throws IOException {
SheetMetaBuilder builder = new SheetMetaBuilder();
SheetMeta meta = builder.fromAnnotatedObject(dataObject).build();
this.export(templateFileStream, meta, outputStream);
}
@Override
public void export(SheetMeta exportMeta, OutputStream outputStream) throws IOException {
this.export(null, exportMeta, outputStream);
}
@Override
public void export(InputStream templateFileStream, SheetMeta exportMeta, OutputStream outputStream) throws IOException {
List rows;
if (templateFileStream == null) {
rows = new ArrayList<>();
}
else {
rows = IoUtils.readToStringList(templateFileStream);
}
this.extendSheet(rows, exportMeta.findMaxPosition());
exportMeta.setAllowFreeSize(true);
exportMeta.accept((metaItem, startPos, rowCount, columnCount) -> {
if (metaItem.getValue() == null) {
throw new RuntimeException(String.format("No value provided to export for key: %s", metaItem.getKey()));
}
if (metaItem.getValue() instanceof PictureLoader) {
log.warn("Picture is not supported to export to CSV, just ignore ");
}
else {
List> matrix = asMatrix(metaItem.getValue(), rowCount, columnCount);
if (matrix.isEmpty()){
return;
}
int actualRowCount = rowCount == null ? matrix.size() : Math.min(rowCount, matrix.size());
int actualColumnCount = columnCount == null ? matrix.get(0).size() : Math.min(columnCount, matrix.get(0).size());
for (int i = 0; i < actualRowCount; i++) {
List
© 2015 - 2024 Weber Informatics LLC | Privacy Policy