Search in sources :

Example 26 with XSSFCellStyle

use of org.apache.poi.xssf.usermodel.XSSFCellStyle in project translationstudio8 by heartsome.

the class ExportQAResult method beginExport.

public void beginExport(List<QAResultBean> dataList, List<String> fileLCList, IProgressMonitor monitor) {
    if (monitor == null) {
        monitor = new NullProgressMonitor();
    }
    // 分成十份,其中解析文件 1 份,其余 9 份
    monitor.beginTask("", 10);
    monitor.setTaskName(Messages.getString("qa.export.ExportQAResult.monitor.title"));
    // 将 fileLCList 转换成相对路径
    List<File> fileList = new ArrayList<File>();
    for (String fileLC : fileLCList) {
        fileList.add(new File(fileLC));
    }
    for (IFile iFile : ResourceUtils.filesToIFiles(fileList)) {
        filePathList.add(iFile.getFullPath().toOSString());
    }
    if (monitor.isCanceled()) {
        throw new OperationCanceledException();
    }
    monitor.worked(1);
    // UNDO 这里按文件排序给注释了。。。。
    //		// 先按文件排序
    //		sort(dataList);
    // 工作簿
    XSSFWorkbook workbook = new XSSFWorkbook();
    // 创建sheet页
    XSSFSheet sheet = workbook.createSheet();
    // 设置sheet名称
    workbook.setSheetName(0, Messages.getString("qa.export.ExportQAResult.sheet.title"));
    sheet.setColumnWidth(0, 255 * 6);
    sheet.setColumnWidth(1, 255 * 20);
    sheet.setColumnWidth(2, 255 * 30);
    sheet.setColumnWidth(3, 255 * 60);
    sheet.setColumnWidth(4, 255 * 60);
    XSSFFont titleFont = workbook.createFont();
    titleFont.setColor(IndexedColors.GREY_80_PERCENT.getIndex());
    titleFont.setBold(true);
    titleFont.setFontHeight(20);
    XSSFFont headerFont = workbook.createFont();
    headerFont.setBold(true);
    headerFont.setFontHeight(14);
    XSSFFont errorFont = workbook.createFont();
    errorFont.setColor(IndexedColors.RED.getIndex());
    XSSFCellStyle titleStyle = workbook.createCellStyle();
    titleStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
    titleStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
    titleStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
    titleStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
    titleStyle.setAlignment(HorizontalAlignment.CENTER);
    titleStyle.setFont(titleFont);
    XSSFCellStyle headerStyle = workbook.createCellStyle();
    headerStyle.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex());
    headerStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
    headerStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
    headerStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
    headerStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
    headerStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
    headerStyle.setFont(headerFont);
    XSSFCellStyle cellStyle = workbook.createCellStyle();
    cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
    cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
    cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
    cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
    cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
    cellStyle.setWrapText(true);
    XSSFCellStyle errorCellStyle = workbook.createCellStyle();
    errorCellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
    errorCellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
    errorCellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
    errorCellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
    errorCellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
    errorCellStyle.setWrapText(true);
    errorCellStyle.setFont(errorFont);
    // 生成标题行
    XSSFRow row = sheet.createRow(0);
    XSSFCell cell = row.createCell(0);
    cell.setCellStyle(titleStyle);
    cell.setCellValue(Messages.getString("qa.export.ExportQAResult.titleCell"));
    String[] headers = new String[] { // 级别
    Messages.getString("qa.export.ExportQAResult.header.errorLeavel"), // 类型
    Messages.getString("qa.export.ExportQAResult.header.qaType"), // 位置
    Messages.getString("qa.export.ExportQAResult.header.location"), // 源文
    Messages.getString("qa.export.ExportQAResult.header.srcText"), //  译文
    Messages.getString("qa.export.ExportQAResult.header.tgtText") };
    // 产生表格标题行
    row = sheet.createRow(1);
    for (short i = 0; i < headers.length; i++) {
        cell = row.createCell(i);
        cell.setCellStyle(headerStyle);
        cell.setCellValue(headers[i]);
    }
    // 开始生成数据
    int index = 1;
    String rowId = null;
    // 先处理品质检查结果数据为空的情况
    if (dataList.size() <= 0) {
        if (isMultiFile) {
            String multiFileStr = getMultiResouce();
            index++;
            row = sheet.createRow(index);
            for (int i = 0; i < headers.length; i++) {
                cell = row.createCell(i);
                cell.setCellStyle(cellStyle);
                if (i == headers.length - 1) {
                    cell.setCellValue(multiFileStr);
                }
            }
        } else {
            for (String filePath : this.filePathList) {
                index++;
                row = sheet.createRow(index);
                for (int i = 0; i < headers.length; i++) {
                    cell = row.createCell(i);
                    cell.setCellStyle(cellStyle);
                    if (i == headers.length - 1) {
                        cell.setCellValue(filePath);
                    }
                }
            }
        }
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 4));
    } else {
        int interval = 1;
        if (dataList.size() > 9) {
            interval = dataList.size() / 9;
        }
        int startMergeRow = -1;
        int endMergeRow = -1;
        for (int i = 0; i < dataList.size(); i++) {
            QAResultBean bean = dataList.get(i);
            index++;
            System.out.println(index);
            if (index % interval == 0) {
                if (monitor.isCanceled()) {
                    throw new OperationCanceledException();
                }
                monitor.worked(1);
            }
            row = sheet.createRow(index);
            // 处理合并 级别 与 类型 两列的行
            mergeIF: if (bean.getMergeId() != null) {
                if (mergedIdSet.contains(bean.getMergeId())) {
                    break mergeIF;
                }
                startMergeRow = index;
                mergeFor: for (int j = i + 1; j < dataList.size(); j++) {
                    if (dataList.get(j).getMergeId() != null && dataList.get(j).getMergeId().equals(bean.getMergeId())) {
                        mergedIdSet.add(bean.getMergeId());
                        endMergeRow = index + (j - i);
                    } else {
                        break mergeFor;
                    }
                }
                if (startMergeRow >= 0 && endMergeRow >= 0) {
                    sheet.addMergedRegion(new CellRangeAddress(startMergeRow, endMergeRow, 0, 0));
                    sheet.addMergedRegion(new CellRangeAddress(startMergeRow, endMergeRow, 1, 1));
                    startMergeRow = -1;
                    endMergeRow = -1;
                }
            }
            // 循环当前行的每一列
            for (int h = 0; h < headers.length; h++) {
                cell = row.createCell(h);
                cell.setCellStyle(cellStyle);
                String text = null;
                switch(h) {
                    case 0:
                        if (bean.getLevel() == 0) {
                            text = Messages.getString("qa.export.ExportQAResult.errorLeavel.error");
                            cell.setCellStyle(errorCellStyle);
                        } else if (bean.getLevel() == 1) {
                            text = Messages.getString("qa.export.ExportQAResult.errorLeavel.warning");
                        }
                        cell.setCellValue(text);
                        break;
                    case 1:
                        text = bean.getQaTypeText();
                        cell.setCellValue(text);
                        break;
                    case 2:
                        text = bean.getFileName() + " [" + bean.getLineNumber() + "]";
                        cell.setCellValue(text);
                        break;
                    case 3:
                        text = bean.getSrcContent();
                        cell.setCellValue(getDisplayText(text));
                        break;
                    case 4:
                        text = bean.getTgtContent();
                        cell.setCellValue(getDisplayText(text));
                        break;
                    default:
                        break;
                }
            }
        }
        //	            // 这是合并 文件路径
        //	            if (isMultiFile) {
        //	            	sheet.addMergedRegion(new CellRangeAddress(resourceIndex, index, 6, 6));
        //	    		}else {
        //	    			sheet.addMergedRegion(new CellRangeAddress(resourceIndex, index, 6, 6));
        //	    		}
        //	            sheet.addMergedRegion(new CellRangeAddress(rowidIndex, index, 1, 1));
        //	    		sheet.addMergedRegion(new CellRangeAddress(rowidIndex, index, 4, 4));
        //	    		sheet.addMergedRegion(new CellRangeAddress(rowidIndex, index, 5, 5));
        // 标题行合并(处理未合并完的部份)
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 4));
    }
    try {
        FileOutputStream fileoutputstream = new FileOutputStream(exportFilePath);
        workbook.write(fileoutputstream);
        fileoutputstream.close();
        Display.getDefault().syncExec(new Runnable() {

            public void run() {
                MessageDialog.openInformation(Display.getDefault().getActiveShell(), Messages.getString("qa.all.dialog.info"), Messages.getString("qa.export.ExportQAResult.MSG.exportSuccess"));
            }
        });
    } catch (Exception e) {
        Display.getDefault().syncExec(new Runnable() {

            public void run() {
                MessageDialog.openInformation(Display.getDefault().getActiveShell(), Messages.getString("qa.all.dialog.info"), Messages.getString("qa.export.ExportQAResult.MSG.exportFail"));
            }
        });
        LOGGER.error(Messages.getString("qa.export.ExportQAResult.LOG.exportError"), e);
    }
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) IFile(org.eclipse.core.resources.IFile) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) QAResultBean(net.heartsome.cat.ts.ui.qa.model.QAResultBean) ArrayList(java.util.ArrayList) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) XSSFSheet(org.apache.poi.xssf.usermodel.XSSFSheet) XSSFCellStyle(org.apache.poi.xssf.usermodel.XSSFCellStyle) XSSFRow(org.apache.poi.xssf.usermodel.XSSFRow) XSSFFont(org.apache.poi.xssf.usermodel.XSSFFont) FileOutputStream(java.io.FileOutputStream) XSSFWorkbook(org.apache.poi.xssf.usermodel.XSSFWorkbook) XSSFCell(org.apache.poi.xssf.usermodel.XSSFCell) CellRangeAddress(org.apache.poi.ss.util.CellRangeAddress) IFile(org.eclipse.core.resources.IFile) File(java.io.File)

