Example usage for org.apache.poi.hssf.usermodel HSSFSheet getColumnWidth

List of usage examples for org.apache.poi.hssf.usermodel HSSFSheet getColumnWidth

Introduction

In this page you can find the example usage for org.apache.poi.hssf.usermodel HSSFSheet getColumnWidth.

Prototype

@Override
public int getColumnWidth(int columnIndex) 

Source Link

Document

get the width (in units of 1/256th of a character width )

Usage

From source file:at.spardat.xma.mdl.grid.GridPOIAdapter.java

License:Open Source License

/**
 * Transfers the spreadsheet data from the POI <code>HSSFWorkbook</code> into the <code>IGridWMServer</code>.
 * Only the sheet on the given sheetIndex is copied.
        /*ww  w . j av  a2s .c o m*/
 * @param igrid the XMA model where to copy the data
 * @param book the POI represntation of the data
 * @param sheetIndex the index of the sheet to copy
 * @return a list containing all SysExceptions describing problems with individual cell formulas or ranges
 */
public static List poi2xma(IGridWM igrid, HSSFWorkbook book, int sheetIndex) {
    GridWM grid = (GridWM) igrid;
    try {
        List errorList = new ArrayList();
        grid.setSheetName(book.getSheetName(sheetIndex));

        grid.colors.clear();
        grid.initBuildInColors();
        short ic = GridWM.HSSF_FIRST_COLOR_INDEX;
        HSSFPalette palette = book.getCustomPalette();
        for (HSSFColor color = palette.getColor(ic); ic < 64 && color != null; color = palette.getColor(++ic)) {
            grid.colors.add(ic, new GridColor(color.getTriplet()));
        }

        grid.fonts.clear();
        int numFonts = book.getNumberOfFonts();
        if (numFonts > 4) {
            // adjust for "There is no 4" see code of org.apache.poi.hssf.model.Workbook.getFontRecordAt()
            numFonts += 1;
        }
        for (short i = 0; i < numFonts; i++) {
            HSSFFont font = book.getFontAt(i);
            byte fontstyle = GridFont.FONT_NORML;
            if (font.getBoldweight() >= HSSFFont.BOLDWEIGHT_BOLD)
                fontstyle |= GridFont.FONT_BOLD;
            if (font.getItalic())
                fontstyle |= GridFont.FONT_ITALIC;
            grid.fonts.add(i, new GridFont(font.getFontName(), fontstyle, font.getColor()));
        }

        grid.styles.clear();
        for (short i = 0, numStyles = book.getNumCellStyles(); i < numStyles; i++) {
            HSSFCellStyle style = book.getCellStyleAt(i);
            grid.styles.add(i, new GridCellStyle(style.getFontIndex(), style.getFillForegroundColor()));
        }

        grid.namedRanges.clear();
        for (int i = 0, numRanges = book.getNumberOfNames(); i < numRanges; i++) {
            HSSFName name = book.getNameAt(i);
            String rangeName = name.getNameName();
            String rangeRef = null;
            try { // ranges not defined but referenced by formulas have a name but no reference in HSSF
                rangeRef = name.getReference();
            } catch (Exception exc) {
                errorList.add(new SysException(exc, ((GridWM) grid).getMessage("inconsistentRange", rangeName))
                        .setCode(GridWM.CODE_inconsistentRange));
            }
            if (rangeRef != null) {
                try {
                    GridRange range = grid.getJeksDelegate().toRange(rangeRef);
                    range.setKey(rangeName);
                    grid.namedRanges.put(rangeName, range);
                } catch (Exception exc) {
                    errorList.add(new SysException(exc,
                            ((GridWM) grid).getMessage("unsupportedReference", rangeName, rangeRef))
                                    .setCode(GridWM.CODE_unsupportedReference));
                }
            }
        }

        grid.rows.clear();
        grid.cols.clear();
        grid.cells.clear();
        grid.delegate = new GridJeksDelegate(grid);
        HSSFSheet sheet = book.getSheetAt(sheetIndex);
        int firstColNum = Integer.MAX_VALUE;
        int lastColNum = Integer.MIN_VALUE;
        for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
            HSSFRow row = sheet.getRow(i);
            if (row == null)
                continue;
            if (row.getFirstCellNum() >= 0)
                firstColNum = Math.min(firstColNum, row.getFirstCellNum());
            lastColNum = Math.max(lastColNum, row.getLastCellNum());
            if (lastColNum > 255)
                lastColNum = 255;
            for (short j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
                HSSFCell hssfcell = row.getCell(j);
                if (hssfcell == null)
                    continue;
                GridCell gridcell = grid.getOrCreateCell(i, j);
                switch (hssfcell.getCellType()) {
                case HSSFCell.CELL_TYPE_BLANK:
                    break;
                case HSSFCell.CELL_TYPE_BOOLEAN:
                    gridcell.setValue(hssfcell.getBooleanCellValue());
                    break;
                case HSSFCell.CELL_TYPE_ERROR:
                    // TODO: recherche error text
                    byte errorCode = hssfcell.getErrorCellValue();
                    //                    gridcell.setValue(errorCode);
                    gridcell.setValue("#ERROR");
                    errorList.add(new SysException(((GridWM) grid).getMessage("errorRecord",
                            grid.getJeksDelegate().toExcelRef(i, j), Byte.toString(errorCode)))
                                    .setCode(GridWM.CODE_errorRecord));
                    break;
                case HSSFCell.CELL_TYPE_FORMULA:
                    String formula = null;
                    try {
                        formula = hssfcell.getCellFormula();
                        gridcell.setFormula(formula);
                    } catch (SysException e) {
                        if (formula != null)
                            gridcell.setValue("=" + formula); //set it as text without interpretation
                        errorList.add(e);
                    }
                    break;
                case HSSFCell.CELL_TYPE_NUMERIC:
                    if (isDateCell(book, hssfcell)) {
                        gridcell.setValue(hssfcell.getDateCellValue());
                    } else {
                        gridcell.setValue(hssfcell.getNumericCellValue());
                    }
                    break;
                case HSSFCell.CELL_TYPE_STRING:
                    gridcell.setValue(hssfcell.getStringCellValue());
                    break;
                default:
                    throw new SysException("unknown cell type " + hssfcell.getCellType());
                }
                gridcell.setEditable(!hssfcell.getCellStyle().getLocked());
                gridcell.setStyle(hssfcell.getCellStyle().getIndex());
            }
        }

        final int scalefactor = 256 / 7; // empirically testet
        //        int width = sheet.getDefaultColumnWidth();  // returns nonsense
        //        width = width/scalefactor;
        //        grid.setDefaultColumnWidth(width);
        for (short i = (short) firstColNum; i <= lastColNum; i++) {
            int width = sheet.getColumnWidth(i);
            width = width / scalefactor;
            grid.getOrCreateColumn(i).setWidth(width);
        }

        if (firstColNum == Integer.MAX_VALUE)
            firstColNum = 0;
        if (lastColNum == Integer.MIN_VALUE)
            lastColNum = 0;
        grid.setMaxRange(
                new GridRange(grid, sheet.getFirstRowNum(), firstColNum, sheet.getLastRowNum(), lastColNum));
        grid.setVisibleRange(grid.getMaxRange());
        return errorList;
    } finally {
        grid.handle(grid.new GridReloadEvent());
    }
}

