Search in sources :

Example 1 with CSVStrategy

use of org.apache.commons.csv.CSVStrategy in project portfolio by buchen.

the class PerformanceIndex method exportTo.

private void exportTo(File file, Predicate<Integer> filter) throws IOException {
    CSVStrategy strategy = new CSVStrategy(';', '"', CSVStrategy.COMMENTS_DISABLED, CSVStrategy.ESCAPE_DISABLED, false, false, false, false);
    try (Writer writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)) {
        CSVPrinter printer = new CSVPrinter(writer);
        printer.setStrategy(strategy);
        printer.println(new String[] { // 
        Messages.CSVColumn_Date, // 
        Messages.CSVColumn_Value, // 
        Messages.CSVColumn_InboundTransferals, // 
        Messages.CSVColumn_OutboundTransferals, // 
        Messages.CSVColumn_DeltaInPercent, Messages.CSVColumn_CumulatedPerformanceInPercent });
        for (int ii = 0; ii < totals.length; ii++) {
            if (!filter.test(ii))
                continue;
            printer.print(dates[ii].toString());
            printer.print(Values.Amount.format(totals[ii]));
            printer.print(Values.Amount.format(inboundTransferals[ii]));
            printer.print(Values.Amount.format(outboundTransferals[ii]));
            printer.print(Values.Percent.format(delta[ii]));
            printer.print(Values.Percent.format(accumulated[ii]));
            printer.println();
        }
    }
}
Also used : CSVPrinter(org.apache.commons.csv.CSVPrinter) FileOutputStream(java.io.FileOutputStream) CSVStrategy(org.apache.commons.csv.CSVStrategy) OutputStreamWriter(java.io.OutputStreamWriter) OutputStreamWriter(java.io.OutputStreamWriter) Writer(java.io.Writer)

Example 2 with CSVStrategy

use of org.apache.commons.csv.CSVStrategy in project alfresco-remote-api by Alfresco.

the class DeclarativeSpreadsheetWebScript method generateSpreadsheet.

/**
 * Generates the spreadsheet, based on the properties in the header
 *  and a callback for the body.
 */
public void generateSpreadsheet(Object resource, String format, WebScriptRequest req, Status status, Map<String, Object> model) throws IOException {
    Pattern qnameMunger = Pattern.compile("([A-Z][a-z]+)([A-Z].*)");
    String delimiterParam = req.getParameter(PARAM_REQ_DELIMITER);
    CSVStrategy reqCSVstrategy = null;
    if (delimiterParam != null && !delimiterParam.isEmpty()) {
        reqCSVstrategy = new CSVStrategy(delimiterParam.charAt(0), '"', CSVStrategy.COMMENTS_DISABLED);
    }
    // Build up the details of the header
    List<Pair<QName, Boolean>> propertyDetails = buildPropertiesForHeader(resource, format, req);
    String[] headings = new String[propertyDetails.size()];
    String[] descriptions = new String[propertyDetails.size()];
    boolean[] required = new boolean[propertyDetails.size()];
    for (int i = 0; i < headings.length; i++) {
        Pair<QName, Boolean> property = propertyDetails.get(i);
        if (property == null || property.getFirst() == null) {
            headings[i] = "";
            required[i] = false;
        } else {
            QName column = property.getFirst();
            required[i] = property.getSecond();
            // Ask the dictionary service nicely for the details
            PropertyDefinition pd = dictionaryService.getProperty(column);
            if (pd != null && pd.getTitle(dictionaryService) != null) {
                // Use the friendly titles, which may even be localised!
                headings[i] = pd.getTitle(dictionaryService);
                descriptions[i] = pd.getDescription(dictionaryService);
            } else {
                // Nothing friendly found, try to munge the raw qname into
                // something we can show to a user...
                String raw = column.getLocalName();
                raw = raw.substring(0, 1).toUpperCase() + raw.substring(1);
                Matcher m = qnameMunger.matcher(raw);
                if (m.matches()) {
                    headings[i] = m.group(1) + " " + m.group(2);
                } else {
                    headings[i] = raw;
                }
            }
        }
    }
    // Build a list of just the properties
    List<QName> properties = new ArrayList<QName>(propertyDetails.size());
    for (Pair<QName, Boolean> p : propertyDetails) {
        QName qn = null;
        if (p != null) {
            qn = p.getFirst();
        }
        properties.add(qn);
    }
    // Output
    if ("csv".equals(format)) {
        StringWriter sw = new StringWriter();
        CSVPrinter csv = new CSVPrinter(sw, reqCSVstrategy != null ? reqCSVstrategy : getCsvStrategy());
        csv.println(headings);
        populateBody(resource, csv, properties);
        model.put(MODEL_CSV, sw.toString());
    } else {
        Workbook wb;
        if ("xlsx".equals(format)) {
            wb = new XSSFWorkbook();
        // TODO Properties
        } else {
            wb = new HSSFWorkbook();
        // TODO Properties
        }
        // Add our header row
        Sheet sheet = wb.createSheet("Export");
        Row hr = sheet.createRow(0);
        sheet.createFreezePane(0, 1);
        Font fb = wb.createFont();
        fb.setBold(true);
        Font fi = wb.createFont();
        fi.setBold(true);
        fi.setItalic(true);
        CellStyle csReq = wb.createCellStyle();
        csReq.setFont(fb);
        CellStyle csOpt = wb.createCellStyle();
        csOpt.setFont(fi);
        // Populate the header
        Drawing draw = null;
        for (int i = 0; i < headings.length; i++) {
            Cell c = hr.createCell(i);
            c.setCellValue(headings[i]);
            if (required[i]) {
                c.setCellStyle(csReq);
            } else {
                c.setCellStyle(csOpt);
            }
            if (headings[i].length() == 0) {
                sheet.setColumnWidth(i, 3 * 250);
            } else {
                sheet.setColumnWidth(i, 18 * 250);
            }
            if (descriptions[i] != null && descriptions[i].length() > 0) {
                // Add a description for it too
                if (draw == null) {
                    draw = sheet.createDrawingPatriarch();
                }
                ClientAnchor ca = wb.getCreationHelper().createClientAnchor();
                ca.setCol1(c.getColumnIndex());
                ca.setCol2(c.getColumnIndex() + 1);
                ca.setRow1(hr.getRowNum());
                ca.setRow2(hr.getRowNum() + 2);
                Comment cmt = draw.createCellComment(ca);
                cmt.setAuthor("");
                cmt.setString(wb.getCreationHelper().createRichTextString(descriptions[i]));
                cmt.setVisible(false);
                c.setCellComment(cmt);
            }
        }
        // Have the contents populated
        populateBody(resource, wb, sheet, properties);
        // Save it for the template
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        wb.write(baos);
        model.put(MODEL_EXCEL, baos.toByteArray());
    }
}
Also used : Drawing(org.apache.poi.ss.usermodel.Drawing) Matcher(java.util.regex.Matcher) ArrayList(java.util.ArrayList) Font(org.apache.poi.ss.usermodel.Font) CSVPrinter(org.apache.commons.csv.CSVPrinter) StringWriter(java.io.StringWriter) ClientAnchor(org.apache.poi.ss.usermodel.ClientAnchor) XSSFWorkbook(org.apache.poi.xssf.usermodel.XSSFWorkbook) Cell(org.apache.poi.ss.usermodel.Cell) Pair(org.alfresco.util.Pair) Pattern(java.util.regex.Pattern) Comment(org.apache.poi.ss.usermodel.Comment) QName(org.alfresco.service.namespace.QName) CSVStrategy(org.apache.commons.csv.CSVStrategy) ByteArrayOutputStream(java.io.ByteArrayOutputStream) PropertyDefinition(org.alfresco.service.cmr.dictionary.PropertyDefinition) XSSFWorkbook(org.apache.poi.xssf.usermodel.XSSFWorkbook) Workbook(org.apache.poi.ss.usermodel.Workbook) HSSFWorkbook(org.apache.poi.hssf.usermodel.HSSFWorkbook) HSSFWorkbook(org.apache.poi.hssf.usermodel.HSSFWorkbook) Row(org.apache.poi.ss.usermodel.Row) CellStyle(org.apache.poi.ss.usermodel.CellStyle) Sheet(org.apache.poi.ss.usermodel.Sheet)