Example 27 with XSSFCellStyle

use of org.apache.poi.xssf.usermodel.XSSFCellStyle in project cubrid-manager by CUBRID.

the class ExportTableDataTask method exportXlsx.

/**
	 *
	 * Export data as XLSX file format
	 *
	 * @param rs CUBRIDResultSetProxy
	 * @param monitor IProgressMonitor
	 * @throws IOException The exception
	 * @throws SQLException The exception
	 */
private void exportXlsx(CUBRIDResultSetProxy rs, final IProgressMonitor monitor) throws IOException, SQLException {
    // FIXME move this logic to core module
    // 1048576: limit xlsx row number.
    int rowLimit = ImportFileConstants.XLSX_ROW_LIMIT;
    // 16384: limit xlsx column number.
    int columnLimit = ImportFileConstants.XLSX_COLUMN_LIMIT;
    int cellCharacterLimit = ImportFileConstants.XLSX_CELL_CHAR_LIMIT;
    CUBRIDResultSetMetaDataProxy rsmt = (CUBRIDResultSetMetaDataProxy) rs.getMetaData();
    int colCount = rsmt.getColumnCount();
    if (colCount >= columnLimit) {
        Display.getDefault().syncExec(new Runnable() {

            public void run() {
                if (!CommonUITool.openConfirmBox(Messages.exportColumnCountOverWarnInfo)) {
                    isExit = true;
                }
            }
        });
        if (isExit) {
            return;
        }
        colCount = columnLimit;
    }
    List<String> columnTitles = new ArrayList<String>();
    for (int j = 1; j <= colCount; j++) {
        String columnName = rsmt.getColumnName(j);
        String columnType = rsmt.getColumnTypeName(j);
        int precision = rsmt.getPrecision(j);
        columnType = columnType == null ? "" : columnType;
        setIsHasBigValue(columnType, precision);
        //the data length > XLS column character limit
        if (precision > cellCharacterLimit) {
            final String confirmMSG = Messages.bind(Messages.exportCharacterCountExceedWarnInfo, columnName);
            Display.getDefault().syncExec(new Runnable() {

                public void run() {
                    if (!CommonUITool.openConfirmBox(confirmMSG)) {
                        isExit = true;
                    }
                }
            });
            if (isExit) {
                return;
            }
        }
        if (columnName.length() > cellCharacterLimit) {
            columnName = columnName.substring(0, cellCharacterLimit);
        }
        columnTitles.add(columnName);
    }
    XlsxWriterHelper xlsxWriterhelper = new XlsxWriterHelper();
    //create memory workbook
    XSSFWorkbook workbook = new XSSFWorkbook();
    Calendar cal = Calendar.getInstance();
    int datetimeStyleIndex = ((XSSFCellStyle) xlsxWriterhelper.getStyles(workbook).get("datetime")).getIndex();
    int timestampStyleIndex = ((XSSFCellStyle) xlsxWriterhelper.getStyles(workbook).get("timestamp")).getIndex();
    int dateStyleIndex = ((XSSFCellStyle) xlsxWriterhelper.getStyles(workbook).get("date")).getIndex();
    int timeStyleIndex = ((XSSFCellStyle) xlsxWriterhelper.getStyles(workbook).get("time")).getIndex();
    int sheetNum = 1;
    int xssfRowNum = 0;
    Map<String, File> fileMap = new HashMap<String, File>();
    XlsxWriterHelper.SpreadsheetWriter sheetWriter = null;
    try {
        sheetWriter = createSheetWriter(workbook, xlsxWriterhelper, sheetNum, fileMap, columnTitles, xssfRowNum);
        if (isFirstRowAsColumnName && columnTitles != null) {
            xssfRowNum++;
        }
        while (rs.next()) {
            sheetWriter.insertRow(xssfRowNum);
            for (int k = 1; k <= colCount; k++) {
                String colType = rsmt.getColumnTypeName(k);
                colType = FieldHandlerUtils.amendDataTypeByResult(rs, k, colType);
                int precision = rsmt.getPrecision(k);
                setIsHasBigValue(colType, precision);
                Object cellValue = FieldHandlerUtils.getRsValueForExport(colType, rs, k, nullValue);
                if (cellValue instanceof Long) {
                    sheetWriter.createCell(k - 1, ((Long) cellValue).longValue());
                } else if (cellValue instanceof Double) {
                    sheetWriter.createCell(k - 1, ((Double) cellValue).doubleValue());
                } else if (cellValue instanceof Date) {
                    cal.setTime((Date) cellValue);
                    if (DataType.DATATYPE_DATETIME.equals(colType)) {
                        sheetWriter.createCell(k - 1, cal, datetimeStyleIndex);
                    } else if (DataType.DATATYPE_DATE.equals(colType)) {
                        sheetWriter.createCell(k - 1, cal, dateStyleIndex);
                    } else if (DataType.DATATYPE_TIME.equals(colType)) {
                        sheetWriter.createCell(k - 1, cal, timeStyleIndex);
                    } else {
                        sheetWriter.createCell(k - 1, cal, timestampStyleIndex);
                    }
                } else {
                    String cellStr = cellValue.toString().length() > cellCharacterLimit ? cellValue.toString().substring(0, cellCharacterLimit) : cellValue.toString();
                    sheetWriter.createCell(k - 1, Export.covertXMLString(cellStr));
                }
            }
            sheetWriter.endRow();
            xssfRowNum++;
            if (((exportedCount + 1) % rowLimit) == 0) {
                sheetNum++;
                xssfRowNum -= rowLimit;
                try {
                    XlsxWriterHelper.writeSheetWriter(sheetWriter);
                } catch (IOException e) {
                    sheetWriter = null;
                    throw e;
                }
                sheetWriter = createSheetWriter(workbook, xlsxWriterhelper, sheetNum, fileMap, columnTitles, xssfRowNum);
            }
            exportedCount++;
            monitor.worked(10);
            monitor.subTask(Messages.bind(Messages.msgExportDataRow, exportedCount));
        }
    } finally {
        try {
            XlsxWriterHelper.writeSheetWriter(sheetWriter);
        } catch (IOException e) {
            sheetWriter = null;
            throw e;
        } finally {
            XlsxWriterHelper.writeWorkbook(workbook, xlsxWriterhelper, fileMap, file);
        }
    }
}
Also used : HashMap(java.util.HashMap) Calendar(java.util.Calendar) ArrayList(java.util.ArrayList) IOException(java.io.IOException) XlsxWriterHelper(com.cubrid.common.ui.cubrid.table.control.XlsxWriterHelper) Date(java.util.Date) CUBRIDResultSetMetaDataProxy(com.cubrid.jdbc.proxy.driver.CUBRIDResultSetMetaDataProxy) XSSFCellStyle(org.apache.poi.xssf.usermodel.XSSFCellStyle) XSSFWorkbook(org.apache.poi.xssf.usermodel.XSSFWorkbook) File(java.io.File)

