Example usage for org.apache.poi.ss.usermodel Workbook setSheetName

List of usage examples for org.apache.poi.ss.usermodel Workbook setSheetName

Introduction

In this page you can find the example usage for org.apache.poi.ss.usermodel Workbook setSheetName.

Prototype

void setSheetName(int sheet, String name);

Source Link

Document

Set the sheet name.

Usage

From source file:adams.data.io.output.ExcelSpreadSheetWriter.java

License:Open Source License

/**
 * Performs the actual writing. The caller must ensure that the writer gets
 * closed.//w  ww  .  jav a  2  s.co  m
 *
 * @param content   the spreadsheet to write
 * @param out      the writer to write the spreadsheet to
 * @return      true if successfully written
 */
@Override
protected boolean doWrite(SpreadSheet[] content, OutputStream out) {
    boolean result;
    Workbook workbook;
    Sheet sheet;
    Row row;
    adams.data.spreadsheet.Row spRow;
    adams.data.spreadsheet.Cell spCell;
    Cell cell;
    int i;
    int n;
    int count;
    CellStyle styleDate;
    CellStyle styleDateTime;
    CellStyle styleTime;
    HashSet<String> names;
    String name;

    result = true;

    try {
        if (getWriteOOXML())
            workbook = new XSSFWorkbook();
        else
            workbook = new HSSFWorkbook();
        styleDate = ExcelHelper.getDateCellStyle(workbook, Constants.DATE_FORMAT);
        styleDateTime = ExcelHelper.getDateCellStyle(workbook, Constants.TIMESTAMP_FORMAT);
        styleTime = ExcelHelper.getDateCellStyle(workbook, Constants.TIME_FORMAT);

        count = 0;
        names = new HashSet<>();
        for (SpreadSheet cont : content) {
            if (m_Stopped)
                return false;

            sheet = workbook.createSheet();
            if (cont.getName() != null) {
                name = cont.getName().replace("'", "");
                if (names.contains(name))
                    name += (count + 1);
            } else {
                name = m_SheetPrefix + (count + 1);
            }
            names.add(name);
            workbook.setSheetName(count, name);

            // header
            row = sheet.createRow(0);
            for (i = 0; i < cont.getColumnCount(); i++) {
                cell = row.createCell(i);
                cell.setCellValue(cont.getHeaderRow().getCell(i).getContent());
            }

            // data
            for (n = 0; n < cont.getRowCount(); n++) {
                if (m_Stopped)
                    return false;
                row = sheet.createRow(n + 1);
                spRow = cont.getRow(n);
                for (i = 0; i < cont.getColumnCount(); i++) {
                    cell = row.createCell(i);
                    spCell = spRow.getCell(i);
                    if ((spCell == null) || spCell.isMissing()) {
                        if (m_MissingValue.length() > 0)
                            cell.setCellValue(m_MissingValue);
                        else
                            cell.setCellType(Cell.CELL_TYPE_BLANK);
                        continue;
                    }

                    if (spCell.isFormula() && !m_OutputAsDisplayed) {
                        cell.setCellFormula(spCell.getFormula().substring(1));
                    } else {
                        if (spCell.isDate()) {
                            cell.setCellValue(spCell.toDate());
                            cell.setCellStyle(styleDate);
                        } else if (spCell.isTime()) {
                            cell.setCellValue(spCell.toTime());
                            cell.setCellStyle(styleTime);
                        } else if (spCell.isDateTime()) {
                            cell.setCellValue(spCell.toDateTime());
                            cell.setCellStyle(styleDateTime);
                        } else if (spCell.isNumeric()) {
                            cell.setCellValue(Utils.toDouble(spCell.getContent()));
                        } else {
                            cell.setCellValue(spCell.getContent());
                        }
                    }
                }
            }

            // next sheet
            count++;
        }

        // save
        workbook.write(out);
    } catch (Exception e) {
        result = false;
        getLogger().log(Level.SEVERE, "Failed writing spreadsheet data", e);
    }

    return result;
}

From source file:cn.afterturn.easypoi.excel.export.template.ExcelExportOfTemplateUtil.java

License:Apache License

