Search in sources :

Example 6 with WritableWorkbook

use of jxl.write.WritableWorkbook in project cubrid-manager by CUBRID.

the class ExportToXlsHandler method exportFromCache.

public void exportFromCache(String tableName) throws IOException {
    if (StringUtil.isEmpty(tableName)) {
        // FIXME move this logic to core module
        return;
    }
    WritableWorkbook workbook = null;
    int workbookNum = 0;
    int cellCharacterLimit = ImportFileConstants.XLSX_CELL_CHAR_LIMIT;
    // 65536: limit xls row number.
    int rowLimit = ImportFileConstants.XLS_ROW_LIMIT;
    boolean isInitedColumnTitles = false;
    List<String> columnTitles = new ArrayList<String>();
    try {
        int sheetNum = 0;
        int xlsRecordNum = 0;
        workbook = createWorkbook(exportConfig.getDataFilePath(tableName), workbookNum++);
        WritableSheet sheet = workbook.createSheet("Sheet " + sheetNum, sheetNum);
        sheetNum++;
        int exportedCount = 0;
        try {
            ResultSetDataCache resultSetDataCache = exportConfig.getResultSetDataCache();
            List<ArrayList<Object>> datas = resultSetDataCache.getDatas();
            List<ColumnInfo> columnInfos = resultSetDataCache.getColumnInfos();
            int colCount = columnInfos.size();
            if (!isInitedColumnTitles) {
                isInitedColumnTitles = true;
                for (ColumnInfo column : columnInfos) {
                    columnTitles.add(column.getName());
                }
                if (isExit) {
                    return;
                }
                // first line add column name
                if (exportConfig.isFirstRowAsColumnName()) {
                    writeHeader(sheet, columnTitles);
                    xlsRecordNum++;
                }
            }
            for (ArrayList<Object> rowData : datas) {
                //Check memory
                if (!CommonUITool.isAvailableMemory(REMAINING_MEMORY_SIZE)) {
                    closeWorkbook(workbook);
                    workbook = null;
                    System.gc();
                    workbook = createWorkbook(exportConfig.getDataFilePath(tableName), workbookNum++);
                    sheetNum = 0;
                    sheet = workbook.createSheet("Sheet " + sheetNum, sheetNum);
                    sheetNum++;
                    xlsRecordNum = 0;
                    // first line add column name
                    if (exportConfig.isFirstRowAsColumnName()) {
                        writeHeader(sheet, columnTitles);
                        xlsRecordNum++;
                    }
                }
                for (int j = 1; j <= colCount; j++) {
                    String colType = columnInfos.get(j - 1).getType();
                    int precision = columnInfos.get(j - 1).getPrecision();
                    setIsHasBigValue(colType, precision);
                    Object cellValue = rowData.get(j - 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;
                            }
                            sheet.addCell(new Label(j - 1, xlsRecordNum, 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;
                            }
                            sheet.addCell(new Label(j - 1, xlsRecordNum, dataCellValue));
                        }
                    } else if (cellValue instanceof Long) {
                        sheet.addCell(new Number(j - 1, xlsRecordNum, (Long) cellValue));
                    } else if (cellValue instanceof Double) {
                        sheet.addCell(new Number(j - 1, xlsRecordNum, (Double) cellValue));
                    } else if (cellValue instanceof Timestamp) {
                        String dataCellValue = FieldHandlerUtils.formatDateTime((Timestamp) cellValue);
                        sheet.addCell(new Label(j - 1, xlsRecordNum, dataCellValue));
                    } else if (cellValue instanceof java.sql.Time) {
                        String dataCellValue = DateUtil.getDatetimeString(((java.sql.Time) cellValue).getTime(), FieldHandlerUtils.FORMAT_TIME);
                        sheet.addCell(new Label(j - 1, xlsRecordNum, dataCellValue));
                    } else if (cellValue instanceof java.sql.Date) {
                        String dataCellValue = DateUtil.getDatetimeString(((java.sql.Date) cellValue).getTime(), FieldHandlerUtils.FORMAT_DATE);
                        sheet.addCell(new Label(j - 1, xlsRecordNum, dataCellValue));
                    } else {
                        sheet.addCell(new Label(j - 1, xlsRecordNum, cellValue.toString().length() > cellCharacterLimit ? cellValue.toString().substring(0, cellCharacterLimit) : cellValue.toString()));
                    }
                }
                xlsRecordNum++;
                if ((xlsRecordNum + 1) % rowLimit == 0) {
                    xlsRecordNum = 0;
                    sheet = workbook.createSheet("Sheet " + sheetNum, sheetNum);
                    sheetNum++;
                    // first line add column name
                    if (exportConfig.isFirstRowAsColumnName()) {
                        writeHeader(sheet, columnTitles);
                        xlsRecordNum++;
                    }
                }
                exportedCount++;
                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();
    } catch (Exception e) {
        LOGGER.error("", e);
    } finally {
        closeWorkbook(workbook);
    }
}
Also used : ArrayList(java.util.ArrayList) Label(jxl.write.Label) ColumnInfo(com.cubrid.common.ui.query.control.ColumnInfo) Timestamp(java.sql.Timestamp) ExportDataFailedOneTableEvent(com.cubrid.common.ui.cubrid.table.event.ExportDataFailedOneTableEvent) Number(jxl.write.Number) ResultSetDataCache(com.cubrid.common.ui.cubrid.table.export.ResultSetDataCache) WritableSheet(jxl.write.WritableSheet) WriteException(jxl.write.WriteException) SQLException(java.sql.SQLException) IOException(java.io.IOException) RowsExceededException(jxl.write.biff.RowsExceededException) WritableWorkbook(jxl.write.WritableWorkbook) ExportDataSuccessEvent(com.cubrid.common.ui.cubrid.table.event.ExportDataSuccessEvent)

Example 7 with WritableWorkbook

use of jxl.write.WritableWorkbook in project cubrid-manager by CUBRID.

the class ExportTableDataTask method exportXls.

/**
	 * Export data as XLS file format
	 *
	 * @param rs CUBRIDResultSetProxy
	 * @param monitor IProgressMonitor
	 */
private void exportXls(CUBRIDResultSetProxy rs, final IProgressMonitor monitor) {
    // FIXME move this logic to core module
    WritableWorkbook workbook = null;
    try {
        int sheetNum = 0;
        workbook = Workbook.createWorkbook(file);
        if (fileCharset == null || fileCharset.trim().length() == 0) {
            workbook = Workbook.createWorkbook(file);
        } else {
            WorkbookSettings workbookSettings = new WorkbookSettings();
            workbookSettings.setEncoding(fileCharset);
            workbook = Workbook.createWorkbook(file, workbookSettings);
        }
        WritableSheet sheet = workbook.createSheet("Sheet " + sheetNum, sheetNum);
        // 65536: limit xls row number.
        int rowLimit = ImportFileConstants.XLS_ROW_LIMIT;
        // it set 257. Because Tbl's first column is oid value that doesn't export
        // 256: limit xls column number.
        int columnLimit = ImportFileConstants.XLS_COLUMN_LIMIT + 1;
        int cellCharacterLimit = ImportFileConstants.XLSX_CELL_CHAR_LIMIT;
        CUBRIDResultSetMetaDataProxy rsmt = (CUBRIDResultSetMetaDataProxy) rs.getMetaData();
        int colCount = rsmt.getColumnCount() + 1;
        isExit = false;
        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;
                }
            }
            // first line add column name
            if (isFirstRowAsColumnName) {
                WritableFont wf = new WritableFont(WritableFont.ARIAL, 12, WritableFont.BOLD, false);
                WritableCellFormat wcf = new WritableCellFormat(wf);
                if (columnName.length() > cellCharacterLimit) {
                    Label label = new Label(j - 1, 0, columnName.substring(0, cellCharacterLimit));
                    sheet.addCell(label);
                    label = null;
                } else {
                    Label label = new Label(j - 1, 0, columnName.toString(), wcf);
                    sheet.addCell(label);
                    label = null;
                }
                wcf = null;
                wf = null;
            }
        }
        if (colCount > columnLimit) {
            Display.getDefault().syncExec(new Runnable() {

                public void run() {
                    if (!CommonUITool.openConfirmBox(Messages.exportColumnCountOverWarnInfo)) {
                        isExit = true;
                    }
                }
            });
            if (isExit) {
                return;
            }
            colCount = columnLimit;
        }
        int xlsRecordNum = 0;
        if (isFirstRowAsColumnName) {
            xlsRecordNum = 1;
        }
        while (rs.next()) {
            if (!CommonUITool.isAvailableMemory(REMAINING_MEMORY_SIZE)) {
                throw new OutOfMemoryError();
            }
            for (int j = 1; j < colCount; j++) {
                String colType = rsmt.getColumnTypeName(j);
                colType = FieldHandlerUtils.amendDataTypeByResult(rs, j, colType);
                int precision = rsmt.getPrecision(j);
                setIsHasBigValue(colType, precision);
                Object cellValue = FieldHandlerUtils.getRsValueForExport(colType, rs, j, nullValue);
                if (cellValue instanceof Long) {
                    sheet.addCell(new Number(j - 1, xlsRecordNum, (Long) cellValue));
                } else if (cellValue instanceof Double) {
                    sheet.addCell(new Number(j - 1, xlsRecordNum, (Double) cellValue));
                } else if (cellValue instanceof Timestamp) {
                    String dataCellValue = FieldHandlerUtils.formatDateTime((Timestamp) cellValue);
                    sheet.addCell(new Label(j - 1, xlsRecordNum, dataCellValue));
                } else if (cellValue instanceof java.sql.Time) {
                    String dataCellValue = DateUtil.getDatetimeString(((java.sql.Time) cellValue).getTime(), FieldHandlerUtils.FORMAT_TIME);
                    sheet.addCell(new Label(j - 1, xlsRecordNum, dataCellValue));
                } else if (cellValue instanceof java.sql.Date) {
                    String dataCellValue = DateUtil.getDatetimeString(((java.sql.Date) cellValue).getTime(), FieldHandlerUtils.FORMAT_DATE);
                    sheet.addCell(new Label(j - 1, xlsRecordNum, dataCellValue));
                } else {
                    sheet.addCell(new Label(j - 1, xlsRecordNum, cellValue.toString().length() > cellCharacterLimit ? cellValue.toString().substring(0, cellCharacterLimit) : cellValue.toString()));
                }
            }
            xlsRecordNum++;
            if (((exportedCount + 1) % rowLimit) == 0) {
                sheetNum++;
                xlsRecordNum -= rowLimit;
                sheet = workbook.createSheet("Sheet " + sheetNum, sheetNum);
            }
            exportedCount++;
            monitor.worked(10);
            monitor.subTask(Messages.bind(Messages.msgExportDataRow, exportedCount));
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        try {
            if (workbook != null) {
                workbook.write();
            }
        } catch (Exception ignored) {
        }
        try {
            if (workbook != null) {
                workbook.close();
            }
        } catch (Exception ignored) {
        }
    }
}
Also used : WritableFont(jxl.write.WritableFont) Label(jxl.write.Label) WorkbookSettings(jxl.WorkbookSettings) WritableSheet(jxl.write.WritableSheet) WritableCellFormat(jxl.write.WritableCellFormat) Timestamp(java.sql.Timestamp) Date(java.util.Date) ParseException(java.text.ParseException) FileNotFoundException(java.io.FileNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) SQLException(java.sql.SQLException) IOException(java.io.IOException) WritableWorkbook(jxl.write.WritableWorkbook) CUBRIDResultSetMetaDataProxy(com.cubrid.jdbc.proxy.driver.CUBRIDResultSetMetaDataProxy) Number(jxl.write.Number)