From source file:com.cms.utils.ExcelReader.java

public static void copySheets(HSSFSheet newSheet, HSSFSheet sheet, boolean copyStyle) {
    int maxColumnNum = 0;
    Map<Integer, HSSFCellStyle> styleMap = (copyStyle) ? new HashMap<Integer, HSSFCellStyle>() : null;
    for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
        HSSFRow srcRow = sheet.getRow(i);
        HSSFRow destRow = newSheet.createRow(i);
        if (srcRow != null) {
            copyRow(sheet, newSheet, srcRow, destRow, styleMap);
            if (srcRow.getLastCellNum() > maxColumnNum) {
                maxColumnNum = srcRow.getLastCellNum();
            }//from   w  w w . j av  a  2s . c  om
        }
    }
    for (int i = 0; i <= maxColumnNum; i++) {
        newSheet.setColumnWidth(i, sheet.getColumnWidth(i));
    }
}

From source file:com.eryansky.core.excelTools.ExcelUtils.java

License:Apache License

public static void copySheetStyle(HSSFWorkbook destwb, HSSFSheet dest, HSSFWorkbook srcwb, HSSFSheet src) {
    if (src == null || dest == null)
        return;// www.j a  va  2  s . c o m

    dest.setAlternativeExpression(src.getAlternateExpression());
    dest.setAlternativeFormula(src.getAlternateFormula());
    dest.setAutobreaks(src.getAutobreaks());
    dest.setDialog(src.getDialog());
    if (src.getColumnBreaks() != null) {
        for (int col : src.getColumnBreaks()) {
            dest.setColumnBreak(col);
        }
    }
    dest.setDefaultColumnWidth(src.getDefaultColumnWidth());
    dest.setDefaultRowHeight(src.getDefaultRowHeight());
    dest.setDefaultRowHeightInPoints(src.getDefaultRowHeightInPoints());
    dest.setDisplayGuts(src.getDisplayGuts());
    dest.setFitToPage(src.getFitToPage());
    dest.setHorizontallyCenter(src.getHorizontallyCenter());
    dest.setDisplayFormulas(src.isDisplayFormulas());
    dest.setDisplayGridlines(src.isDisplayGridlines());
    dest.setDisplayRowColHeadings(src.isDisplayRowColHeadings());
    dest.setGridsPrinted(src.isGridsPrinted());
    dest.setPrintGridlines(src.isPrintGridlines());

    for (int i = 0; i < src.getNumMergedRegions(); i++) {
        CellRangeAddress r = src.getMergedRegion(i);
        dest.addMergedRegion(r);
    }

    if (src.getRowBreaks() != null) {
        for (int row : src.getRowBreaks()) {
            dest.setRowBreak(row);
        }
    }
    dest.setRowSumsBelow(src.getRowSumsBelow());
    dest.setRowSumsRight(src.getRowSumsRight());

    int maxcol = 0;
    for (int i = 0; i <= src.getLastRowNum(); i++) {
        HSSFRow row = src.getRow(i);
        if (row != null) {
            if (maxcol < row.getLastCellNum())
                maxcol = row.getLastCellNum();
        }
    }
    for (int col = 0; col <= maxcol; col++) {
        if (src.getColumnWidth(col) != src.getDefaultColumnWidth())
            dest.setColumnWidth(col, src.getColumnWidth(col));
        dest.setColumnHidden(col, src.isColumnHidden(col));
    }
}