public Workbook createExcelCloneByTemplate(TemplateExportParams params,
        Map<Integer, List<Map<String, Object>>> map) {
    // step 1. ??
    if (params == null || map == null || StringUtils.isEmpty(params.getTemplateUrl())) {
        throw new ExcelExportException(ExcelExportEnum.PARAMETER_ERROR);
    }// ww  w .j  a v a  2  s  .co  m
    Workbook wb = null;
    // step 2. ?Excel,??
    try {
        this.teplateParams = params;
        wb = ExcelCache.getWorkbook(teplateParams.getTemplateUrl(), teplateParams.getSheetNum(), true);
        int oldSheetNum = wb.getNumberOfSheets();
        List<String> oldSheetName = new ArrayList<>();
        for (int i = 0; i < oldSheetNum; i++) {
            oldSheetName.add(wb.getSheetName(i));
        }
        // KEY?
        List<Map<String, Object>> mapList;
        List<Integer> sheetNumList = new ArrayList<>();
        sheetNumList.addAll(map.keySet());
        Collections.sort(sheetNumList);

        //???
        for (Integer sheetNum : sheetNumList) {
            mapList = map.get(sheetNum);
            for (int i = mapList.size(); i > 0; i--) {
                wb.cloneSheet(sheetNum);
            }
        }
        for (int i = 0; i < oldSheetName.size(); i++) {
            wb.removeSheetAt(wb.getSheetIndex(oldSheetName.get(i)));
        }
        // ?
        setExcelExportStyler(
                (IExcelExportStyler) teplateParams.getStyle().getConstructor(Workbook.class).newInstance(wb));
        // step 3. ??
        int sheetIndex = 0;
        for (Integer sheetNum : sheetNumList) {
            mapList = map.get(sheetNum);
            for (int i = mapList.size() - 1; i >= 0; i--) {
                tempCreateCellSet.clear();
                if (mapList.get(i).containsKey(SHEET_NAME)) {
                    wb.setSheetName(sheetIndex, mapList.get(i).get(SHEET_NAME).toString());
                }
                parseTemplate(wb.getSheetAt(sheetIndex), mapList.get(i), params.isColForEach());
                sheetIndex++;
            }
        }
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        return null;
    }
    return wb;
}

From source file:cn.afterturn.easypoi.excel.export.template.ExcelExportOfTemplateUtil.java

License:Apache License

public Workbook createExcelByTemplate(TemplateExportParams params, Map<Integer, Map<String, Object>> map) {
    // step 1. ??
    if (params == null || map == null || StringUtils.isEmpty(params.getTemplateUrl())) {
        throw new ExcelExportException(ExcelExportEnum.PARAMETER_ERROR);
    }/*  w ww.  j av a2s  .com*/
    Workbook wb = null;
    // step 2. ?Excel,??
    try {
        this.teplateParams = params;
        wb = getCloneWorkBook();
        // ?
        setExcelExportStyler(
                (IExcelExportStyler) teplateParams.getStyle().getConstructor(Workbook.class).newInstance(wb));
        // step 3. ??
        for (int i = 0, le = params.isScanAllsheet() ? wb.getNumberOfSheets()
                : params.getSheetNum().length; i < le; i++) {
            if (params.getSheetName() != null && params.getSheetName().length > i
                    && StringUtils.isNotEmpty(params.getSheetName()[i])) {
                wb.setSheetName(i, params.getSheetName()[i]);
            }
            tempCreateCellSet.clear();
            parseTemplate(wb.getSheetAt(i), map.get(i), params.isColForEach());
        }
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        return null;
    }
    return wb;
}

From source file:cn.afterturn.easypoi.excel.export.template.ExcelExportOfTemplateUtil.java

License:Apache License

