List of usage examples for org.apache.poi.ss.usermodel Workbook createSheet
Sheet createSheet(String sheetname);
From source file:com.wabacus.system.component.application.report.abstractreport.AbsReportType.java
License:Open Source License
protected void createNewSheet(Workbook workbook, int defaultcolumnwidth) { String title = rbean.getTitle(rrequest); if (sheetIdx > 1) title = title + "_" + sheetIdx; if (title == null || title.trim().equals("")) title = "Sheet_" + (sheetIdx + 100); sheetIdx++;//from ww w . ja v a 2 s . com excelSheet = workbook.createSheet(title); excelSheet.setDefaultColumnWidth(defaultcolumnwidth); excelRowIdx = 0; }
From source file:com.waku.mmdataextract.IMEIMerge.java
License:Open Source License
@SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { Workbook wb = new XSSFWorkbook(); Sheet sheet = wb.createSheet("IMEI"); int colIndex = 0; int rowIndex = 0; Row row = sheet.createRow(rowIndex++); row.createCell(colIndex++).setCellValue(""); row.createCell(colIndex++).setCellValue("?"); row.createCell(colIndex++).setCellValue("?"); row.createCell(colIndex++).setCellValue("IMEI"); int i = 0;// w ww. ja v a2 s. co m InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("Brand.xml"); for (Element brand : (List<Element>) new SAXReader().read(in).selectNodes("/brand/option")) { String brandName = brand.getText(); System.out.println(brandName); File file = new File("output/" + brandName + ".csv"); if (file.exists()) { System.out.println("Found file ->" + file.getAbsolutePath()); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file))); String line = null; boolean noDataAvailable = true; while ((line = br.readLine()) != null) { if (line.indexOf(",") != -1) { rowIndex = addRow(line.split(","), sheet, rowIndex); noDataAvailable = false; } } if (noDataAvailable) { System.out.println("No data for " + brandName); rowIndex = addRow(new String[] { "", brandName, "N/A", "N/A" }, sheet, rowIndex); } br.close(); } else { System.out.println("No file for " + brandName); rowIndex = addRow(new String[] { "", brandName, "N/A", "N/A" }, sheet, rowIndex); } System.out.println(i++); } System.out.println(i); System.out.println(" ---------------------------------- File saved!"); wb.write(new FileOutputStream(new File("IMEI.xls"))); }
From source file:com.wantdo.stat.excel.poi_src.AddDimensionedImage.java
License:Apache License
/** * The main entry point to the program. It contains code that demonstrates * one way to use the program./*w w w .j a va 2 s. c o m*/ * * Note, the code is not restricted to use on new workbooks only. If an * image is to be inserted into an existing workbook. just open that * workbook, gat a reference to a sheet and pass that; * * AddDimensionedImage addImage = new AddDimensionedImage(); * * File file = new File("....... Existing Workbook ......."); * FileInputStream fis = new FileInputStream(file); * Workbook workbook = new HSSFWorkbook(fis); * HSSFSheet sheet = workbook.getSheetAt(0); * addImage.addImageToSheet("C3", sheet, "image.jpg", 30, 20, * AddDimensionedImage.EXPAND.ROW); * * @param args the command line arguments */ public static void main(String[] args) { String imageFile = null; String outputFile = null; FileOutputStream fos = null; Workbook workbook = null; Sheet sheet = null; try { if (args.length < 2) { System.err.println("Usage: AddDimensionedImage imageFile outputFile"); return; } workbook = new HSSFWorkbook(); // OR XSSFWorkbook sheet = workbook.createSheet("Picture Test"); imageFile = args[0]; outputFile = args[1]; new AddDimensionedImage().addImageToSheet("B5", sheet, sheet.createDrawingPatriarch(), new File(imageFile).toURI().toURL(), 100, 40, AddDimensionedImage.EXPAND_ROW_AND_COLUMN); fos = new FileOutputStream(outputFile); workbook.write(fos); } catch (FileNotFoundException fnfEx) { System.out.println("Caught an: " + fnfEx.getClass().getName()); System.out.println("Message: " + fnfEx.getMessage()); System.out.println("Stacktrace follows..........."); fnfEx.printStackTrace(System.out); } catch (IOException ioEx) { System.out.println("Caught an: " + ioEx.getClass().getName()); System.out.println("Message: " + ioEx.getMessage()); System.out.println("Stacktrace follows..........."); ioEx.printStackTrace(System.out); } finally { if (fos != null) { try { fos.close(); fos = null; } catch (IOException ioEx) { // I G N O R E } } } }
From source file:com.wantdo.stat.excel.poi_src.ConditionalFormats.java
License:Apache License
public static void main(String[] args) throws IOException { Workbook wb; if (args.length > 0 && args[0].equals("-xls")) wb = new HSSFWorkbook(); else//from ww w . j av a 2 s .c o m wb = new XSSFWorkbook(); sameCell(wb.createSheet("Same Cell")); multiCell(wb.createSheet("MultiCell")); errors(wb.createSheet("Errors")); hideDupplicates(wb.createSheet("Hide Dups")); formatDuplicates(wb.createSheet("Duplicates")); inList(wb.createSheet("In List")); expiry(wb.createSheet("Expiry")); shadeAlt(wb.createSheet("Shade Alt")); shadeBands(wb.createSheet("Shade Bands")); // Write the output to a file String file = "cf-poi.xls"; if (wb instanceof XSSFWorkbook) file += "x"; FileOutputStream out = new FileOutputStream(file); wb.write(out); out.close(); }
From source file:com.wantdo.stat.excel.poi_src.SSPerformanceTest.java
License:Apache License
public static void main(String[] args) { if (args.length != 4) usage("need four command arguments"); String type = args[0];/*from w w w . j a va 2 s . c om*/ long timeStarted = System.currentTimeMillis(); Workbook workBook = createWorkbook(type); boolean isHType = workBook instanceof HSSFWorkbook; int rows = parseInt(args[1], "Failed to parse rows value as integer"); int cols = parseInt(args[2], "Failed to parse cols value as integer"); boolean saveFile = parseInt(args[3], "Failed to parse saveFile value as integer") != 0; Map<String, CellStyle> styles = createStyles(workBook); Sheet sheet = workBook.createSheet("Main Sheet"); Cell headerCell = sheet.createRow(0).createCell(0); headerCell.setCellValue("Header text is spanned across multiple cells"); headerCell.setCellStyle(styles.get("header")); sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$F$1")); int sheetNo = 0; int rowIndexInSheet = 1; double value = 0; Calendar calendar = Calendar.getInstance(); for (int rowIndex = 0; rowIndex < rows; rowIndex++) { if (isHType && sheetNo != rowIndex / 0x10000) { sheet = workBook.createSheet("Spillover from sheet " + (++sheetNo)); headerCell.setCellValue("Header text is spanned across multiple cells"); headerCell.setCellStyle(styles.get("header")); sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$F$1")); rowIndexInSheet = 1; } Row row = sheet.createRow(rowIndexInSheet); for (int colIndex = 0; colIndex < cols; colIndex++) { Cell cell = row.createCell(colIndex); String address = new CellReference(cell).formatAsString(); switch (colIndex) { case 0: // column A: default number format cell.setCellValue(value++); break; case 1: // column B: #,##0 cell.setCellValue(value++); cell.setCellStyle(styles.get("#,##0.00")); break; case 2: // column C: $#,##0.00 cell.setCellValue(value++); cell.setCellStyle(styles.get("$#,##0.00")); break; case 3: // column D: red bold text on yellow background cell.setCellValue(address); cell.setCellStyle(styles.get("red-bold")); break; case 4: // column E: boolean // TODO booleans are shown as 1/0 instead of TRUE/FALSE cell.setCellValue(rowIndex % 2 == 0); break; case 5: // column F: date / time cell.setCellValue(calendar); cell.setCellStyle(styles.get("m/d/yyyy")); calendar.roll(Calendar.DAY_OF_YEAR, -1); break; case 6: // column F: formula // TODO formulas are not yet supported in SXSSF //cell.setCellFormula("SUM(A" + (rowIndex+1) + ":E" + (rowIndex+1)+ ")"); //break; default: cell.setCellValue(value++); break; } } rowIndexInSheet++; } if (saveFile) { String fileName = type + "_" + rows + "_" + cols + "." + getFileSuffix(args[0]); try { FileOutputStream out = new FileOutputStream(fileName); workBook.write(out); out.close(); } catch (IOException ioe) { System.err .println("Error: failed to write to file \"" + fileName + "\", reason=" + ioe.getMessage()); } } long timeFinished = System.currentTimeMillis(); System.out.println("Elapsed " + (timeFinished - timeStarted) / 1000 + " seconds"); }
From source file:com.zhangyue.zeus.service.impl.ExportDataServiceImpl.java
License:Open Source License
@Override public void downloadData(OutputStream os, String hdfsResultLocation, boolean isDownload) { List<String> resultList = readResultData(hdfsResultLocation, isDownload); if (resultList.size() == 0) { return;//from w w w . j a v a 2s.c om } Workbook book = new HSSFWorkbook(); Sheet sheet = book.createSheet(Constants.SHEET_NAME); sheet.setColumnWidth(0, 10000); for (int i = 0; i < resultList.size(); i++) { Row row = sheet.createRow(i); if (null == resultList.get(i)) { continue; } String[] items = resultList.get(i).split(Constants.HIVE_RESULT_TAG); for (int j = 0; j < items.length; j++) { row.createCell(j).setCellValue(items[j]); } } try { book.write(os); os.flush(); os.close(); } catch (IOException e) { LOG.error("Export excel error!!", e); } }
From source file:com.zlfun.framework.excel.ExcelUtils.java
public static <T> void write(String sheetName, Class<T> clazz, List<T> list, OutputStream out) { if (out == null) { return;/* w w w . j ava2 s . co m*/ } Workbook workbook = new HSSFWorkbook(); Sheet sheet = workbook.createSheet(sheetName); // 15 sheet.setDefaultColumnWidth(15); Drawing drawing = sheet.createDrawingPatriarch(); List<String> header = buildHeader(workbook, sheet, clazz); buildBody(workbook, sheet, drawing, header, list); try { workbook.write(out); } catch (IOException ex) { // TODO Auto-generated catch block Logger.getLogger(ExcelUtils.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.zxy.commons.poi.excel.ExcelUtils.java
License:Apache License
/** * export excel//from www .ja v a 2 s . com * * @param sheetName sheet name * @param table table * @return Workbook */ @SuppressWarnings("PMD.ShortVariable") private static Workbook exportExcel(String sheetName, Table<Integer, String, String> table) { Set<Integer> tableRows = table.rowKeySet(); Set<String> tableColumns = table.columnKeySet(); // excel Workbook wb = new HSSFWorkbook(); // sheet?? Sheet sheet = wb.createSheet(sheetName); // ???n? /*for (int i = 0; i < keys.length; i++) { sheet.setColumnWidth((short) i, (short) (35.7 * 150)); }*/ // Row row = sheet.createRow((short) 0); // ??? CellStyle cs = wb.createCellStyle(); CellStyle cs2 = wb.createCellStyle(); // ? Font f1 = wb.createFont(); Font f2 = wb.createFont(); // ???? f1.setFontHeightInPoints((short) 10); f1.setColor(IndexedColors.BLACK.getIndex()); f1.setBold(true); // ?? f2.setFontHeightInPoints((short) 10); f2.setColor(IndexedColors.BLACK.getIndex()); // Font f3=wb.createFont(); // f3.setFontHeightInPoints((short) 10); // f3.setColor(IndexedColors.RED.getIndex()); // ????? cs.setFont(f1); cs.setBorderLeft(BorderStyle.THIN); cs.setBorderRight(BorderStyle.THIN); cs.setBorderTop(BorderStyle.THIN); cs.setBorderBottom(BorderStyle.THIN); cs.setAlignment(HorizontalAlignment.CENTER); // ??? cs2.setFont(f2); cs2.setBorderLeft(BorderStyle.THIN); cs2.setBorderRight(BorderStyle.THIN); cs2.setBorderTop(BorderStyle.THIN); cs2.setBorderBottom(BorderStyle.THIN); cs2.setAlignment(HorizontalAlignment.CENTER); // ?? int i = 0; for (String tableColumn : tableColumns) { Cell cell = row.createCell(i); cell.setCellValue(tableColumn); cell.setCellStyle(cs); i++; } // ?? for (Integer tableRow : tableRows) { // Row ,Cell , Row Cell 0 // sheet checkArgument(tableRow > 0, "Row index must be greater than zero!"); Row row1 = sheet.createRow(tableRow); // row Map<String, String> item = table.row(tableRow); int j = 0; for (Map.Entry<String, String> entry : item.entrySet()) { // for(String v:item.keySet()){ // System.out.println(tableRow + "-" + v + "-" + item.get(v)); Cell cell = row1.createCell(j); cell.setCellValue(entry.getValue()); cell.setCellStyle(cs2); j++; } } return wb; }
From source file:Compras.altaCompras.java
private void b_muestraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_muestraActionPerformed // TODO add your handling code here: javax.swing.JFileChooser jF1= new javax.swing.JFileChooser(); jF1.setFileFilter(new ExtensionFileFilter("Excel document (*.xls)", new String[] { "xls" })); String ruta = null;//from w w w .j av a 2s .c o m if(jF1.showSaveDialog(null)==jF1.APPROVE_OPTION) { ruta = jF1.getSelectedFile().getAbsolutePath(); File archivoXLS = new File(ruta+".xls"); try { if(archivoXLS.exists()) archivoXLS.delete(); archivoXLS.createNewFile(); Workbook libro = new HSSFWorkbook(); FileOutputStream archivo = new FileOutputStream(archivoXLS); Sheet hoja = libro.createSheet("Muestras"); org.apache.poi.ss.usermodel.Font font10 = libro.createFont(); font10.setFontHeightInPoints((short)10); font10.setFontName("Arial"); font10.setItalic(false); font10.setBold(false); font10.setColor(new HSSFColor.YELLOW().getIndex()); CellStyle titulo = libro.createCellStyle(); CellStyle contenido = libro.createCellStyle(); CellStyle firma = libro.createCellStyle(); CellStyle costado = libro.createCellStyle(); CellStyle derecha = libro.createCellStyle(); CellStyle derecha_borde = libro.createCellStyle(); titulo.setFont(font10); titulo.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); titulo.setFillBackgroundColor(new HSSFColor.GREEN().getIndex()); titulo.setAlignment(CellStyle.ALIGN_CENTER); contenido.setBorderBottom(HSSFCellStyle.BORDER_THIN); contenido.setBorderTop(HSSFCellStyle.BORDER_THIN); contenido.setBorderRight(HSSFCellStyle.BORDER_THIN); contenido.setBorderLeft(HSSFCellStyle.BORDER_THIN); derecha_borde.setBorderBottom(HSSFCellStyle.BORDER_THIN); derecha_borde.setBorderTop(HSSFCellStyle.BORDER_THIN); derecha_borde.setBorderRight(HSSFCellStyle.BORDER_THIN); derecha_borde.setBorderLeft(HSSFCellStyle.BORDER_THIN); derecha_borde.setAlignment(CellStyle.ALIGN_RIGHT); derecha.setAlignment(CellStyle.ALIGN_RIGHT); firma.setBorderTop(HSSFCellStyle.BORDER_THIN); firma.setAlignment(CellStyle.ALIGN_CENTER); //costado.setBorderLeft(HSSFCellStyle.BORDER_THIN); hoja.setColumnWidth(0, 3000); hoja.setColumnWidth(2, 3000); hoja.setColumnWidth(3, 8000); hoja.setColumnWidth(4, 5000); try { InputStream is = new FileInputStream("imagenes/grande300115.jpg"); byte[] bytes = IOUtils.toByteArray(is); int pictureIdx = libro.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG); is.close(); CreationHelper helper = libro.getCreationHelper(); Drawing drawing = hoja.createDrawingPatriarch(); ClientAnchor anchor = helper.createClientAnchor(); anchor.setCol1(0); anchor.setRow1(0); Picture pict = drawing.createPicture(anchor, pictureIdx); pict.resize(); }catch(Exception e){e.printStackTrace();} Row r7 = hoja.createRow(7); r7.createCell(0).setCellValue("ORDEN:"); r7.createCell(1).setCellValue(String.valueOf(ord.getIdOrden())); r7.createCell(2).setCellValue("Hrs. Entrega:"); r7.createCell(3).setCellValue(""); hoja.addMergedRegion(new CellRangeAddress(7,7,4,7)); r7.createCell(4).setCellValue("ORDEN PARA SURTIR MUESTRAS"); r7.getCell(4).setCellStyle(derecha); Date fecha = new Date(); DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");//YYYY-MM-DD HH:MM:SS String valor=dateFormat.format(fecha); Row r8 = hoja.createRow(8); r8.createCell(0).setCellValue("Supervisor:"); hoja.addMergedRegion(new CellRangeAddress(8,8,1,3)); r8.createCell(1).setCellValue(""); r8.createCell(4).setCellValue("F. Elaboracin:"); r8.createCell(5).setCellValue(valor); Row r9 = hoja.createRow(9); r9.createCell(0).setCellValue("Comprador:"); hoja.addMergedRegion(new CellRangeAddress(9,9,1,3)); r9.createCell(1).setCellValue(""); r9.createCell(4).setCellValue("F. Entrega:"); r9.createCell(5).setCellValue(""); Row r10 = hoja.createRow(10); r10.createCell(0).setCellValue("Cantidad"); r10.getCell(0).setCellStyle(titulo); hoja.addMergedRegion(new CellRangeAddress(10,10,1,7)); r10.createCell(1).setCellValue("Descripcin"); r10.getCell(1).setCellStyle(titulo); int ren=11; for(int r=0;r<(t_datos.getRowCount());r++) { if((boolean)t_titulos.getValueAt(r, 3)==true) { Row fila = hoja.createRow(ren); Cell celda = fila.createCell(0); celda.setCellStyle(derecha_borde); Cell celda1 = fila.createCell(1); celda1.setCellStyle(contenido); fila.createCell(2).setCellStyle(contenido); fila.createCell(3).setCellStyle(contenido); fila.createCell(4).setCellStyle(contenido); fila.createCell(5).setCellStyle(contenido); fila.createCell(6).setCellStyle(contenido); fila.createCell(7).setCellStyle(contenido); //Cell celda8 = fila.createCell(8); //celda8.setCellStyle(costado); try{ celda.setCellValue(t_datos.getValueAt(r, 14).toString()); hoja.addMergedRegion(new CellRangeAddress(ren,ren,1,7)); celda1.setCellValue(t_titulos.getValueAt(r, 2).toString()); //celda8.setCellValue(""); }catch(Exception e){ celda.setCellValue(""); } ren++; } } Row rx = hoja.createRow(ren+5); hoja.addMergedRegion(new CellRangeAddress(ren+5,ren+5,0,2)); rx.createCell(0).setCellValue("Recibe Muestras"); rx.getCell(0).setCellStyle(firma); rx.createCell(1).setCellStyle(firma); rx.createCell(2).setCellStyle(firma); hoja.addMergedRegion(new CellRangeAddress(ren+5,ren+5,5,7)); rx.createCell(5).setCellValue("Entrega Muestras"); rx.getCell(5).setCellStyle(firma); rx.createCell(6).setCellStyle(firma); rx.createCell(7).setCellStyle(firma); libro.write(archivo); archivo.close(); Desktop.getDesktop().open(archivoXLS); }catch(Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(this, "No se pudo realizar el reporte si el archivo esta abierto"); } } }
From source file:Compras.altaCompras.java
private void b_exelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_exelActionPerformed // TODO add your handling code here: javax.swing.JFileChooser jF1= new javax.swing.JFileChooser(); jF1.setFileFilter(new ExtensionFileFilter("Excel document (*.xls)", new String[] { "xls" })); String ruta = null;//from www .ja va 2s . com if(jF1.showSaveDialog(null)==jF1.APPROVE_OPTION) { ruta = jF1.getSelectedFile().getAbsolutePath(); if(ruta!=null) { File archivoXLS = new File(ruta+".xls"); try { if(archivoXLS.exists()) archivoXLS.delete(); archivoXLS.createNewFile(); Workbook libro = new HSSFWorkbook(); FileOutputStream archivo = new FileOutputStream(archivoXLS); Sheet hoja = libro.createSheet("reporte1"); for(int ren=0;ren<(t_datos.getRowCount()+1);ren++) { Row fila = hoja.createRow(ren); for(int col=0; col<t_datos.getColumnCount()+(t_titulos.getColumnCount()-1); col++) { Cell celda = fila.createCell(col); if(ren==0) { if(col<3) celda.setCellValue(t_titulos.getColumnName(col)); else celda.setCellValue(t_datos.getColumnName(col-3)); } else { try { if(col<3) celda.setCellValue(t_titulos.getValueAt(ren-1, col).toString()); else { if(t_datos.getValueAt(ren-1, col-3).toString().compareToIgnoreCase("false")==0) celda.setCellValue(""); else { if(t_datos.getValueAt(ren-1, col-3).toString().compareToIgnoreCase("true")==0) celda.setCellValue("x"); else celda.setCellValue(t_datos.getValueAt(ren-1, col-3).toString()); } } }catch(Exception e) { celda.setCellValue(""); } } } } libro.write(archivo); archivo.close(); Desktop.getDesktop().open(archivoXLS); }catch(Exception e) { System.out.println(e); JOptionPane.showMessageDialog(this, "No se pudo realizar el reporte si el archivo esta abierto"); } } } }