List of usage examples for org.apache.poi.ss.util CellRangeAddress CellRangeAddress
public CellRangeAddress(int firstRow, int lastRow, int firstCol, int lastCol)
From source file:de.jlo.talendcomp.excel.SpreadsheetOutput.java
License:Apache License
private CellRangeAddress createAppendingCellRangeAddress(CellRangeAddress originalAdressRange, int newLastRowIndex) { return new CellRangeAddress(originalAdressRange.getLastRow() + 1, newLastRowIndex, originalAdressRange.getFirstColumn(), originalAdressRange.getLastColumn()); }
From source file:de.maklerpoint.office.Schnittstellen.Excel.ExportKalenderExcel.java
License:Open Source License
/** * /*from w ww. j a va 2 s .co m*/ * @throws FileNotFoundException * @throws IOException */ public void write() throws FileNotFoundException, IOException { Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); HSSFWorkbook wb = new HSSFWorkbook(); Map<String, HSSFCellStyle> styles = createStyles(wb); for (int month = 0; month < 12; month++) { calendar.set(Calendar.MONTH, month); calendar.set(Calendar.DAY_OF_MONTH, 1); //create a sheet for each month HSSFSheet sheet = wb.createSheet(months[month]); //turn off gridlines sheet.setDisplayGridlines(false); sheet.setPrintGridlines(false); sheet.setFitToPage(true); sheet.setHorizontallyCenter(true); HSSFPrintSetup printSetup = sheet.getPrintSetup(); printSetup.setLandscape(true); //the following three statements are required only for HSSF sheet.setAutobreaks(true); printSetup.setFitHeight((short) 1); printSetup.setFitWidth((short) 1); //the header row: centered text in 48pt font HSSFRow headerRow = sheet.createRow(0); headerRow.setHeightInPoints(80); HSSFCell titleCell = headerRow.createCell(0); titleCell.setCellValue(months[month] + " " + year); titleCell.setCellStyle(styles.get("title")); // sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$N$1")); //header with month titles HSSFRow monthRow = sheet.createRow(1); for (int i = 0; i < days.length; i++) { //set column widths, the width is measured in units of 1/256th of a character width sheet.setColumnWidth((i * 2), (5 * 256)); //the column is 5 characters wide sheet.setColumnWidth((i * 2 + 1), (13 * 256)); //the column is 13 characters wide //sheet.addMergedRegion(new Region(1, (short) 1, i*2, (short) (i * 2 + 1))); sheet.addMergedRegion(new CellRangeAddress(1, i * 2, 1, (i * 2 + 1))); // TODO Test HSSFCell monthCell = monthRow.createCell((i * 2)); monthCell.setCellValue(days[i]); monthCell.setCellStyle(styles.get("month")); } int cnt = 1, day = 1; int rownum = 2; for (int j = 0; j < 6; j++) { HSSFRow row = sheet.createRow(rownum++); row.setHeightInPoints(100); for (int i = 0; i < days.length; i++) { HSSFCell dayCell_1 = row.createCell((i * 2)); HSSFCell dayCell_2 = row.createCell((i * 2 + 1)); int day_of_week = calendar.get(Calendar.DAY_OF_WEEK); if (cnt >= day_of_week && calendar.get(Calendar.MONTH) == month) { dayCell_1.setCellValue(day); calendar.set(Calendar.DAY_OF_MONTH, ++day); if (i == 0 || i == days.length - 1) { dayCell_1.setCellStyle(styles.get("weekend_left")); dayCell_2.setCellStyle(styles.get("weekend_right")); } else { dayCell_1.setCellStyle(styles.get("workday_left")); dayCell_2.setCellStyle(styles.get("workday_right")); } } else { dayCell_1.setCellStyle(styles.get("grey_left")); dayCell_2.setCellStyle(styles.get("grey_right")); } cnt++; } if (calendar.get(Calendar.MONTH) > month) break; } } // Write the output to a file FileOutputStream out = new FileOutputStream(this.filename); wb.write(out); out.close(); }
From source file:de.thb.ue.backend.util.EvaluationExcelFileGenerator.java
License:Apache License
private void createTextualAnswers(@NonNull List<Vote> answers, @NonNull List<String> questionTexts, Sheet sheet, Workbook wb) {//from ww w . jav a 2 s .co m Row row; Cell cell; row = sheet.createRow(sheet.getLastRowNum() + 2); cell = row.createCell(1); CellStyle helpStyle = wb.createCellStyle(); helpStyle.cloneStyleFrom(headerStyle); helpStyle.setBorderBottom(CellStyle.BORDER_NONE); helpStyle.setBorderTop(CellStyle.BORDER_NONE); helpStyle.setBorderLeft(CellStyle.BORDER_NONE); helpStyle.setBorderRight(CellStyle.BORDER_NONE); cell.setCellValue("Kommentare"); cell.setCellStyle(helpStyle); //TODO used to determine style for current line -> its stupid. Think of something better int styleCounter = 0; for (String textualQuestion : questionTexts) { row = sheet.createRow(sheet.getLastRowNum() + 3); cell = row.createCell(1); cell.setCellValue(textualQuestion); setTextQuestionStyle(cell, styleCounter, true); //colorize horizontal neighbour cells of headline for (int i = 2; i < 5; i++) { cell = row.createCell(i); setTextQuestionStyle(cell, styleCounter, false); } int rowNum = sheet.getLastRowNum(); int counter = 1; for (String comment : aggregateTextAnswers(answers, textualQuestion)) { row = sheet.createRow(rowNum + 1); cell = row.createCell(1, Cell.CELL_TYPE_STRING); // introduces line breaks in long comments ArrayList<String> commentChunks = splitComment(comment); StringBuilder formattedComment = new StringBuilder(); formattedComment.append(Integer.toString(counter)); formattedComment.append(": "); int chunkCounter = 0; for (String chunk : commentChunks) { formattedComment.append(chunk); if ((chunkCounter + 1) < commentChunks.size()) { formattedComment.append(System.lineSeparator()); } chunkCounter++; } cell.setCellValue(formattedComment.toString()); CellStyle style = setTextQuestionStyle(cell, styleCounter, false); // increase height of row based on font size, number of lines and line spacing // the origin of 140 % -> http://superuser.com/questions/337181/how-many-pts-is-1-5-line-spacing-in-microsoft-word-2007 float pointsPerLine = (wb.getFontAt(style.getFontIndex()).getFontHeightInPoints() * 140) / 100; row.setHeightInPoints(pointsPerLine * commentChunks.size()); //colorize horizontal neighbour cells of comment for (int i = 2; i < 17; i++) { cell = row.createCell(i); setTextQuestionStyle(cell, styleCounter, false); } sheet.addMergedRegion(new CellRangeAddress(row.getRowNum(), row.getRowNum(), 1, 17)); rowNum++; counter++; } styleCounter++; } }
From source file:Demos.CalendarDemo.java
License:Apache License
public static void main(String[] args) throws Exception { Calendar calendar = Calendar.getInstance(); boolean xlsx = true; for (int i = 0; i < args.length; i++) { if (args[i].charAt(0) == '-') { xlsx = args[i].equals("-xlsx"); } else {//from ww w .jav a 2 s .com calendar.set(Calendar.YEAR, Integer.parseInt(args[i])); } } int year = calendar.get(Calendar.YEAR); Workbook wb = xlsx ? new XSSFWorkbook() : new HSSFWorkbook(); Map<String, CellStyle> styles = createStyles(wb); for (int month = 0; month < 12; month++) { calendar.set(Calendar.MONTH, month); calendar.set(Calendar.DAY_OF_MONTH, 1); // create a sheet for each month Sheet sheet = wb.createSheet(months[month]); // turn off gridlines sheet.setDisplayGridlines(false); sheet.setPrintGridlines(false); sheet.setFitToPage(true); sheet.setHorizontallyCenter(true); PrintSetup printSetup = sheet.getPrintSetup(); printSetup.setLandscape(true); // the following three statements are required only for HSSF sheet.setAutobreaks(true); printSetup.setFitHeight((short) 1); printSetup.setFitWidth((short) 1); // the header row: centered text in 48pt font Row headerRow = sheet.createRow(0); headerRow.setHeightInPoints(80); Cell titleCell = headerRow.createCell(0); titleCell.setCellValue(months[month] + " " + year); titleCell.setCellStyle(styles.get("title")); sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$N$1")); // header with month titles Row monthRow = sheet.createRow(1); for (int i = 0; i < days.length; i++) { // set column widths, the width is measured in units of 1/256th // of a character width sheet.setColumnWidth(i * 2, 5 * 256); // the column is 5 // characters wide sheet.setColumnWidth(i * 2 + 1, 13 * 256); // the column is 13 // characters wide sheet.addMergedRegion(new CellRangeAddress(1, 1, i * 2, i * 2 + 1)); Cell monthCell = monthRow.createCell(i * 2); monthCell.setCellValue(days[i]); monthCell.setCellStyle(styles.get("month")); } int cnt = 1, day = 1; int rownum = 2; for (int j = 0; j < 6; j++) { Row row = sheet.createRow(rownum++); row.setHeightInPoints(100); for (int i = 0; i < days.length; i++) { Cell dayCell_1 = row.createCell(i * 2); Cell dayCell_2 = row.createCell(i * 2 + 1); int day_of_week = calendar.get(Calendar.DAY_OF_WEEK); if (cnt >= day_of_week && calendar.get(Calendar.MONTH) == month) { dayCell_1.setCellValue(day); calendar.set(Calendar.DAY_OF_MONTH, ++day); if (i == 0 || i == days.length - 1) { dayCell_1.setCellStyle(styles.get("weekend_left")); dayCell_2.setCellStyle(styles.get("weekend_right")); } else { dayCell_1.setCellStyle(styles.get("workday_left")); dayCell_2.setCellStyle(styles.get("workday_right")); } } else { dayCell_1.setCellStyle(styles.get("grey_left")); dayCell_2.setCellStyle(styles.get("grey_right")); } cnt++; } if (calendar.get(Calendar.MONTH) > month) break; } } // Write the output to a file String file = "C:\\Users\\BaldiniHP\\Desktop\\calendar.xls"; if (wb instanceof XSSFWorkbook) file += "x"; FileOutputStream out = new FileOutputStream(file); wb.write(out); out.close(); }
From source file:document.ExcelDocument.java
protected void mergeCellsInRow(Sheet sheet, int rowIdx, int startCellIdx, int span) { sheet.addMergedRegion(new CellRangeAddress(rowIdx, rowIdx, startCellIdx, startCellIdx + span - 1)); }
From source file:Documentos.ClaseAlmacenGeneral.java
public void crearExcel() { try {//from w w w. j ava2 s . co m // Defino el Libro de Excel HSSFWorkbook wb = new HSSFWorkbook(); // Creo la Hoja en Excel Sheet sheet1 = wb.createSheet("Productos"); Sheet sheet2 = wb.createSheet("hoja2"); Sheet sheet3 = wb.createSheet("hoja3"); // quito las lineas del libro para darle un mejor acabado // sheet.setDisplayGridlines(false); sheet1.addMergedRegion(new CellRangeAddress(0, 0, 0, 7)); sheet2.addMergedRegion(new CellRangeAddress(0, 0, 0, 7)); sheet3.addMergedRegion(new CellRangeAddress(0, 0, 0, 7)); // creo una nueva fila Row trow = sheet1.createRow((short) 0); createTituloCell(wb, trow, 0, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "Productos de Almacn-Repostera AnaIS " + ControllerFechas.getFechaActual()); // Creo la cabecera de mi listado en Excel Row row = sheet1.createRow((short) 2); createCell(wb, row, 0, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "Cdigo de producto", true, true); createCell(wb, row, 1, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "Nombre", true, true); createCell(wb, row, 2, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "Cantidad", true, true); createCell(wb, row, 3, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "Existencia", true, true); createCell(wb, row, 4, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "Existencia minma", true, true); Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost/poscakeapp", "root", ""); try ( // Creamos un Statement para poder hacer peticiones a la bd Statement stat = con.createStatement()) { ResultSet resultado = stat.executeQuery( "select idProducto, nombre, cantidad,UnidadExistencia,minStock where tipoProducto=2 from producto"); while (resultado.next()) { //creamos la fila Row fila = sheet1.createRow(3 + i); String idProducto = String.valueOf(resultado.getString("idProducto")); String nombre = String.valueOf(resultado.getString("nombre")); String cantidad = String.valueOf(resultado.getInt("cantidad")); String UnidadExistencia = String.valueOf(resultado.getInt("UnidadExistencia")); String minStock = String.valueOf(resultado.getInt("minStock")); // Creo las celdas de mi fila, se puede poner un diseo a la celda System.out.println(i + " /// " + idProducto + " - " + nombre + " - " + cantidad + " - " + UnidadExistencia + " - " + minStock); creandoCelda(wb, fila, 0, idProducto); creandoCelda(wb, fila, 1, nombre); creandoCelda(wb, fila, 2, cantidad); creandoCelda(wb, fila, 3, UnidadExistencia); creandoCelda(wb, fila, 4, minStock); i++; } } con.close(); // Definimos el tamao de las celdas, podemos definir un tamaa especifico o hacer que // la celda se acomode segn su tamao Sheet ssheet = wb.getSheetAt(0); ssheet.autoSizeColumn(0); ssheet.autoSizeColumn(1); ssheet.autoSizeColumn(2); ssheet.autoSizeColumn(3); ssheet.autoSizeColumn(4); ssheet.autoSizeColumn(5); ssheet.autoSizeColumn(6); ssheet.autoSizeColumn(7); //Ajustando la hoja de una pagina Sheet sheet = wb.createSheet("format sheet"); PrintSetup ps = sheet.getPrintSetup(); sheet.setAutobreaks(true); ps.setFitHeight((short) 1); ps.setFitWidth((short) 1); //Area de impresion wb.setPrintArea(0, 0, 1, 0, 9); String strRuta = System.getProperty("user.dir") + System.getProperty("file.separator") + "reports" + System.getProperty("file.separator") + "Almacen" + ControllerFechas.getFechaActual() + ".xls"; //"C:\\Users\\Tet\\Documents\\GitHub\\gestionProyecto\\4.- Cdigo\\AnaIsRepo" + ControllerFechas.getFechaActual() + ".xls"; try (FileOutputStream fileOut = new FileOutputStream(strRuta)) { wb.write(fileOut); } JOptionPane.showMessageDialog(null, "Se ha creado!\nSu archivo es:\n" + strRuta); } catch (Exception e) { e.printStackTrace(); //JOptionPane.showMessageDialog(null, "El archivo no se ha creado debido a que otro usuario esta haciendo uso de el.\nSe recomienda cerrar el archivo"); } }
From source file:Documentos.ClaseAlmacenProducto.java
public void crearExcel() { try {//from w w w . j ava 2s .com // Defino el Libro de Excel HSSFWorkbook wb = new HSSFWorkbook(); // Creo la Hoja en Excel Sheet sheet1 = wb.createSheet("Productos"); Sheet sheet2 = wb.createSheet("hoja2"); Sheet sheet3 = wb.createSheet("hoja3"); // quito las lineas del libro para darle un mejor acabado // sheet.setDisplayGridlines(false); sheet1.addMergedRegion(new CellRangeAddress(0, 0, 0, 7)); sheet2.addMergedRegion(new CellRangeAddress(0, 0, 0, 7)); sheet3.addMergedRegion(new CellRangeAddress(0, 0, 0, 7)); // creo una nueva fila Row trow = sheet1.createRow((short) 0); createTituloCell(wb, trow, 0, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "Productos existentes-Repostera AnaIS " + ControllerFechas.getFechaActual()); // Creo la cabecera de mi listado en Excel Row row = sheet1.createRow((short) 2); createCell(wb, row, 0, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "Cdigo de producto", true, true); createCell(wb, row, 1, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "Nombre", true, true); createCell(wb, row, 2, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "Cantidad", true, true); createCell(wb, row, 3, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "Precio de Venta", true, true); createCell(wb, row, 4, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "Ganancia", true, true); createCell(wb, row, 5, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "Existencia", true, true); Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost/poscakeapp", "root", ""); try ( // Creamos un Statement para poder hacer peticiones a la bd Statement stat = con.createStatement()) { ResultSet resultado = stat.executeQuery( "select idproducto,nombre,format(cantidad,0) as cantidad,preciocompra,precioVenta,concat('$ ',format(((precioventa-preciocompra)*cantidad),2)) as ganancia, UnidadExistencia from producto where tipoProducto = 3;"); while (resultado.next()) { //creamos la fila Row fila = sheet1.createRow(3 + i); String idProducto = String.valueOf(resultado.getString("idProducto")); String nombre = String.valueOf(resultado.getString("nombre")); String cantidad = String.valueOf(resultado.getInt("cantidad")); String precioVenta = String.valueOf(resultado.getString("precioVenta")); String ganancia = String.valueOf(resultado.getString("ganancia")); String UnidadExistencia = String.valueOf(resultado.getInt("UnidadExistencia")); //String Image = String.valueOf(resultado.getBlob("Image")); // Creo las celdas de mi fila, se puede poner un diseo a la celda System.out.println(i + " /// " + idProducto + " - " + nombre + " - " + cantidad + " - " + precioVenta + " - " + ganancia + " - " + UnidadExistencia); creandoCelda(wb, fila, 0, idProducto); creandoCelda(wb, fila, 1, nombre); creandoCelda(wb, fila, 2, cantidad); creandoCelda(wb, fila, 3, precioVenta); creandoCelda(wb, fila, 4, ganancia); creandoCelda(wb, fila, 5, UnidadExistencia); //creandoCelda(wb, fila, 5, Image); i++; } } con.close(); // Definimos el tamao de las celdas, podemos definir un tamaa especifico o hacer que // la celda se acomode segn su tamao Sheet ssheet = wb.getSheetAt(0); ssheet.autoSizeColumn(0); ssheet.autoSizeColumn(1); ssheet.autoSizeColumn(2); ssheet.autoSizeColumn(3); ssheet.autoSizeColumn(4); ssheet.autoSizeColumn(5); ssheet.autoSizeColumn(6); ssheet.autoSizeColumn(7); //Ajustando la hoja de una pagina Sheet sheet = wb.createSheet("format sheet"); PrintSetup ps = sheet.getPrintSetup(); sheet.setAutobreaks(true); ps.setFitHeight((short) 1); ps.setFitWidth((short) 1); //Area de impresion wb.setPrintArea(0, 0, 1, 0, 9); String strRuta = System.getProperty("user.dir") + System.getProperty("file.separator") + "reports" + System.getProperty("file.separator") + "Productos" + ControllerFechas.getFechaActual() + ".xls"; //"C:\\Users\\Tet\\Documents\\GitHub\\gestionProyecto\\4.- Cdigo\\AnaIsRepo" + ControllerFechas.getFechaActual() + ".xls"; try (FileOutputStream fileOut = new FileOutputStream(strRuta)) { wb.write(fileOut); } JOptionPane.showMessageDialog(null, "Se ha creado!\nSu archivo es:\n" + strRuta); } catch (Exception e) { e.printStackTrace(); //JOptionPane.showMessageDialog(null, "El archivo no se ha creado debido a que otro usuario esta haciendo uso de el.\nSe recomienda cerrar el archivo"); } }
From source file:Documentos.ClaseAlmacenXLS.java
public void crearExcel() { try {/*from w w w . ja v a 2s . c om*/ // Defino el Libro de Excel HSSFWorkbook wb = new HSSFWorkbook(); // Creo la Hoja en Excel Sheet sheet1 = wb.createSheet("Productos"); Sheet sheet2 = wb.createSheet("hoja2"); Sheet sheet3 = wb.createSheet("hoja3"); // quito las lineas del libro para darle un mejor acabado // sheet.setDisplayGridlines(false); sheet1.addMergedRegion(new CellRangeAddress(0, 0, 0, 7)); sheet2.addMergedRegion(new CellRangeAddress(0, 0, 0, 7)); sheet3.addMergedRegion(new CellRangeAddress(0, 0, 0, 7)); // creo una nueva fila Row trow = sheet1.createRow((short) 0); createTituloCell(wb, trow, 0, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "Productos de Almacn-Repostera AnaIS " + ControllerFechas.getFechaActual()); // Creo la cabecera de mi listado en Excel Row row = sheet1.createRow((short) 2); createCell(wb, row, 0, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "Cdigo de producto", true, true); createCell(wb, row, 1, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "Nombre", true, true); createCell(wb, row, 2, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "Cantidad", true, true); createCell(wb, row, 3, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "Existencia", true, true); createCell(wb, row, 4, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "Existencia minma", true, true); Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost/poscakeapp", "root", ""); try ( // Creamos un Statement para poder hacer peticiones a la bd Statement stat = con.createStatement()) { ResultSet resultado = stat.executeQuery( "select idProducto, nombre, cantidad,UnidadExistencia,minStock from producto where tipoProducto=2 "); while (resultado.next()) { //creamos la fila Row fila = sheet1.createRow(3 + i); String idProducto = String.valueOf(resultado.getString("idProducto")); String nombre = String.valueOf(resultado.getString("nombre")); String cantidad = String.valueOf(resultado.getInt("cantidad")); String UnidadExistencia = String.valueOf(resultado.getInt("UnidadExistencia")); String minStock = String.valueOf(resultado.getInt("minStock")); // Creo las celdas de mi fila, se puede poner un diseo a la celda System.out.println(i + " /// " + idProducto + " - " + nombre + " - " + cantidad + " - " + UnidadExistencia + " - " + minStock); creandoCelda(wb, fila, 0, idProducto); creandoCelda(wb, fila, 1, nombre); creandoCelda(wb, fila, 2, cantidad); creandoCelda(wb, fila, 3, UnidadExistencia); creandoCelda(wb, fila, 4, minStock); i++; } } con.close(); // Definimos el tamao de las celdas, podemos definir un tamaa especifico o hacer que // la celda se acomode segn su tamao Sheet ssheet = wb.getSheetAt(0); ssheet.autoSizeColumn(0); ssheet.autoSizeColumn(1); ssheet.autoSizeColumn(2); ssheet.autoSizeColumn(3); ssheet.autoSizeColumn(4); ssheet.autoSizeColumn(5); ssheet.autoSizeColumn(6); ssheet.autoSizeColumn(7); //Ajustando la hoja de una pagina Sheet sheet = wb.createSheet("format sheet"); PrintSetup ps = sheet.getPrintSetup(); sheet.setAutobreaks(true); ps.setFitHeight((short) 1); ps.setFitWidth((short) 1); //Area de impresion wb.setPrintArea(0, 0, 1, 0, 9); String strRuta = System.getProperty("user.dir") + System.getProperty("file.separator") + "reports" + System.getProperty("file.separator") + "Almacen" + ControllerFechas.getFechaActual() + ".xls"; //"C:\\Users\\Tet\\Documents\\GitHub\\gestionProyecto\\4.- Cdigo\\AnaIsRepo" + ControllerFechas.getFechaActual() + ".xls"; try (FileOutputStream fileOut = new FileOutputStream(strRuta)) { wb.write(fileOut); } JOptionPane.showMessageDialog(null, "Se ha creado!\nSu archivo es:\n" + strRuta); } catch (Exception e) { e.printStackTrace(); //JOptionPane.showMessageDialog(null, "El archivo no se ha creado debido a que otro usuario esta haciendo uso de el.\nSe recomienda cerrar el archivo"); } }
From source file:DSC.AccountantReport.java
private static void createExcelReport() { XSSFWorkbook workbook = new XSSFWorkbook(); clients.sort(new Comparator<Client>() { @Override//from w ww . j ava 2s. co m public int compare(Client o1, Client o2) { return (o1.getSurname() + " " + o1.getName()).compareTo(o2.getSurname() + " " + o2.getName()); } }); int lastIndex = 0; for (int letter = 0; letter < 26; letter++) { XSSFSheet sheet = workbook.createSheet("AccountReport " + (char) (65 + letter)); Map<String, Object[]> data = new TreeMap<>(); data.put("1", new Object[] { "Doorstep Chef Accountant Sheet", "", "", "", "", "", "", "Week: " + DriverReport.returnWeekInt(), "", "" }); data.put("2", new Object[] { "", "", "", "", "", "", "", "", "", "" }); data.put("3", new Object[] { "Customer", "Contact", "Fam", "4Day", "Mthly", "EFT", "Cash", "Date Paid", "Stay", "Comments" }); int reduction = 0; for (int i = 0; i < clients.size(); i++) { Client client = clients.get(i); if (client.getSurname().toUpperCase().charAt(0) == (char) (65 + letter)) { data.put((i + 4 - reduction) + "", new Object[] { client.getName() + " " + client.getSurname(), client.getContactNumber().substring(0, 3) + " " + client.getContactNumber().substring(3, 6) + " " + client.getContactNumber().substring(6, 10), client.getAdditionalInfo(), "", "", "", "", "", "", "" }); } else { reduction++; } } Set<String> keySet = data.keySet(); int totalSize = 34900; int longestCustomer = 0; for (int key = 1; key < keySet.size() + 1; key++) { Row row = sheet.createRow(key - 1); Object[] arr = data.get(key + ""); for (int i = 0; i < arr.length; i++) { Cell cell = row.createCell(i); cell.setCellValue((String) arr[i]); if (i == 0 && !(key + "").equals("1") && longestCustomer < ((String) arr[i]).length()) { longestCustomer = ((String) arr[i]).length(); } XSSFCellStyle borderStyle = workbook.createCellStyle(); if (!((key + "").equals("1") || (key + "").equals("2"))) { borderStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex()); borderStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex()); borderStyle.setTopBorderColor(IndexedColors.BLACK.getIndex()); borderStyle.setRightBorderColor(IndexedColors.BLACK.getIndex()); if ((key + "").equals("3")) { borderStyle.setBorderBottom(XSSFCellStyle.BORDER_MEDIUM); borderStyle.setBorderLeft(XSSFCellStyle.BORDER_MEDIUM); borderStyle.setBorderTop(XSSFCellStyle.BORDER_MEDIUM); borderStyle.setBorderRight(XSSFCellStyle.BORDER_MEDIUM); borderStyle.setAlignment(HorizontalAlignment.CENTER); borderStyle.setFillPattern(XSSFCellStyle.LESS_DOTS); borderStyle.setFillBackgroundColor(IndexedColors.GREY_50_PERCENT.getIndex()); XSSFFont font = workbook.createFont(); font.setColor(IndexedColors.WHITE.getIndex()); font.setBold(true); borderStyle.setFont(font); } else { if (i != 0) { borderStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN); } else { borderStyle.setBorderLeft(XSSFCellStyle.BORDER_MEDIUM); } if (i != 9) { borderStyle.setBorderRight(XSSFCellStyle.BORDER_THIN); } else { borderStyle.setBorderRight(XSSFCellStyle.BORDER_MEDIUM); } if ((Integer.parseInt((key + ""))) != keySet.size()) { borderStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN); } else { borderStyle.setBorderBottom(XSSFCellStyle.BORDER_MEDIUM); } borderStyle.setBorderTop(XSSFCellStyle.BORDER_THIN); } } else { if (i == 7) { borderStyle.setAlignment(HorizontalAlignment.RIGHT); } XSSFFont font = workbook.createFont(); font.setFontName("Calibri"); font.setFontHeightInPoints((short) 13); font.setBold(true); borderStyle.setFont(font); } cell.setCellStyle(borderStyle); } if (key == 1) { sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 6)); sheet.addMergedRegion(new CellRangeAddress(0, 0, 7, 9)); } } sheet.setColumnWidth(0, (longestCustomer + 1) * 240); sheet.setColumnWidth(1, 11 * 240); sheet.setColumnWidth(2, 5 * 240); sheet.setColumnWidth(3, 5 * 240); sheet.setColumnWidth(4, 5 * 240); sheet.setColumnWidth(5, 5 * 240); sheet.setColumnWidth(6, 5 * 240); sheet.setColumnWidth(7, 10 * 240); sheet.setColumnWidth(8, 5 * 240); for (int i = 0; i < 9; i++) { totalSize -= sheet.getColumnWidth(i); } sheet.setColumnWidth(9, totalSize); Row rowDate = sheet.createRow(keySet.size() + 1); Cell cell = rowDate.createCell(0); SimpleDateFormat sf = new SimpleDateFormat("EEE MMM yyyy HH:mm:ss"); cell.setCellValue(sf.format(Calendar.getInstance().getTime())); XSSFCellStyle cellStyle = workbook.createCellStyle(); cellStyle.setAlignment(XSSFCellStyle.ALIGN_RIGHT); cell.setCellStyle(cellStyle); sheet.addMergedRegion(new CellRangeAddress(keySet.size() + 1, keySet.size() + 1, 0, 9)); } try { workbook.write(excelOut); excelOut.close(); System.out.println("Done - Accountant"); if (!(DSC_Main.generateAllReports)) { accountLoadObj.setVisible(false); accountLoadObj.dispose(); JOptionPane.showMessageDialog(null, "AccountReports Succesfully Generated", "Success", JOptionPane.INFORMATION_MESSAGE); } else { DSC_Main.reportsDone++; if (DSC_Main.reportsDone == DSC_Main.TOTAL_REPORTS) { DSC_Main.reportsDone(); } } } catch (IOException io) { accountLoadObj.setVisible(false); accountLoadObj.dispose(); JOptionPane.showMessageDialog(null, "An error occured\nCould not create AccountReport", "Error", JOptionPane.ERROR_MESSAGE); System.err.println("Error - Could not create new AccountReport: "); io.printStackTrace(); } }
From source file:DSC.ChefReport.java
public static void processChefReport() throws IOException { boolean firstFamEntry = true; String list[] = { "Standard", "Low Carb", "Kiddies" }; int excelNumber = 0; int sheetNumber = 0; for (mealCounter = 0; mealCounter < 3; mealCounter++) { workbook = new XSSFWorkbook(); sheetNumber = 0;//w w w . j a v a 2s . co m for (String currRoute : allRoutes) { Map<String, Object[]> data = new TreeMap<>(); data.put(0 + "", new String[] { "Doorstep Chef - Chef Report " + DriverReport.returnWeekInt(), "", "", "Meal Type : " + list[mealCounter] + " " + " " + "Route: " + sheetNumber }); data.put(1 + "", new String[] { "", "", "", "", "", "", "" }); data.put(2 + "", new String[] { "Family Size", "Quantity", "Allergies", "Exclusions" }); int counter = 3; XSSFSheet sheet = workbook.createSheet("ChefReports Route - " + sheetNumber); int rowNum = 0; int cellNum = 0; String familysize = ""; ArrayList<Meal> mealList = new ArrayList<>(); boolean hasValue = false; for (Order order : orders) { for (Meal meal : order.getMeals()) { if (meal.getMealType().equals(list[mealCounter]) && order.getRoute().equals(currRoute)) { mealList.add(meal); hasValue = true; } } } mealList.sort(new Comparator<Meal>() { @Override public int compare(Meal o1, Meal o2) { if (o1.getQuantity() < o2.getQuantity()) { return -1; } else if (o1.getQuantity() > o2.getQuantity()) { return 1; } else { return 0; } } }); if (hasValue) { int currQuantity = 0; int bulk = 0; boolean firstIterate = true; for (Meal meal : mealList) { if (meal.getQuantity() != currQuantity) { if (!firstIterate && bulk != 0) { data.put(counter + "", new String[] { familysize + " Normal *", bulk + "", "", "" }); bulk = 0; counter++; } firstIterate = false; switch (meal.getQuantity()) { case 1: familysize = "Single"; break; case 2: familysize = "Couple"; break; case 3: familysize = "Three"; break; case 4: familysize = "Four"; break; case 5: familysize = "Five"; break; case 6: familysize = "Six"; break; default: familysize = "Extra"; } currQuantity = meal.getQuantity(); } if (meal.getAllergies().equals("-") && meal.getExclusions().equals("-")) { bulk++; } else { data.put(counter + "", new String[] { familysize + " Meal", meal.getQuantity() + "", meal.getAllergies(), meal.getExclusions() }); counter++; } } } Set<String> keySet = data.keySet(); Object[] keys = data.keySet().toArray(); Arrays.sort(keys); ArrayList<Object> keyList = new ArrayList(); int longestCustomer = 5; int totalWidth = 50000; boolean isBulk = false; for (Object key : keys) { keyList.add(data.get(key)); } for (int keyIterate = 0; keyIterate < keySet.size(); keyIterate++) { Row row = sheet.createRow(rowNum); Object[] arr = data.get(keyIterate + ""); for (int i = 0; i < arr.length; i++) { XSSFFont font = workbook.createFont(); Cell cell = row.createCell(i); cell.setCellValue((String) arr[i]); XSSFCellStyle borderStyle = workbook.createCellStyle(); if ((keyIterate + "").equals("0") || (keyIterate + "").equals("1")) { font.setFontName("Calibri"); font.setFontHeightInPoints((short) 13); font.setBold(true); borderStyle.setFont(font); borderStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex()); borderStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex()); borderStyle.setTopBorderColor(IndexedColors.BLACK.getIndex()); borderStyle.setRightBorderColor(IndexedColors.BLACK.getIndex()); borderStyle.setAlignment(HorizontalAlignment.LEFT); } else { borderStyle.setBorderBottom(BorderStyle.THIN); borderStyle.setBorderTop(BorderStyle.THIN); borderStyle.setBorderLeft(BorderStyle.THIN); borderStyle.setBorderRight(BorderStyle.THIN); if ((arr[0] + "").contains("*")) { isBulk = true; borderStyle.setBorderBottom(BorderStyle.MEDIUM); } } if ((keyIterate + "").equals("2")) { borderStyle.setBorderBottom(XSSFCellStyle.BORDER_MEDIUM); borderStyle.setBorderLeft(XSSFCellStyle.BORDER_MEDIUM); borderStyle.setBorderTop(XSSFCellStyle.BORDER_MEDIUM); borderStyle.setBorderRight(XSSFCellStyle.BORDER_MEDIUM); borderStyle.setAlignment(HorizontalAlignment.CENTER); borderStyle.setFillPattern(XSSFCellStyle.LESS_DOTS); borderStyle.setFillBackgroundColor(IndexedColors.GREY_50_PERCENT.getIndex()); XSSFFont font2 = workbook.createFont(); font2.setColor(IndexedColors.WHITE.getIndex()); borderStyle.setFont(font2); } cell.setCellStyle(borderStyle); } rowNum++; cellNum++; } sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2)); for (int i = 0; i < 5; i++) { switch (i) { case 1: sheet.setColumnWidth(i, 3000); break; case 2: sheet.setColumnWidth(i, 8000); break; default: sheet.setColumnWidth(i, 4000); break; } if (i == 3) { sheet.setColumnWidth(i, 8000); } } Row rowDate = sheet.createRow(keySet.size() + 1); Cell cell = rowDate.createCell(0); SimpleDateFormat sf = new SimpleDateFormat("EEE MMM yyyy HH:mm:ss"); cell.setCellValue(sf.format(Calendar.getInstance().getTime())); XSSFCellStyle cellStyle = workbook.createCellStyle(); cellStyle.setAlignment(XSSFCellStyle.ALIGN_RIGHT); cell.setCellStyle(cellStyle); sheet.addMergedRegion(new CellRangeAddress(keySet.size() + 1, keySet.size() + 1, 0, 3)); sheetNumber++; creatSheet(list[mealCounter], workbook); excelNumber++; if (excelNumber == allRoutes.size()) { if (!(DSC_Main.generateAllReports)) { chefLoadingObj.setVisible(false); chefLoadingObj.dispose(); JOptionPane.showMessageDialog(null, "Chef Reports Successfully Generated."); } } } } }