Example 8 with WritableWorkbook

use of jxl.write.WritableWorkbook in project cubrid-manager by CUBRID.

the class ImportResultDialog method writeExcel.

/**
	 * wirte error message to exlce
	 * @param file
	 */
public void writeExcel(File file) {
    // FIXME move this logic to core module
    WritableWorkbook wwb = null;
    try {
        wwb = Workbook.createWorkbook(file);
        WritableSheet ws = wwb.createSheet("error", 0);
        ws.setColumnView(0, 100);
        jxl.write.Label label = null;
        for (int i = 0; i < errorList.size(); i++) {
            label = new jxl.write.Label(0, i, errorList.get(i), getNormolCell());
            ws.addCell(label);
        }
        wwb.write();
        CommonUITool.openInformationBox(Messages.infoSuccess, Messages.importResultDialogWriteExcelSucessInfo);
    } catch (Exception e) {
        LOGGER.error("write excel error", e);
    } finally {
        if (wwb != null) {
            try {
                wwb.close();
            } catch (Exception ex) {
                LOGGER.error("close excel stream error", ex);
            }
        }
    }
}
Also used : WritableWorkbook(jxl.write.WritableWorkbook) WritableSheet(jxl.write.WritableSheet) WriteException(jxl.write.WriteException)

Example 9 with WritableWorkbook