public Workbook createExcelByTemplate(TemplateExportParams params, Class<?> pojoClass, Collection<?> dataSet,
        Map<String, Object> map) {
    // step 1. ??
    if (params == null || map == null
            || (StringUtils.isEmpty(params.getTemplateUrl()) && params.getTemplateWb() == null)) {
        throw new ExcelExportException(ExcelExportEnum.PARAMETER_ERROR);
    }// w w w  .  j  av  a 2  s . c  om
    Workbook wb = null;
    // step 2. ?Excel,??
    try {
        this.teplateParams = params;
        if (params.getTemplateWb() != null) {
            wb = params.getTemplateWb();
        } else {
            wb = getCloneWorkBook();
        }
        // ?
        setExcelExportStyler(
                (IExcelExportStyler) teplateParams.getStyle().getConstructor(Workbook.class).newInstance(wb));
        // step 3. ??
        for (int i = 0, le = params.isScanAllsheet() ? wb.getNumberOfSheets()
                : params.getSheetNum().length; i < le; i++) {
            if (params.getSheetName() != null && params.getSheetName().length > i
                    && StringUtils.isNotEmpty(params.getSheetName()[i])) {
                wb.setSheetName(i, params.getSheetName()[i]);
            }
            tempCreateCellSet.clear();
            parseTemplate(wb.getSheetAt(i), map, params.isColForEach());
        }
        if (dataSet != null) {
            // step 4. ?
            dataHandler = params.getDataHandler();
            if (dataHandler != null) {
                needHandlerList = Arrays.asList(dataHandler.getNeedHandlerFields());
            }
            addDataToSheet(pojoClass, dataSet, wb.getSheetAt(params.getDataSheetNum()), wb);
        }
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        return null;
    }
    return wb;
}

From source file:cn.bzvs.excel.export.template.ExcelExportOfTemplateUtil.java

License:Apache License

public Workbook createExcleByTemplate(TemplateExportParams params, Class<?> pojoClass, Collection<?> dataSet,
        Map<String, Object> map) {
    // step 1. ??
    if (params == null || map == null || StringUtils.isEmpty(params.getTemplateUrl())) {
        throw new ExcelExportException(ExcelExportEnum.PARAMETER_ERROR);
    }/*from   ww w  .j  av  a  2  s .  c om*/
    Workbook wb = null;
    // step 2. ?Excel,??
    try {
        this.teplateParams = params;
        wb = getCloneWorkBook();
        // ?
        setExcelExportStyler(
                (IExcelExportStyler) teplateParams.getStyle().getConstructor(Workbook.class).newInstance(wb));
        // step 3. ??
        for (int i = 0, le = params.isScanAllsheet() ? wb.getNumberOfSheets()
                : params.getSheetNum().length; i < le; i++) {
            if (params.getSheetName() != null && params.getSheetName().length > i
                    && StringUtils.isNotEmpty(params.getSheetName()[i])) {
                wb.setSheetName(i, params.getSheetName()[i]);
            }
            tempCreateCellSet.clear();
            parseTemplate(wb.getSheetAt(i), map, params.isColForEach());
        }
        if (dataSet != null) {
            // step 4. ?
            dataHanlder = params.getDataHanlder();
            if (dataHanlder != null) {
                needHanlderList = Arrays.asList(dataHanlder.getNeedHandlerFields());
            }
            addDataToSheet(pojoClass, dataSet, wb.getSheetAt(params.getDataSheetNum()), wb);
        }
    } catch (Exception e) {
        e.getMessage();
        return null;
    }
    return wb;
}

From source file:cn.bzvs.excel.export.template.ExcelExportOfTemplateUtil.java

License:Apache License

public Workbook createExcleByTemplate(TemplateExportParams params, Map<Integer, Map<String, Object>> map) {
    // step 1. ??
    if (params == null || map == null || StringUtils.isEmpty(params.getTemplateUrl())) {
        throw new ExcelExportException(ExcelExportEnum.PARAMETER_ERROR);
    }/*  w w w.ja  va  2s .c o m*/
    Workbook wb = null;
    // step 2. ?Excel,??
    try {
        this.teplateParams = params;
        wb = getCloneWorkBook();
        // step 3. ??
        for (int i = 0, le = params.isScanAllsheet() ? wb.getNumberOfSheets()
                : params.getSheetNum().length; i < le; i++) {
            if (params.getSheetName() != null && params.getSheetName().length > i
                    && StringUtils.isNotEmpty(params.getSheetName()[i])) {
                wb.setSheetName(i, params.getSheetName()[i]);
            }
            tempCreateCellSet.clear();
            parseTemplate(wb.getSheetAt(i), map.get(i), params.isColForEach());
        }
    } catch (Exception e) {
        e.getMessage();
        return null;
    }
    return wb;
}

From source file:cn.mypandora.util.MyExcelUtil.java

License:Apache License

/**
 * Excel, ?/* w  w  w. ja v a 2  s  . com*/
 *
 * @param filepath    ?
 * @param sheetTitle  Sheet??
 * @param fieldTitles Sheet????
 */
