Search in sources :

Example 71 with CSVPrinter

use of org.apache.commons.csv.CSVPrinter 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);
    CSVFormat reqCSVFormat = null;
    if (delimiterParam != null && !delimiterParam.isEmpty()) {
        reqCSVFormat = CSVFormat.EXCEL.withDelimiter(delimiterParam.charAt(0)).withQuote('"').withRecordSeparator("\n").withFirstRecordAsHeader();
    }
    // 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, reqCSVFormat != null ? reqCSVFormat : getCsvFormat());
        csv.printRecord(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) 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) CSVFormat(org.apache.commons.csv.CSVFormat) Row(org.apache.poi.ss.usermodel.Row) CellStyle(org.apache.poi.ss.usermodel.CellStyle) Sheet(org.apache.poi.ss.usermodel.Sheet)

Aggregations

CSVPrinter (org.apache.commons.csv.CSVPrinter)71 IOException (java.io.IOException)25 CSVFormat (org.apache.commons.csv.CSVFormat)20 OutputStreamWriter (java.io.OutputStreamWriter)17 StringWriter (java.io.StringWriter)14 Writer (java.io.Writer)13 ArrayList (java.util.ArrayList)12 FileOutputStream (java.io.FileOutputStream)11 Test (org.junit.Test)11 FileWriter (java.io.FileWriter)8 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)8 BufferedWriter (java.io.BufferedWriter)6 File (java.io.File)5 PrintWriter (java.io.PrintWriter)5 JSONArray (org.json.JSONArray)5 Map (java.util.Map)4 Word (ai.elimu.model.content.Word)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 Letter (ai.elimu.model.content.Letter)2 LetterSoundCorrespondence (ai.elimu.model.content.LetterSoundCorrespondence)2