Example 28 with XSSFCellStyle

use of org.apache.poi.xssf.usermodel.XSSFCellStyle in project cubrid-manager by CUBRID.

the class ExportConnectionUtil method writeToXlsx.

/**
	 * Write to xlsx
	 *
	 * @throws IOException
	 */
private void writeToXlsx() throws IOException {
    // FIXME split logic and ui
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet(Messages.sheetNameConnections);
    String sheetRef = sheet.getPackagePart().getPartName().getName().substring(1);
    File tmp = File.createTempFile("Connections", ".xml");
    Map<String, File> fileMap = new HashMap<String, File>();
    fileMap.put(sheetRef, tmp);
    OutputStreamWriter writer = null;
    XlsxWriterHelper xlsxWriterhelper = null;
    XlsxWriterHelper.SpreadsheetWriter sheetWriter = null;
    try {
        writer = new OutputStreamWriter(new FileOutputStream(tmp), "UTF-8");
        xlsxWriterhelper = new XlsxWriterHelper();
        sheetWriter = new XlsxWriterHelper.SpreadsheetWriter(writer);
        sheetWriter.setCharset("UTF-8");
        sheetWriter.beginSheet();
        /* Write the header */
        int styleIndex = ((XSSFCellStyle) xlsxWriterhelper.getStyles(workbook).get("header")).getIndex();
        sheetWriter.insertRow(0);
        sheetWriter.createCell(0, Messages.nameColumn, styleIndex);
        sheetWriter.createCell(1, Messages.iPColumn, styleIndex);
        sheetWriter.createCell(2, Messages.portColumn, styleIndex);
        sheetWriter.createCell(3, Messages.userColumn, styleIndex);
        sheetWriter.createCell(4, Messages.commentColumn, styleIndex);
        sheetWriter.createCell(5, Messages.javaUrlColumn, styleIndex);
        sheetWriter.createCell(6, Messages.phpUrlColumn, styleIndex);
        sheetWriter.endRow();
        /* Write the data */
        int rowIndex = 1;
        for (CubridDatabase database : input) {
            if (database == null) {
                continue;
            }
            DatabaseInfo dbInfo = database.getDatabaseInfo();
            if (dbInfo == null) {
                continue;
            }
            sheetWriter.insertRow(rowIndex++);
            /* name */
            sheetWriter.createCell(0, dbInfo.getDbName());
            /* ip */
            sheetWriter.createCell(1, dbInfo.getBrokerIP());
            /* port */
            sheetWriter.createCell(2, dbInfo.getBrokerPort());
            /* user */
            sheetWriter.createCell(3, getDbUser(dbInfo));
            /* comment */
            String comment = "";
            DatabaseEditorConfig editorConfig = QueryOptions.getEditorConfig(database, managerMode);
            if (editorConfig != null && editorConfig.getDatabaseComment() != null) {
                comment = editorConfig.getDatabaseComment();
            }
            sheetWriter.createCell(4, comment);
            /* javaUrl */
            String url = NodeUtil.getJavaConnectionUrl(dbInfo);
            sheetWriter.createCell(5, url);
            /* phpUrl */
            String phpUrl = NodeUtil.getPHPConnectionUrl(dbInfo);
            sheetWriter.createCell(6, phpUrl);
            sheetWriter.endRow();
        }
        XlsxWriterHelper.writeSheetWriter(sheetWriter);
    } finally {
        XlsxWriterHelper.writeWorkbook(workbook, xlsxWriterhelper, fileMap, file);
    }
}
Also used : HashMap(java.util.HashMap) DatabaseInfo(com.cubrid.cubridmanager.core.cubrid.database.model.DatabaseInfo) XlsxWriterHelper(com.cubrid.common.ui.cubrid.table.control.XlsxWriterHelper) XSSFSheet(org.apache.poi.xssf.usermodel.XSSFSheet) XSSFCellStyle(org.apache.poi.xssf.usermodel.XSSFCellStyle) FileOutputStream(java.io.FileOutputStream) XSSFWorkbook(org.apache.poi.xssf.usermodel.XSSFWorkbook) OutputStreamWriter(java.io.OutputStreamWriter) CubridDatabase(com.cubrid.common.ui.spi.model.CubridDatabase) File(java.io.File) DatabaseEditorConfig(com.cubrid.common.ui.spi.model.DatabaseEditorConfig)