public static void writeExcel(String filepath, String sheetTitle, String fieldTitles) {
    Workbook[] wbs = new Workbook[] { new HSSFWorkbook(), new XSSFWorkbook() };
    for (int i = 0; i < wbs.length; i++) {
        Workbook wb = wbs[i];
        // ExcelSheet
        Sheet sheet = wb.createSheet();
        wb.setSheetName(0, sheetTitle);

        // Sheet
        createTitle(sheet, fieldTitles);

        // ?Excel
        saveExcelFile(wb, filepath);
    }
}

From source file:cn.mypandora.util.MyExcelUtil.java

License:Apache License

/**
 * Excel ????List<Map<String K,String V>>
 *
 * @param filepath    ?/*from   w  w  w . ja va  2 s. c  o m*/
 * @param sheetTitle  Sheet??
 * @param fieldTitles Sheet????
 * @param objList     ??
 * @param fieldNames  ?objClassfield??
 */
public static void writeExcel(String filepath, String sheetTitle, String fieldTitles,
        List<Map<String, String>> objList, String fieldNames) {
    Workbook[] wbs = new Workbook[] { new HSSFWorkbook(), new XSSFWorkbook() };
    for (int j = 0; j < wbs.length; j++) {
        Workbook workbook = wbs[j];
        CreationHelper creationHelper = workbook.getCreationHelper();

        // ExcelSheet
        Sheet sheet = workbook.createSheet(sheetTitle);
        workbook.setSheetName(0, sheetTitle);

        // Sheet
        createTitle(sheet, fieldTitles);

        // Sheet?
        String[] strArray = fieldNames.split(",");
        for (int objIndex = 0; objIndex < objList.size(); objIndex++) {
            Map<String, String> map = objList.get(objIndex);
            Row row = sheet.createRow(objIndex + 1);
            for (int cellNum = 0; cellNum < strArray.length; cellNum++) {
                Cell cell = row.createCell(cellNum);
                cell.setCellType(CellType.STRING);
                if (map.get(strArray[cellNum]) != null)
                    cell.setCellValue(map.get(strArray[cellNum]).toString());
                else {
                    cell.setCellValue("");
                }
            }
        }

        // ?Excel
        saveExcelFile(workbook, filepath);
    }

}

From source file:cn.mypandora.util.MyExcelUtil.java

License:Apache License

/**
 * Excle/*from  w  w w  .j a v a  2s.  co m*/
 *
 * @param filepath    ?
 * @param sheetTitle  Sheet??
 * @param fieldTitles Sheet????
 * @param objList     ??
 * @param objClass    ???
 * @param fieldNames  ?objClassfield??
 */
public static void writeExcel(String filepath, String sheetTitle, String fieldTitles, List<?> objList,
        Class<?> objClass, String fieldNames) {
    Workbook[] wbs = new Workbook[] { new HSSFWorkbook(), new XSSFWorkbook() };
    for (int j = 0; j < wbs.length; j++) {
        Workbook workbook = wbs[j];
        CreationHelper creationHelper = workbook.getCreationHelper();

        Sheet sheet = workbook.createSheet();
        workbook.setSheetName(0, sheetTitle);

        createTitle(sheet, fieldTitles);
        createBody(sheet, objList, objClass, fieldNames);
        // ?Excel
        saveExcelFile(workbook, filepath);
    }

}

From source file:com.asakusafw.testdata.generator.excel.SheetEditor.java

License:Apache License

/**
 * Creates a clone of the specified sheet.
 * @param oldName the name of original sheet
 * @param newName the created sheet name
 * @throws IllegalArgumentException if some parameters were {@code null}
 *///from  w w w .j a  v a  2s .  co m
public void copy(String oldName, String newName) {
    if (oldName == null) {
        throw new IllegalArgumentException("oldName must not be null"); //$NON-NLS-1$
    }
    if (newName == null) {
        throw new IllegalArgumentException("newName must not be null"); //$NON-NLS-1$
    }
    Workbook workbook = info.workbook;
    int oldIndex = workbook.getSheetIndex(oldName);
    if (oldIndex < 0) {
        throw new IllegalArgumentException();
    }
    Sheet newSheet = workbook.cloneSheet(oldIndex);
    int newIndex = workbook.getSheetIndex(newSheet);
    workbook.setSheetName(newIndex, newName);
}