use of jxl.write.WritableWorkbook in project cubrid-manager by CUBRID.

the class ExportConnectionUtil method writeToXls.

/**
	 * Write to xls
	 *
	 * @throws IOException
	 * @throws RowsExceededException
	 * @throws WriteException
	 */
private void writeToXls() throws IOException, RowsExceededException, WriteException {
    // FIXME split logic and ui
    WritableWorkbook workbook = null;
    WorkbookSettings workbookSettings = new WorkbookSettings();
    workbookSettings.setEncoding("UTF-8");
    workbook = Workbook.createWorkbook(file, workbookSettings);
    WritableSheet sheet = workbook.createSheet(Messages.sheetNameConnections, 0);
    WritableFont wf = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD, false);
    WritableCellFormat wcf = new WritableCellFormat(wf);
    jxl.write.Label label = null;
    label = new jxl.write.Label(0, 0, Messages.nameColumn, wcf);
    sheet.addCell(label);
    label = new jxl.write.Label(1, 0, Messages.iPColumn, wcf);
    sheet.addCell(label);
    label = new jxl.write.Label(2, 0, Messages.portColumn, wcf);
    sheet.addCell(label);
    label = new jxl.write.Label(3, 0, Messages.userColumn, wcf);
    sheet.addCell(label);
    label = new jxl.write.Label(4, 0, Messages.commentColumn, wcf);
    sheet.addCell(label);
    label = new jxl.write.Label(5, 0, Messages.javaUrlColumn, wcf);
    sheet.addCell(label);
    label = new jxl.write.Label(6, 0, Messages.phpUrlColumn, wcf);
    sheet.addCell(label);
    int index = 1;
    for (CubridDatabase database : input) {
        if (database == null) {
            continue;
        }
        DatabaseInfo dbInfo = database.getDatabaseInfo();
        if (dbInfo == null) {
            continue;
        }
        /* name */
        sheet.addCell(new jxl.write.Label(0, index, dbInfo.getDbName()));
        /* ip */
        sheet.addCell(new jxl.write.Label(1, index, dbInfo.getBrokerIP()));
        /* port */
        sheet.addCell(new jxl.write.Label(2, index, dbInfo.getBrokerPort()));
        /* user */
        sheet.addCell(new jxl.write.Label(3, index, getDbUser(dbInfo)));
        /* comment */
        String comment = "";
        DatabaseEditorConfig editorConfig = QueryOptions.getEditorConfig(database, managerMode);
        if (editorConfig != null && editorConfig.getDatabaseComment() != null) {
            comment = editorConfig.getDatabaseComment();
        }
        sheet.addCell(new jxl.write.Label(4, index, comment));
        /* java url */
        String javaUrl = NodeUtil.getJavaConnectionUrl(dbInfo);
        sheet.addCell(new jxl.write.Label(5, index, javaUrl));
        /* php url */
        String phpUrl = NodeUtil.getPHPConnectionUrl(dbInfo);
        sheet.addCell(new jxl.write.Label(6, index, phpUrl));
        index++;
    }
    workbook.write();
    workbook.close();
}
Also used : WritableWorkbook(jxl.write.WritableWorkbook) DatabaseInfo(com.cubrid.cubridmanager.core.cubrid.database.model.DatabaseInfo) WritableFont(jxl.write.WritableFont) WorkbookSettings(jxl.WorkbookSettings) WritableSheet(jxl.write.WritableSheet) CubridDatabase(com.cubrid.common.ui.spi.model.CubridDatabase) WritableCellFormat(jxl.write.WritableCellFormat) DatabaseEditorConfig(com.cubrid.common.ui.spi.model.DatabaseEditorConfig)