Example 29 with XSSFCellStyle

use of org.apache.poi.xssf.usermodel.XSSFCellStyle in project cubrid-manager by CUBRID.

the class ExportToXlsxHandler method exportFromCache.

public void exportFromCache(String tableName) throws IOException {
    if (StringUtil.isEmpty(tableName)) {
        return;
    }
    // 1048576: limit xlsx row number.
    int rowLimit = ImportFileConstants.XLSX_ROW_LIMIT;
    // 16384: limit xlsx column number.
    int columnLimit = ImportFileConstants.XLSX_COLUMN_LIMIT;
    int cellCharacterLimit = ImportFileConstants.XLSX_CELL_CHAR_LIMIT;
    XlsxWriterHelper xlsxWriterhelper = new XlsxWriterHelper();
    //create memory workbook
    XSSFWorkbook workbook = new XSSFWorkbook();
    Calendar cal = Calendar.getInstance();
    int datetimeStyleIndex = ((XSSFCellStyle) xlsxWriterhelper.getStyles(workbook).get("datetime")).getIndex();
    int timestampStyleIndex = ((XSSFCellStyle) xlsxWriterhelper.getStyles(workbook).get("timestamp")).getIndex();
    int dateStyleIndex = ((XSSFCellStyle) xlsxWriterhelper.getStyles(workbook).get("date")).getIndex();
    int timeStyleIndex = ((XSSFCellStyle) xlsxWriterhelper.getStyles(workbook).get("time")).getIndex();
    int sheetNum = 0;
    int xssfRowNum = 0;
    File file = new File(exportConfig.getDataFilePath(tableName));
    Map<String, File> fileMap = new HashMap<String, File>();
    XlsxWriterHelper.SpreadsheetWriter sheetWriter = null;
    boolean isInitedColumnTitle = false;
    List<String> columnTitles = new ArrayList<String>();
    try {
        int exportedCount = 0;
        ResultSetDataCache resultSetDataCache = exportConfig.getResultSetDataCache();
        List<ColumnInfo> columnInfos = resultSetDataCache.getColumnInfos();
        List<ArrayList<Object>> datas = resultSetDataCache.getDatas();
        int colCount = columnInfos.size();
        if (colCount >= columnLimit && !isConfirmColumnLimit) {
            isConfirmColumnLimit = true;
            Display.getDefault().syncExec(new Runnable() {

                public void run() {
                    if (!CommonUITool.openConfirmBox(Messages.exportColumnCountOverWarnInfo)) {
                        isExit = true;
                    }
                }
            });
            if (isExit) {
                return;
            }
            colCount = columnLimit;
        }
        if (!isInitedColumnTitle) {
            for (ColumnInfo column : columnInfos) {
                columnTitles.add(column.getName());
            }
            isInitedColumnTitle = true;
            if (isExit) {
                return;
            }
            sheetWriter = createSheetWriter(workbook, xlsxWriterhelper, sheetNum++, fileMap, columnTitles, xssfRowNum);
            if (exportConfig.isFirstRowAsColumnName()) {
                xssfRowNum++;
            }
        }
        try {
            for (ArrayList<Object> rowData : datas) {
                sheetWriter.insertRow(xssfRowNum);
                for (int k = 1; k <= colCount; k++) {
                    String colType = columnInfos.get(k - 1).getType();
                    int precision = columnInfos.get(k - 1).getPrecision();
                    setIsHasBigValue(colType, precision);
                    Object cellValue = rowData.get(k - 1);
                    // We need judge the CLOB/BLOD data by column type
                    if (DataType.DATATYPE_BLOB.equals(colType) || DataType.DATATYPE_CLOB.equals(colType)) {
                        if (DataType.DATATYPE_BLOB.equals(colType)) {
                            String fileName = exportBlobData(tableName, (Blob) cellValue);
                            String dataCellValue = DataType.NULL_EXPORT_FORMAT;
                            if (StringUtil.isNotEmpty(fileName)) {
                                dataCellValue = DBAttrTypeFormatter.FILE_URL_PREFIX + tableName + BLOB_FOLDER_POSTFIX + File.separator + fileName;
                            }
                            sheetWriter.createCell(k - 1, dataCellValue);
                        } else {
                            String fileName = exportClobData(tableName, (Clob) cellValue);
                            String dataCellValue = DataType.NULL_EXPORT_FORMAT;
                            if (StringUtil.isNotEmpty(fileName)) {
                                dataCellValue = DBAttrTypeFormatter.FILE_URL_PREFIX + tableName + CLOB_FOLDER_POSTFIX + File.separator + fileName;
                            }
                            sheetWriter.createCell(k - 1, dataCellValue);
                        }
                    } else if (cellValue instanceof Long) {
                        sheetWriter.createCell(k - 1, ((Long) cellValue).longValue());
                    } else if (cellValue instanceof Double) {
                        sheetWriter.createCell(k - 1, ((Double) cellValue).doubleValue());
                    } else if (cellValue instanceof Date) {
                        cal.setTime((Date) cellValue);
                        if (DataType.DATATYPE_DATETIME.equals(colType)) {
                            sheetWriter.createCell(k - 1, cal, datetimeStyleIndex);
                        } else if (DataType.DATATYPE_DATE.equals(colType)) {
                            sheetWriter.createCell(k - 1, cal, dateStyleIndex);
                        } else if (DataType.DATATYPE_TIME.equals(colType)) {
                            sheetWriter.createCell(k - 1, cal, timeStyleIndex);
                        } else {
                            sheetWriter.createCell(k - 1, cal, timestampStyleIndex);
                        }
                    } else {
                        String cellStr = cellValue.toString().length() > cellCharacterLimit ? cellValue.toString().substring(0, cellCharacterLimit) : cellValue.toString();
                        sheetWriter.createCell(k - 1, Export.covertXMLString(cellStr));
                    }
                }
                sheetWriter.endRow();
                xssfRowNum++;
                exportedCount++;
                if ((xssfRowNum + 1) % rowLimit == 0) {
                    xssfRowNum = 0;
                    if (sheetWriter != null) {
                        try {
                            XlsxWriterHelper.writeSheetWriter(sheetWriter);
                        } catch (IOException e) {
                            sheetWriter = null;
                            throw e;
                        }
                    }
                    sheetWriter = createSheetWriter(workbook, xlsxWriterhelper, sheetNum, fileMap, columnTitles, xssfRowNum);
                    sheetNum++;
                    if (exportConfig.isFirstRowAsColumnName()) {
                        xssfRowNum++;
                    }
                }
                if (exportedCount >= COMMIT_LINES) {
                    exportDataEventHandler.handleEvent(new ExportDataSuccessEvent(tableName, exportedCount));
                    exportedCount = 0;
                }
                if (stop) {
                    break;
                }
            }
            exportDataEventHandler.handleEvent(new ExportDataSuccessEvent(tableName, exportedCount));
            exportedCount = 0;
        } catch (Exception e) {
            LOGGER.error("", e);
            exportDataEventHandler.handleEvent(new ExportDataFailedOneTableEvent(tableName));
        }
        System.gc();
    } finally {
        try {
            if (sheetWriter != null) {
                XlsxWriterHelper.writeSheetWriter(sheetWriter);
            }
        } catch (IOException e) {
            sheetWriter = null;
            throw e;
        } finally {
            XlsxWriterHelper.writeWorkbook(workbook, xlsxWriterhelper, fileMap, file);
        }
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ColumnInfo(com.cubrid.common.ui.query.control.ColumnInfo) XlsxWriterHelper(com.cubrid.common.ui.cubrid.table.control.XlsxWriterHelper) XSSFCellStyle(org.apache.poi.xssf.usermodel.XSSFCellStyle) ExportDataFailedOneTableEvent(com.cubrid.common.ui.cubrid.table.event.ExportDataFailedOneTableEvent) XSSFWorkbook(org.apache.poi.xssf.usermodel.XSSFWorkbook) ResultSetDataCache(com.cubrid.common.ui.cubrid.table.export.ResultSetDataCache) Calendar(java.util.Calendar) IOException(java.io.IOException) Date(java.util.Date) SQLException(java.sql.SQLException) IOException(java.io.IOException) ExportDataSuccessEvent(com.cubrid.common.ui.cubrid.table.event.ExportDataSuccessEvent) File(java.io.File)

Example 30 with XSSFCellStyle

use of org.apache.poi.xssf.usermodel.XSSFCellStyle in project cubrid-manager by CUBRID.

the class ExportToXlsxHandler method exportByQuerying.

public void exportByQuerying(String tableName) throws IOException, SQLException {
    if (StringUtil.isEmpty(tableName)) {
        return;
    }
    long totalRecord = exportConfig.getTotalCount(tableName);
    if (totalRecord == 0) {
        return;
    }
    // 1048576: limit xlsx row number.
    int rowLimit = ImportFileConstants.XLSX_ROW_LIMIT;
    // 16384: limit xlsx column number.
    int columnLimit = ImportFileConstants.XLSX_COLUMN_LIMIT;
    int cellCharacterLimit = ImportFileConstants.XLSX_CELL_CHAR_LIMIT;
    boolean hasNextPage = true;
    long beginIndex = 1;
    String whereCondition = exportConfig.getWhereCondition(tableName);
    XlsxWriterHelper xlsxWriterhelper = new XlsxWriterHelper();
    //create memory workbook
    XSSFWorkbook workbook = new XSSFWorkbook();
    Calendar cal = Calendar.getInstance();
    int datetimeStyleIndex = ((XSSFCellStyle) xlsxWriterhelper.getStyles(workbook).get("datetime")).getIndex();
    int timestampStyleIndex = ((XSSFCellStyle) xlsxWriterhelper.getStyles(workbook).get("timestamp")).getIndex();
    int dateStyleIndex = ((XSSFCellStyle) xlsxWriterhelper.getStyles(workbook).get("date")).getIndex();
    int timeStyleIndex = ((XSSFCellStyle) xlsxWriterhelper.getStyles(workbook).get("time")).getIndex();
    int sheetNum = 0;
    int xssfRowNum = 0;
    File file = new File(exportConfig.getDataFilePath(tableName));
    Map<String, File> fileMap = new HashMap<String, File>();
    XlsxWriterHelper.SpreadsheetWriter sheetWriter = null;
    Connection conn = null;
    CUBRIDPreparedStatementProxy pStmt = null;
    CUBRIDResultSetProxy rs = null;
    boolean isInitedColumnTitle = false;
    List<String> columnTitles = new ArrayList<String>();
    try {
        conn = getConnection();
        String sql = QueryUtil.getSelectSQL(conn, tableName);
        isPaginating = isPagination(whereCondition, sql, whereCondition);
        int exportedCount = 0;
        while (hasNextPage) {
            String executeSQL = null;
            if (isPaginating) {
                long endIndex = beginIndex + RSPAGESIZE;
                executeSQL = getExecuteSQL(sql, beginIndex, endIndex, whereCondition);
                executeSQL = dbInfo.wrapShardQuery(executeSQL);
                beginIndex = endIndex + 1;
            } else {
                executeSQL = getExecuteSQL(sql, whereCondition);
                executeSQL = dbInfo.wrapShardQuery(sql);
                beginIndex = totalRecord + 1;
            }
            pStmt = getStatement(conn, executeSQL, tableName);
            rs = (CUBRIDResultSetProxy) pStmt.executeQuery();
            CUBRIDResultSetMetaDataProxy rsmt = (CUBRIDResultSetMetaDataProxy) rs.getMetaData();
            int colCount = rsmt.getColumnCount();
            if (colCount >= columnLimit && !isConfirmColumnLimit) {
                isConfirmColumnLimit = true;
                Display.getDefault().syncExec(new Runnable() {

                    public void run() {
                        if (!CommonUITool.openConfirmBox(Messages.exportColumnCountOverWarnInfo)) {
                            isExit = true;
                        }
                    }
                });
                if (isExit) {
                    return;
                }
                colCount = columnLimit;
            }
            if (!isInitedColumnTitle) {
                columnTitles = getColumnTitleList(rsmt);
                isInitedColumnTitle = true;
                if (isExit) {
                    return;
                }
                if (sheetWriter != null) {
                    try {
                        XlsxWriterHelper.writeSheetWriter(sheetWriter);
                    } catch (IOException e) {
                        sheetWriter = null;
                        throw e;
                    }
                }
                sheetWriter = createSheetWriter(workbook, xlsxWriterhelper, sheetNum++, fileMap, columnTitles, xssfRowNum);
                if (exportConfig.isFirstRowAsColumnName()) {
                    xssfRowNum++;
                }
            }
            try {
                while (rs.next()) {
                    sheetWriter.insertRow(xssfRowNum);
                    for (int k = 1; k <= colCount; k++) {
                        String colType = rsmt.getColumnTypeName(k);
                        colType = FieldHandlerUtils.amendDataTypeByResult(rs, k, colType);
                        int precision = rsmt.getPrecision(k);
                        setIsHasBigValue(colType, precision);
                        Object cellValue = FieldHandlerUtils.getRsValueForExport(colType, rs, k, exportConfig.getNULLValueTranslation());
                        // We need judge the CLOB/BLOD data by column type
                        if (DataType.DATATYPE_BLOB.equals(colType) || DataType.DATATYPE_CLOB.equals(colType)) {
                            if (DataType.DATATYPE_BLOB.equals(colType)) {
                                String fileName = exportBlobData(tableName, rs, k);
                                String dataCellValue = DataType.NULL_EXPORT_FORMAT;
                                if (StringUtil.isNotEmpty(fileName)) {
                                    dataCellValue = DBAttrTypeFormatter.FILE_URL_PREFIX + tableName + BLOB_FOLDER_POSTFIX + File.separator + fileName;
                                }
                                sheetWriter.createCell(k - 1, dataCellValue);
                            } else {
                                String fileName = exportClobData(tableName, rs, k);
                                String dataCellValue = DataType.NULL_EXPORT_FORMAT;
                                if (StringUtil.isNotEmpty(fileName)) {
                                    dataCellValue = DBAttrTypeFormatter.FILE_URL_PREFIX + tableName + CLOB_FOLDER_POSTFIX + File.separator + fileName;
                                }
                                sheetWriter.createCell(k - 1, dataCellValue);
                            }
                        } else if (cellValue instanceof Long) {
                            sheetWriter.createCell(k - 1, ((Long) cellValue).longValue());
                        } else if (cellValue instanceof Double) {
                            sheetWriter.createCell(k - 1, ((Double) cellValue).doubleValue());
                        } else if (cellValue instanceof Date) {
                            cal.setTime((Date) cellValue);
                            if (DataType.DATATYPE_DATETIME.equals(colType)) {
                                sheetWriter.createCell(k - 1, cal, datetimeStyleIndex);
                            } else if (DataType.DATATYPE_DATE.equals(colType)) {
                                sheetWriter.createCell(k - 1, cal, dateStyleIndex);
                            } else if (DataType.DATATYPE_TIME.equals(colType)) {
                                sheetWriter.createCell(k - 1, cal, timeStyleIndex);
                            } else {
                                sheetWriter.createCell(k - 1, cal, timestampStyleIndex);
                            }
                        } else {
                            String cellStr = cellValue.toString().length() > cellCharacterLimit ? cellValue.toString().substring(0, cellCharacterLimit) : cellValue.toString();
                            sheetWriter.createCell(k - 1, Export.covertXMLString(cellStr));
                        }
                    }
                    sheetWriter.endRow();
                    xssfRowNum++;
                    exportedCount++;
                    if ((xssfRowNum + 1) % rowLimit == 0) {
                        xssfRowNum = 0;
                        if (sheetWriter != null) {
                            try {
                                XlsxWriterHelper.writeSheetWriter(sheetWriter);
                            } catch (IOException e) {
                                sheetWriter = null;
                                throw e;
                            }
                        }
                        sheetWriter = createSheetWriter(workbook, xlsxWriterhelper, sheetNum, fileMap, columnTitles, xssfRowNum);
                        sheetNum++;
                        if (exportConfig.isFirstRowAsColumnName()) {
                            xssfRowNum++;
                        }
                    }
                    if (exportedCount >= COMMIT_LINES) {
                        exportDataEventHandler.handleEvent(new ExportDataSuccessEvent(tableName, exportedCount));
                        exportedCount = 0;
                    }
                    if (stop) {
                        break;
                    }
                }
                exportDataEventHandler.handleEvent(new ExportDataSuccessEvent(tableName, exportedCount));
                exportedCount = 0;
            } catch (Exception e) {
                LOGGER.error("", e);
                exportDataEventHandler.handleEvent(new ExportDataFailedOneTableEvent(tableName));
            } finally {
                QueryUtil.freeQuery(pStmt, rs);
            }
            if (hasNextPage(beginIndex, totalRecord)) {
                hasNextPage = true;
            } else {
                hasNextPage = false;
            }
            System.gc();
        }
    } finally {
        QueryUtil.freeQuery(conn);
        try {
            if (sheetWriter != null) {
                XlsxWriterHelper.writeSheetWriter(sheetWriter);
            }
        } catch (IOException e) {
            sheetWriter = null;
            throw e;
        } finally {
            XlsxWriterHelper.writeWorkbook(workbook, xlsxWriterhelper, fileMap, file);
        }
    }
}
Also used : HashMap(java.util.HashMap) CUBRIDPreparedStatementProxy(com.cubrid.jdbc.proxy.driver.CUBRIDPreparedStatementProxy) ArrayList(java.util.ArrayList) XlsxWriterHelper(com.cubrid.common.ui.cubrid.table.control.XlsxWriterHelper) CUBRIDResultSetMetaDataProxy(com.cubrid.jdbc.proxy.driver.CUBRIDResultSetMetaDataProxy) XSSFCellStyle(org.apache.poi.xssf.usermodel.XSSFCellStyle) ExportDataFailedOneTableEvent(com.cubrid.common.ui.cubrid.table.event.ExportDataFailedOneTableEvent) XSSFWorkbook(org.apache.poi.xssf.usermodel.XSSFWorkbook) CUBRIDResultSetProxy(com.cubrid.jdbc.proxy.driver.CUBRIDResultSetProxy) Calendar(java.util.Calendar) Connection(java.sql.Connection) IOException(java.io.IOException) Date(java.util.Date) SQLException(java.sql.SQLException) IOException(java.io.IOException) ExportDataSuccessEvent(com.cubrid.common.ui.cubrid.table.event.ExportDataSuccessEvent) File(java.io.File)

Aggregations

XSSFCellStyle (org.apache.poi.xssf.usermodel.XSSFCellStyle)38 XSSFFont (org.apache.poi.xssf.usermodel.XSSFFont)22 XSSFColor (org.apache.poi.xssf.usermodel.XSSFColor)20 Cell (org.apache.poi.ss.usermodel.Cell)16 Row (org.apache.poi.ss.usermodel.Row)16 CellRangeAddress (org.apache.poi.ss.util.CellRangeAddress)13 XSSFWorkbook (org.apache.poi.xssf.usermodel.XSSFWorkbook)12 File (java.io.File)8 XSSFSheet (org.apache.poi.xssf.usermodel.XSSFSheet)8 HashMap (java.util.HashMap)7 XlsxWriterHelper (com.cubrid.common.ui.cubrid.table.control.XlsxWriterHelper)6 FileOutputStream (java.io.FileOutputStream)6 List (java.util.List)6 XSSFCell (org.apache.poi.xssf.usermodel.XSSFCell)6 KpiVO (com.netsteadfast.greenstep.vo.KpiVO)5 ArrayList (java.util.ArrayList)5 DateRangeScoreVO (com.netsteadfast.greenstep.vo.DateRangeScoreVO)4 ObjectiveVO (com.netsteadfast.greenstep.vo.ObjectiveVO)4 PerspectiveVO (com.netsteadfast.greenstep.vo.PerspectiveVO)4 OutputStreamWriter (java.io.OutputStreamWriter)4