From source file:com.haulmont.yarg.formatters.impl.XLSFormatter.java

License:Apache License

/**
 * Method writes vertical band//from ww w .ja  v a  2 s .  c  om
 * Note: no child support for vertical band ;)
 *
 * @param band          - band to write
 * @param templateSheet - template sheet
 * @param resultSheet   - result sheet
 */
protected void writeVerticalBand(BandData band, HSSFSheet templateSheet, HSSFSheet resultSheet) {
    String rangeName = band.getName();
    CellReference[] crefs = getRangeContent(templateWorkbook, rangeName);

    Set<Integer> addedRowNumbers = new HashSet<Integer>();

    if (crefs != null) {
        addRangeBounds(band, crefs);

        Bounds thisBounds = templateBounds.get(band.getName());
        Bounds parentBounds = templateBounds.get(band.getParentBand().getName());
        Range parentRange = bandsToResultRanges.get(band.getParentBand());

        int localRowNum = parentBounds != null && parentRange != null
                ? parentRange.getFirstRow() - 1 + thisBounds.row0 - parentBounds.row0
                : rownum;

        colnum = colnum == 0 ? getCellFromReference(crefs[0], templateSheet).getColumnIndex() : colnum;
        copyMergeRegions(resultSheet, rangeName, localRowNum, colnum);

        int firstRow = crefs[0].getRow();
        int firstColumn = crefs[0].getCol();

        for (CellReference cref : crefs) {//create necessary rows
            int currentRow = cref.getRow();
            final int rowOffset = currentRow - firstRow;
            if (!rowExists(resultSheet, localRowNum + rowOffset)) {
                HSSFRow resultRow = resultSheet.createRow(localRowNum + rowOffset);
                copyPageBreaks(templateSheet, resultSheet, cref.getRow(), resultRow.getRowNum());
            }
            addedRowNumbers.add(cref.getRow());
        }

        CellReference topLeft = null;
        CellReference bottomRight = null;
        for (CellReference cref : crefs) {
            int currentRow = cref.getRow();
            int currentColumn = cref.getCol();
            final int rowOffset = currentRow - firstRow;
            final int columnOffset = currentColumn - firstColumn;

            HSSFCell templateCell = getCellFromReference(cref, templateSheet);
            resultSheet.setColumnWidth(colnum + columnOffset,
                    templateSheet.getColumnWidth(templateCell.getColumnIndex()));
            HSSFCell resultCell = copyCellFromTemplate(templateCell,
                    resultSheet.getRow(localRowNum + rowOffset), colnum + columnOffset, band);
            if (topLeft == null) {
                topLeft = new CellReference(resultCell);
            }
            bottomRight = new CellReference(resultCell);
        }

        colnum += crefs[crefs.length - 1].getCol() - firstColumn + 1;

        AreaReference templateRange = getAreaForRange(templateWorkbook, rangeName);
        AreaReference resultRange = new AreaReference(topLeft, bottomRight);
        areaDependencyManager.addDependency(new Area(band.getName(), Area.AreaAlign.VERTICAL, templateRange),
                new Area(band.getName(), Area.AreaAlign.VERTICAL, resultRange));
        bandsToResultRanges.put(band,
                new Range(resultSheet.getSheetName(), resultRange.getFirstCell().getCol() + 1,
                        resultRange.getFirstCell().getRow() + 1, resultRange.getLastCell().getCol() + 1,
                        resultRange.getLastCell().getRow() + 1));
    }

    //for first level vertical bands we should increase rownum by number of rows added by vertical band
    //nested vertical bands do not add rows, they use parent space
    if (BandData.ROOT_BAND_NAME.equals(band.getParentBand().getName())) {
        List<BandData> sameBands = band.getParentBand().getChildrenByName(band.getName());
        if (sameBands.size() > 0 && sameBands.get(sameBands.size() - 1) == band) {//check if this vertical band is last vertical band with same name
            rownum += addedRowNumbers.size();
            //      rowsAddedByVerticalBand = 0;
        }
    }
}