Example 3 with CSVStrategy

use of org.apache.commons.csv.CSVStrategy in project portfolio by buchen.

the class CSVImporter method processFile.

public void processFile() throws IOException {
    try (FileInputStream stream = new FileInputStream(inputFile)) {
        Reader reader = new InputStreamReader(stream, encoding);
        CSVStrategy strategy = new CSVStrategy(delimiter, '"', CSVStrategy.COMMENTS_DISABLED, CSVStrategy.ESCAPE_DISABLED, false, false, false, false);
        CSVParser parser = new CSVParser(reader, strategy);
        for (int ii = 0; ii < skipLines; ii++) parser.getLine();
        List<String[]> input = new ArrayList<>();
        String[] header = null;
        String[] line = parser.getLine();
        if (isFirstLineHeader) {
            header = line;
        } else {
            header = new String[line.length];
            for (int ii = 0; ii < header.length; ii++) header[ii] = MessageFormat.format(Messages.CSVImportGenericColumnLabel, ii + 1);
            input.add(line);
        }
        while ((line = parser.getLine()) != null) input.add(line);
        this.columns = new CSVImporter.Column[header.length];
        for (int ii = 0; ii < header.length; ii++) this.columns[ii] = new Column(ii, header[ii]);
        this.values = input;
        mapToImportDefinition();
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) CSVParser(org.apache.commons.csv.CSVParser) CSVStrategy(org.apache.commons.csv.CSVStrategy) ArrayList(java.util.ArrayList) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) FileInputStream(java.io.FileInputStream)

Aggregations

CSVStrategy (org.apache.commons.csv.CSVStrategy)3 ArrayList (java.util.ArrayList)2 CSVPrinter (org.apache.commons.csv.CSVPrinter)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 FileInputStream (java.io.FileInputStream)1 FileOutputStream (java.io.FileOutputStream)1 InputStreamReader (java.io.InputStreamReader)1 OutputStreamWriter (java.io.OutputStreamWriter)1 Reader (java.io.Reader)1 StringWriter (java.io.StringWriter)1 Writer (java.io.Writer)1 Matcher (java.util.regex.Matcher)1 Pattern (java.util.regex.Pattern)1 PropertyDefinition (org.alfresco.service.cmr.dictionary.PropertyDefinition)1 QName (org.alfresco.service.namespace.QName)1 Pair (org.alfresco.util.Pair)1 CSVParser (org.apache.commons.csv.CSVParser)1 HSSFWorkbook (org.apache.poi.hssf.usermodel.HSSFWorkbook)1 Cell (org.apache.poi.ss.usermodel.Cell)1 CellStyle (org.apache.poi.ss.usermodel.CellStyle)1