Example 10 with WritableWorkbook

use of jxl.write.WritableWorkbook in project cubrid-manager by CUBRID.

the class BrokerLogTopMergeProgress method writeExcelPartitionByfile.

/**
	 * writeExcelPartitionByfile
	 *
	 * @param mergeString
	 * @param xlsFile
	 * @throws Exception
	 */
public void writeExcelPartitionByfile(ArrayList<ArrayList<String>> mergeString, File xlsFile) throws Exception {
    // FIXME move this logic to core module
    WritableWorkbook wwb = null;
    WritableSheet ws = null;
    String sheetName = "log_top_merge";
    try {
        WritableCellFormat normalCellStyle = getNormalCell();
        WritableCellFormat sqlCellStyle = getSQLCell();
        WorkbookSettings workbookSettings = new WorkbookSettings();
        workbookSettings.setEncoding(charset);
        wwb = Workbook.createWorkbook(xlsFile, workbookSettings);
        ws = wwb.createSheet(sheetName, 0);
        ws.setColumnView(7, 200);
        ws.addCell(new jxl.write.Label(0, 0, "NUM", normalCellStyle));
        ws.addCell(new jxl.write.Label(1, 0, "ID", normalCellStyle));
        ws.addCell(new jxl.write.Label(2, 0, "MAX (sec)", normalCellStyle));
        ws.addCell(new jxl.write.Label(3, 0, "MIN (sec)", normalCellStyle));
        ws.addCell(new jxl.write.Label(4, 0, "AVG (sec)", normalCellStyle));
        ws.addCell(new jxl.write.Label(5, 0, "Counts", normalCellStyle));
        ws.addCell(new jxl.write.Label(6, 0, "Errors", normalCellStyle));
        ws.addCell(new jxl.write.Label(7, 0, "SQL contents", normalCellStyle));
        jxl.write.Label label = null;
        jxl.write.Number num = null;
        for (int i = 0; i < mergeString.size(); i++) {
            List<String> oneLine = mergeString.get(i);
            int row = i + 1;
            for (int j = 0; j < 8; j++) {
                if (j == 0) {
                    String numString = oneLine.get(0) == null ? "" : oneLine.get(0);
                    num = new jxl.write.Number(j, row, Integer.valueOf(numString.replaceAll("Q", "")), normalCellStyle);
                    ws.addCell(num);
                } else if (j == 1) {
                    String comment = "";
                    String sql = oneLine.get(6) == null ? "" : oneLine.get(6).trim();
                    if (sql.startsWith("/*")) {
                        int endIndexOfComment = sql.indexOf("*/");
                        if (endIndexOfComment != -1) {
                            comment = sql.substring(2, endIndexOfComment).trim();
                        }
                    }
                    label = new jxl.write.Label(j, row, comment, sqlCellStyle);
                    ws.addCell(label);
                } else if (j > 1 && j < 7) {
                    num = new jxl.write.Number(j, row, Float.valueOf(oneLine.get(j - 1)), normalCellStyle);
                    ws.addCell(num);
                } else {
                    String s = oneLine.get(6);
                    if (s.length() > excelCelllength) {
                        s = s.substring(0, excelCelllength - 3);
                        s += "...";
                    }
                    label = new jxl.write.Label(j, row, s, sqlCellStyle);
                    ws.addCell(label);
                }
            }
        }
        wwb.write();
    } catch (Exception e) {
        LOGGER.error("write excel error", e);
        throw e;
    } finally {
        if (wwb != null) {
            try {
                wwb.close();
            } catch (Exception ex) {
                LOGGER.error("close excel stream error", ex);
            }
        }
    }
}
Also used : WritableSheet(jxl.write.WritableSheet) WorkbookSettings(jxl.WorkbookSettings) WritableCellFormat(jxl.write.WritableCellFormat) WriteException(jxl.write.WriteException) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) WritableWorkbook(jxl.write.WritableWorkbook)

Aggregations

WritableWorkbook (jxl.write.WritableWorkbook)15 WorkbookSettings (jxl.WorkbookSettings)10 WritableSheet (jxl.write.WritableSheet)10 WriteException (jxl.write.WriteException)7 WritableCellFormat (jxl.write.WritableCellFormat)6 File (java.io.File)5 IOException (java.io.IOException)5 SQLException (java.sql.SQLException)5 InvocationTargetException (java.lang.reflect.InvocationTargetException)4 Label (jxl.write.Label)4 Timestamp (java.sql.Timestamp)3 ArrayList (java.util.ArrayList)3 Number (jxl.write.Number)3 WritableFont (jxl.write.WritableFont)3 ExportDataFailedOneTableEvent (com.cubrid.common.ui.cubrid.table.event.ExportDataFailedOneTableEvent)2 ExportDataSuccessEvent (com.cubrid.common.ui.cubrid.table.event.ExportDataSuccessEvent)2 CUBRIDResultSetMetaDataProxy (com.cubrid.jdbc.proxy.driver.CUBRIDResultSetMetaDataProxy)2 FileNotFoundException (java.io.FileNotFoundException)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 Connection (java.sql.Connection)2