From source file:com.krawler.esp.servlets.exportExcel.java

License:Open Source License

public void exportexcel(HttpServletResponse response, JSONObject jobj, java.util.Hashtable ht,
        String sheetTitle, String fileName, JSONArray hdr, JSONArray xlshdr, String heading, String[] xtypeArr,
        com.krawler.spring.exportFunctionality.exportDAOImpl exportDao) throws ServletException, IOException {
    try {//from  w  w w. ja  v  a  2s . c  om
        response.setContentType("application/vnd.ms-excel");
        if (!StringUtil.isNullOrEmpty(heading)) {
            fileName = heading + fileName;
        }
        response.setHeader("Content-Disposition", "attachement; filename=" + fileName + ".xls");
        HSSFSheet sheet = wb.createSheet(sheetTitle);
        CellStyle cs = wb.createCellStyle();
        cs.setWrapText(true);

        HSSFHeader hh = sheet.getHeader();
        int j = 1;
        int width = 0;
        int maxrowno = 0;
        HSSFRow row1 = sheet.createRow((short) maxrowno);
        HashMap hm = extractData(jobj);
        JSONArray jarr = (JSONArray) hm.get("data");
        JSONObject tempObj;
        for (int k = 0; k < jarr.length(); k++) {
            tempObj = jarr.getJSONObject(k);
            HSSFRow row = sheet.createRow((short) j);
            int cellcount = 0;
            for (int i = 0; i < hdr.length(); i++) {
                Object str = tempObj.optString(hdr.getString(i), "");
                try {
                    if (xtypeArr.length > 0) {
                        str = convertValue(tempObj.optString(hdr.getString(i), ""), xtypeArr[i]);
                    }
                } catch (Exception e) {

                }
                if (ht.containsValue(hdr.getString(i))) {
                    if (j == maxrowno + 1) {
                        HSSFCell cell1 = row1.createCell(cellcount);
                        cell1.setCellStyle(cs);

                        width = xlshdr.getString(i).length() * 325;
                        if (width > sheet.getColumnWidth(cellcount)) {
                            sheet.setColumnWidth(cellcount, width);
                        }
                        HSSFFont font = wb.createFont();
                        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
                        HSSFRichTextString hst = new HSSFRichTextString(xlshdr.getString(i));
                        hst.applyFont(font);
                        cell1.setCellValue(hst);

                    }
                    HSSFCell cell = row.createCell(cellcount);
                    cell.setCellStyle(cs);

                    if (str instanceof Date) {
                        cal.setTime((Date) str);
                        cell.setCellValue(cal);
                        cell.setCellStyle(this.dateCellStyle);
                        width = 4500;
                    } else if (str instanceof Number) {
                        cell.setCellValue(((Number) str).doubleValue());
                        width = 4500;
                    } else {
                        String colvalue = str.toString();
                        cell.setCellValue(new HSSFRichTextString(colvalue));
                        width = colvalue.length() * 325;
                    }

                    width = Math.min(width, MAX_CELL_WIDTH);

                    if (width > sheet.getColumnWidth(cellcount)) {
                        sheet.setColumnWidth(cellcount, width);
                    }

                    cellcount++;
                }
            }
            j++;

        }

        ConfigReader cr = ConfigReader.getinstance();
        String dirpath = cr.get("store");
        String path = dirpath + "baitheader.png";

        //                this.addimage(path,HSSFWorkbook.PICTURE_TYPE_PNG, wb, sheet,0,0,0,0,0,0,12,4);
        if (true) {
            OutputStream out = response.getOutputStream();
            wb.write(out);
            out.close();
        }
    } catch (JSONException ex) {
        Logger.getLogger(exportExcel.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(exportExcel.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.siva.javamultithreading.ExcelUtil.java

private static void copySheets(HSSFWorkbook newWorkbook, HSSFSheet newSheet, HSSFSheet sheet,
        boolean copyStyle) {
    int newRownumber = newSheet.getLastRowNum() + 1;
    int maxColumnNum = 0;
    Map<Integer, HSSFCellStyle> styleMap = (copyStyle) ? new HashMap<Integer, HSSFCellStyle>() : null;

    for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
        HSSFRow srcRow = sheet.getRow(i);
        HSSFRow destRow = newSheet.createRow(i + newRownumber);
        if (srcRow != null) {
            copyRow(newWorkbook, sheet, newSheet, srcRow, destRow, styleMap);
            if (srcRow.getLastCellNum() > maxColumnNum) {
                maxColumnNum = srcRow.getLastCellNum();
            }/* www  . j a v a  2  s. c  om*/
        }
    }
    for (int i = 0; i <= maxColumnNum; i++) {
        newSheet.setColumnWidth(i, sheet.getColumnWidth(i));
    }
}

From source file:com.softtek.mdm.web.admin.IndexController.java

private void exportExcel(String sheetName, String[] headNames, List<OrganizationModel> lists,
        HttpServletResponse response) {/*from w w w.j ava  2  s. c o m*/

    OutputStream out = null;
    try {
        HSSFWorkbook workbook = new HSSFWorkbook(); //   
        HSSFSheet sheet = workbook.createSheet(sheetName); //   
        //   
        HSSFRow rowm = sheet.createRow(0);
        HSSFCell cellTiltle = rowm.createCell(0);
        //sheet??getColumnTopStyle()/getStyle()? - ?  - ?  
        HSSFCellStyle columnTopStyle = CommUtil.getColumnTopStyle(workbook);//??  
        sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (headNames.length - 1)));
        cellTiltle.setCellStyle(columnTopStyle);
        cellTiltle.setCellValue(sheetName);
        //   
        int columnNum = headNames.length;
        HSSFRow rowRowName = sheet.createRow(2); // 2?()  
        // sheet?  
        for (int n = 0; n < columnNum; n++) {
            HSSFCell cellRowName = rowRowName.createCell(n); //?  
            cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); //??  
            HSSFRichTextString text = new HSSFRichTextString(headNames[n]);
            cellRowName.setCellValue(text); //?  
            cellRowName.setCellStyle(columnTopStyle); //??  
        }
        //?sheet?  
        HSSFDataFormat format = workbook.createDataFormat();
        short formatDate = format.getFormat("yyyy-MM-dd hh:mm:ss");
        for (int i = 0; i < lists.size(); i++) {
            HSSFRow row = sheet.createRow(i + 3);//  
            OrganizationModel obj = lists.get(i);//???  
            /*row.createCell(0).setCellValue(obj.getOrgType());*/
            row.createCell(0).setCellValue(obj.getName());
            row.createCell(1).setCellValue(obj.getCreateName());
            row.createCell(2).setCellValue(obj.getTotalUsers() == null ? 0 : obj.getTotalUsers());
            row.createCell(3).setCellValue(obj.getTotalDevices() == null ? 0 : obj.getTotalDevices());
            row.createCell(4).setCellValue(obj.getLicenseCount() == null ? 0 : obj.getLicenseCount());
            row.createCell(5).setCellValue(obj.getUseUsers() == null ? 0 : obj.getUseUsers());
            HSSFCell cell = row.createCell(6);
            cell.setCellValue(obj.getCreateTime());
            HSSFCellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setDataFormat(formatDate);
            cell.setCellStyle(cellStyle);
        }
        //??  
        for (int colNum = 0; colNum < columnNum; colNum++) {
            int columnWidth = sheet.getColumnWidth(colNum) / 256;
            for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
                HSSFRow currentRow;
                //?  
                currentRow = (sheet.getRow(rowNum) == null) ? sheet.createRow(rowNum) : sheet.getRow(rowNum);
                if (currentRow.getCell(colNum) != null) {
                    HSSFCell currentCell = currentRow.getCell(colNum);
                    if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                        int length = currentCell.getStringCellValue().getBytes().length;
                        if (columnWidth < length) {
                            columnWidth = length;
                        }
                    }
                }
            }
            sheet.setColumnWidth(colNum, (colNum == 0) ? (columnWidth * 256) : ((columnWidth + 10) * 256));
        }
        if (workbook != null) {
            try {
                String fileName = "Excel-" + String.valueOf(System.currentTimeMillis()).substring(4, 13)
                        + ".xls";
                String headStr = "attachment; filename=\"" + fileName + "\"";
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", headStr);
                out = response.getOutputStream();
                workbook.write(out);
            } catch (IOException e) {
                logger.error(e.getMessage());
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        }
    } catch (Exception e) {
        logger.error(e.getMessage());
    }
}

From source file:edu.jhu.cvrg.services.nodeDataService.DataStaging.java

License:Open Source License

private HSSFSheet consolidateAlgorithmFiles(int algorithmCode, HSSFSheet sheet, String subjectIds,
        String userId, String fileNames, boolean isPublic, ApacheCommonsFtpWrapper ftpClient) {

    boolean firstToken = true;
    StringTokenizer tokenizer = new StringTokenizer(subjectIds, "^");
    StringTokenizer fileTokenizer = new StringTokenizer(fileNames, "^");
    String currentSubject = null;
    int lineNumber = 0;
    String headerIndicator = null;
    switch (algorithmCode) {
    case 0:/*from w w w. j  av a 2 s  .com*/
        headerIndicator = CHESNOKOV_HEADER_INDICATOR;
        break;
    case 1:
        headerIndicator = BERGER_HEADER_INDICATOR;
        break;
    }
    String directory = localFtpRoot + sep + userId + utils.generateTimeStamp();
    while (tokenizer.hasMoreTokens() && fileTokenizer.hasMoreTokens()) {
        currentSubject = tokenizer.nextToken();
        System.out.println(currentSubject);
        String file = fileTokenizer.nextToken();
        String bareFile = file.substring(file.lastIndexOf("/") + 1);
        try {
            ftpClient.downloadFile(file, directory + bareFile);
            FileReader fi = new FileReader(directory + bareFile);
            BufferedReader br = new BufferedReader(fi);
            String thisLine = null, value = null;
            int inputLineNumber = 0;

            while ((thisLine = br.readLine()) != null) {
                boolean isHeader = false;
                isHeader = thisLine.contains(headerIndicator);
                if (thisLine != null && thisLine.length() > 0 && (firstToken || !isHeader)) {
                    HSSFRow rowOut = sheet.createRow(lineNumber);
                    StringTokenizer rowTokenizer = new StringTokenizer(thisLine, ",");
                    HSSFCell cellOut;
                    int colNumber = 0;
                    while (rowTokenizer.hasMoreTokens()) {

                        cellOut = rowOut.createCell(colNumber);
                        String replacePipes = rowTokenizer.nextToken();
                        if (isHeader) {

                            replacePipes = replacePipes.replaceAll("\\|", ",");
                            value = replacePipes;
                            StringTokenizer temp = new StringTokenizer(replacePipes, ",");
                            if (temp.countTokens() > 1) {

                                HSSFHyperlink link = new HSSFHyperlink(HSSFHyperlink.LINK_URL);
                                link.setAddress(temp.nextToken());
                                cellOut.setHyperlink(link);
                                value = temp.nextToken().trim();

                            }
                            cellOut.setCellValue(value);
                            sheet.setColumnWidth(colNumber, (value.length() + 3) * 256);

                        } else {

                            cellOut.setCellValue(replacePipes);
                            if (sheet.getColumnWidth(colNumber) / 256 < replacePipes.length())
                                sheet.setColumnWidth(colNumber, replacePipes.length() * 256);
                        }
                        colNumber++;
                    }
                    lineNumber++;
                }
                inputLineNumber++;

            }
            fi.close();
            br.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //}
        firstToken = false;

    }

    return sheet;
}

From source file:Import.Utils.XSSFConvert.java

/**
 * @param destination the sheet to create from the copy.
 * @param the sheet to copy.//  w  w  w. jav  a 2  s  .  co  m
 * @param copyStyle true copy the style.
 */
public static void copySheets(HSSFSheet source, XSSFSheet destination, boolean copyStyle) {
    int maxColumnNum = 0;
    Map<Integer, HSSFCellStyle> styleMap = (copyStyle) ? new HashMap<Integer, HSSFCellStyle>() : null;
    for (int i = source.getFirstRowNum(); i <= source.getLastRowNum(); i++) {
        HSSFRow srcRow = source.getRow(i);
        XSSFRow destRow = destination.createRow(i);
        if (srcRow != null) {
            copyRow(source, destination, srcRow, destRow, styleMap);
            if (srcRow.getLastCellNum() > maxColumnNum) {
                maxColumnNum = srcRow.getLastCellNum();
            }
        }
    }
    for (int i = 0; i <= maxColumnNum; i++) {
        destination.setColumnWidth(i, source.getColumnWidth(i));
    }
}

From source file:org.apache.directory.studio.ldapbrowser.core.jobs.ExportXlsRunnable.java

License:Apache License

/**
 * {@inheritDoc}//from  www.  j av  a2  s  .c o  m
 */
public void run(StudioProgressMonitor monitor) {
    monitor.beginTask(BrowserCoreMessages.jobs__export_xls_task, 2);
    monitor.reportProgress(" "); //$NON-NLS-1$
    monitor.worked(1);

    Preferences coreStore = BrowserCorePlugin.getDefault().getPluginPreferences();
    String valueDelimiter = coreStore.getString(BrowserCoreConstants.PREFERENCE_FORMAT_XLS_VALUEDELIMITER);
    int binaryEncoding = coreStore.getInt(BrowserCoreConstants.PREFERENCE_FORMAT_XLS_BINARYENCODING);

    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet sheet = wb.createSheet("Export"); //$NON-NLS-1$

    // header
    HSSFRow headerRow = sheet.createRow(0);
    LinkedHashMap<String, Integer> attributeNameMap = new LinkedHashMap<String, Integer>();
    if (this.exportDn) {
        int cellNum = 0;
        attributeNameMap.put("dn", cellNum); //$NON-NLS-1$
        createStringCell(headerRow, cellNum).setCellValue("dn"); //$NON-NLS-1$
    }

    // max export
    if (searchParameter.getCountLimit() < 1 || searchParameter.getCountLimit() > MAX_COUNT_LIMIT) {
        searchParameter.setCountLimit(MAX_COUNT_LIMIT);
    }

    // export
    try {
        int count = 0;
        exportToXls(browserConnection, searchParameter, sheet, headerRow, count, monitor, attributeNameMap,
                valueDelimiter, binaryEncoding, this.exportDn);
    } catch (Exception e) {
        monitor.reportError(e);
    }

    // column width
    for (int i = 0; i <= sheet.getLastRowNum(); i++) {
        HSSFRow row = sheet.getRow(i);
        for (short j = 0; row != null && j <= row.getLastCellNum(); j++) {
            HSSFCell cell = row.getCell(j);
            if (cell != null && cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                String value = cell.getStringCellValue();

                if ((short) (value.length() * 256 * 1.1) > sheet.getColumnWidth(j)) {
                    sheet.setColumnWidth(j, (short) (value.length() * 256 * 1.1));
                }
            }
        }
    }

    try {
        FileOutputStream fileOut = new FileOutputStream(exportXlsFilename);
        wb.write(fileOut);
        fileOut.close();
    } catch (Exception e) {
        monitor.reportError(e);
    }
}