List of usage examples for org.apache.poi.ss.usermodel Cell setCellValue
void setCellValue(boolean value);
From source file:Algorithm.Method1.java
public String[] MethodTest(String Path) { StringBuffer keyword1 = new StringBuffer(); try {//from w ww.ja v a 2s. c o m Hashtable hash = new Hashtable(); FileInputStream file = new FileInputStream(new File(Path)); XSSFWorkbook workbook = new XSSFWorkbook(file); XSSFSheet sheet1 = workbook.getSheetAt(0); Iterator<Row> rowIterator = sheet1.iterator(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); //Row rowNew =sheetNew.createRow(rowNumNew++); //For each row, iterate through all the columns Iterator<org.apache.poi.ss.usermodel.Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { org.apache.poi.ss.usermodel.Cell cell = cellIterator.next(); // Cell cellNew =rowNew.createCell(cellNumNew++); //Check the cell type and format accordingly switch (cell.getCellType()) { case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_NUMERIC: break; case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_STRING: String result = cell.getStringCellValue(); if (hash.containsKey(result)) { int f = Integer.parseInt(hash.get(result).toString()); f++; hash.put(result, f); } else { hash.put(result, 1); } } } //System.out.println(""); } XSSFWorkbook workbookNew = new XSSFWorkbook(); XSSFSheet sheetNew = workbookNew.createSheet("test"); int rowNum = 0; Set s = hash.keySet(); String key = new String(); int t = 0; for (Iterator<String> i = s.iterator(); i.hasNext();) { key = i.next(); Row rowNew = sheetNew.createRow(rowNum); org.apache.poi.ss.usermodel.Cell cellNew = rowNew.createCell(0); cellNew.setCellValue(key); keyword1.append(key + " "); org.apache.poi.ss.usermodel.Cell cellNew2 = rowNew.createCell(1); cellNew2.setCellValue(hash.get(key).toString()); rowNum++; //sheet2.addCell(new Label(0,t , key)); //System.out.println(hash.get(key)); //sheet2.addCell(new Label(1,t , hash.get(key).toString())); t++; } FileOutputStream fileOut = new FileOutputStream(new File(Path.replace("???.xlsx", "method1.xlsx")));//new file workbookNew.write(fileOut); fileOut.close(); file.close(); // Workbook book = Workbook.getWorkbook(new File("n.xls")); //WritableWorkbook book2 = Workbook.createWorkbook(new File("method1.xls")); // // WritableSheet sheet2 = book2.createSheet("num1", 0); // //Sheet sheet = book.getSheet(0); //int rownum = sheet.getRows();// /** Cell cell; for(int i = 0;i<rownum;i++){ cell = sheet.getCell(0,i); String result = cell.getContents(); if(hash.containsKey(result)){ int f = Integer.parseInt(hash.get(result).toString()); f++; hash.put(result, f); }else{ hash.put(result, 1); } } */ //?? /* Set s=hash.keySet(); String key = new String(); int t = 0; for(Iterator<String> i=s.iterator();i.hasNext();){ key = i.next(); sheet2.addCell(new Label(0,t , key)); //System.out.println(hash.get(key)); sheet2.addCell(new Label(1,t , hash.get(key).toString())); t++; } book2.write(); book2.close(); */ // book.close(); System.out.print("method1"); } catch (Exception e) { System.out.println(e); } return keyword1.toString().split(" "); }
From source file:Algorithm.Method2.java
public String[] MethodTest(String Path) { StringBuffer keyword1 = new StringBuffer(); try {/*from w w w . j av a 2 s . c om*/ /** * ??excel * src * map? * result */ String srcFilePath = Path; String mapFilePath = "??.xlsx"; String newFilePath = Path.replace("???.xlsx", "method2.xlsx"); FileInputStream srcFile = new FileInputStream(new File(srcFilePath)); FileInputStream mapFile = new FileInputStream(new File(mapFilePath)); XSSFWorkbook srcWorkbook = new XSSFWorkbook(srcFile); XSSFWorkbook mapWorkbook = new XSSFWorkbook(mapFile); XSSFWorkbook newWorkbook = new XSSFWorkbook(); XSSFSheet srcSheet = srcWorkbook.getSheetAt(0); XSSFSheet mapSheet = mapWorkbook.getSheetAt(0); XSSFSheet newSheet = newWorkbook.createSheet("test"); Iterator<Row> srcRowIterator = srcSheet.iterator(); Iterator<Row> mapRowIterator = mapSheet.iterator(); //map.xlst???mapList ArrayList mapList = new ArrayList(); while (mapRowIterator.hasNext()) { Row row = mapRowIterator.next(); Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); String test = cell.getStringCellValue(); mapList.add(test); } } //???mapArray,? int mapListLength = mapList.size(); String[] mapArray = (String[]) mapList.toArray(new String[mapListLength]); //??mapResult,mapArray?src //,mapArray[i]src,mapResult[i]1?0 int[] mapResult = new int[mapListLength]; for (int i = 0; i < mapListLength; i++) { mapResult[i] = 0; } //?src.xlsx,?mapArray while (srcRowIterator.hasNext()) { Row row = srcRowIterator.next(); Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); String test = cell.getStringCellValue().trim(); for (int i = 0; i < mapListLength; i++) { if (test.equals(mapArray[i])) mapResult[i] = 1; } } } //?mapResult,mapArrayresult int newRowNum = 0; for (int i = mapListLength - 1; i >= 0; i--) { if (mapResult[i] == 1) { Row newRow = newSheet.createRow(newRowNum++); Cell newCell = newRow.createCell(0); String test = mapArray[i]; keyword1.append(test + " "); newCell.setCellValue(test); } } srcFile.close(); mapFile.close(); //FileOutputStream fileOut = new FileOutputStream(new File(newFilePath)); // newWorkbook.write(fileOut); // fileOut.close(); // System.out.print("method2"); } catch (Exception e) { System.out.println(e); } return keyword1.toString().split(" "); }
From source file:Algorithm.SegmentationAndNounFilter.java
public String[] SegmentationNounFilter(String filepath, String filename) { try {/*w w w .j a v a 2 s .c o m*/ String mingciPath = filepath.replace(filename, "???.xlsx"); ICTCLAS50 testICTCLAS50 = new ICTCLAS50(); String argu = "."; if (testICTCLAS50.ICTCLAS_Init(argu.getBytes("GB2312")) == false) { System.out.println("Init Fail"); } else { System.out.println("Init Succeed!"); } StringBuffer input = new StringBuffer(); FileInputStream file = new FileInputStream(new File(filepath)); XSSFWorkbook workbook = new XSSFWorkbook(file); XSSFSheet sheet1 = workbook.getSheetAt(0); Iterator<Row> rowIterator = sheet1.iterator(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); //Row rowNew =sheetNew.createRow(rowNumNew++); //For each row, iterate through all the columns Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); // Cell cellNew =rowNew.createCell(cellNumNew++); //Check the cell type and format accordingly switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: break; case Cell.CELL_TYPE_STRING: input.append(cell.getStringCellValue()); } } //System.out.println(""); } //? byte nativeBytes[] = testICTCLAS50.ICTCLAS_ParagraphProcess(input.toString().getBytes("GB2312"), 0, 1); String nativeStr = new String(nativeBytes, 0, nativeBytes.length, "GB2312"); //xlsx XSSFWorkbook workbookNew = new XSSFWorkbook(); XSSFSheet sheetNew = workbookNew.createSheet("test"); int rowNum = 0; // WritableWorkbook book = Workbook.createWorkbook(new File("n.xls")); // WritableSheet sheet = book.createSheet("num1", 0); Scanner in = new Scanner(nativeStr); int i = 0;// while (in.hasNext()) { String ss = in.next(); Pattern pattern = Pattern.compile("(.+?)/n.*"); Matcher matcher = pattern.matcher(ss); if (matcher.find() && matcher.group(1).length() > 1 && !isDigit(matcher.group(1))) { //label = new jxl.write.Label(0, i, matcher.group(1));//? //sheet.addCell(label); Row rowNew = sheetNew.createRow(rowNum++); Cell cellNew = rowNew.createCell(0); cellNew.setCellValue(matcher.group(1)); //i++; } } // book.write(); // book.close(); FileOutputStream fileOut = new FileOutputStream(new File(mingciPath));//new file workbookNew.write(fileOut); fileOut.close(); //?? file.close(); testICTCLAS50.ICTCLAS_Exit(); } catch (Exception ex) { } return null; }
From source file:Almacen.Existencias.java
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: h = new Herramientas(this.usr, 0); h.session(sessionPrograma);/*from w ww . j a va 2 s. co m*/ javax.swing.JFileChooser jF1 = new javax.swing.JFileChooser(); jF1.setFileFilter(new ExtensionFileFilter("Excel document (*.xls)", new String[] { "xls" })); String ruta = null; 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("Existencias Articulos"); for (int ren = 0; ren < (t_datos.getRowCount() + 1); ren++) { Row fila = hoja.createRow(ren); for (int col = 0; col < t_datos.getColumnCount(); col++) { Cell celda = fila.createCell(col); if (ren == 0) { celda.setCellValue(t_datos.getColumnName(col)); } else { try { celda.setCellValue(t_datos.getValueAt(ren - 1, col).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"); } } } }
From source file:Almacen.Reporte2.java
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed // TODO add your handling code here: h = new Herramientas(this.usr, 0); h.session(sessionPrograma);/*from ww w .j a v a2s . co m*/ javax.swing.JFileChooser jF1 = new javax.swing.JFileChooser(); jF1.setFileFilter(new ExtensionFileFilter("Excel document (*.xls)", new String[] { "xls" })); String ruta = null; 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("reporte2"); for (int ren = 0; ren < (t_datos1.getRowCount() + 1); ren++) { Row fila = hoja.createRow(ren); for (int col = 0; col < t_datos1.getColumnCount(); col++) { Cell celda = fila.createCell(col); if (ren == 0) { celda.setCellValue(t_datos1.getColumnName(col)); } else { try { celda.setCellValue(t_datos1.getValueAt(ren - 1, col).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"); } } } }
From source file:Almacen.Reporte2.java
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed // TODO add your handling code here: h = new Herramientas(this.usr, 0); h.session(sessionPrograma);/*from w ww . j ava2s.c o m*/ javax.swing.JFileChooser jF1 = new javax.swing.JFileChooser(); jF1.setFileFilter(new ExtensionFileFilter("Excel document (*.xls)", new String[] { "xls" })); String ruta = null; 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(); col++) { Cell celda = fila.createCell(col); if (ren == 0) { celda.setCellValue(t_datos.getColumnName(col)); } else { try { celda.setCellValue(t_datos.getValueAt(ren - 1, col).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"); } } } }
From source file:Almacen.Reporte2.java
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed // TODO add your handling code here: h = new Herramientas(this.usr, 0); h.session(sessionPrograma);//w w w . j a v a2 s.c om javax.swing.JFileChooser jF1 = new javax.swing.JFileChooser(); jF1.setFileFilter(new ExtensionFileFilter("Excel document (*.xls)", new String[] { "xls" })); String ruta = null; 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_datos2.getRowCount() + 1); ren++) { Row fila = hoja.createRow(ren); for (int col = 0; col < t_datos2.getColumnCount(); col++) { Cell celda = fila.createCell(col); if (ren == 0) { celda.setCellValue(t_datos2.getColumnName(col)); } else { try { celda.setCellValue(t_datos2.getValueAt(ren - 1, col).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"); } } } }
From source file:amazonreviews.AmazonReviews.java
public static void main(String[] args) throws IOException { // TODO Auto-generated method stub //new AmazonReviews.filea("B00I8BIBCW"); String s1 = "B002RL9CYK"; reviews = new ArrayList<String>(); reviewsDate = new ArrayList<String>(); reviewsStar = new ArrayList<String>(); XSSFWorkbook workbook = new XSSFWorkbook(); //Create a blank sheet XSSFSheet sheet = workbook.createSheet("Employee Data"); //This data needs to be written (Object[]) Map<String, Object[]> data = new TreeMap<String, Object[]>(); data.put("0", new Object[] { "Review Text", "Review Date", "Review Stars" }); for (int i = 1; i <= 100; i++) { GetReviews(s1, Integer.toString(i)); }/*from w w w . j av a2 s . co m*/ for (int i = 0; i < reviews.size(); i++) { data.put(Integer.toString(i + 1), new Object[] { reviews.get(i), reviewsDate.get(i), reviewsStar.get(i) }); } Set<String> keyset = data.keySet(); int rownum = 0; for (String key : keyset) { XSSFRow row = sheet.createRow(rownum++); Object[] objArr = data.get(key); int cellnum = 0; for (Object obj : objArr) { Cell cell = row.createCell(cellnum++); if (obj instanceof String) cell.setCellValue((String) obj); else if (obj instanceof Integer) cell.setCellValue((Integer) obj); } } try { //Write the workbook in file system FileOutputStream out = new FileOutputStream(new File(name + ".xlsx")); workbook.write(out); out.close(); System.out.println("howtodoinjava_demo.xlsx written successfully on disk."); } catch (Exception e) { e.printStackTrace(); } }
From source file:ambit2.core.io.XLSFileWriter.java
License:Open Source License
public void writeMolecule(IMolecule molecule) { Object value;/*from www . j a v a 2 s . com*/ try { //give it a chance to create a header just before the first write if (!writingStarted) { if (header == null) setHeader(molecule.getProperties()); writeHeader(); writingStarted = true; } Row row = sheet.createRow((short) (sheet.getLastRowNum() + 1)); String s; for (int i = 0; i < header.size(); i++) { value = molecule.getProperty(header.list.get(i)); if (i == smilesIndex) { if (value == null) //no SMILES available try { value = sg.createSMILES(molecule); } catch (Exception x) { logger.log(Level.WARNING, "Error while createSMILES\t", x); value = ""; } } if (value != null) { Cell cell = row.createCell((short) (i + 1)); if (value instanceof Number) { cell.setCellStyle(style); cell.setCellType(Cell.CELL_TYPE_NUMERIC); cell.setCellValue(((Number) value).doubleValue()); } else { try { double d = Double.parseDouble(value.toString()); cell.setCellStyle(style); cell.setCellType(Cell.CELL_TYPE_NUMERIC); cell.setCellValue(d); } catch (Exception x) { cell.setCellType(Cell.CELL_TYPE_STRING); cell.setCellValue(value.toString()); } } } } } catch (Exception x) { logger.log(Level.WARNING, "ERROR while writing Molecule: ", x); } }
From source file:android_connector.ConfigWindowController.java
/** * Speichert die Ergebnisse der Lufe als Excel-Tabelle. * * @author Quelle://from ww w . j av a 2 s .co m * http://viralpatel.net/blogs/java-read-write-excel-file-apache-poi/ * @param programmende True, wenn das Programm beendet werden soll, sonst * false. * */ public void printResults(boolean programmende) { /** * Zahl der Messtore. */ int tore = Integer.parseInt(messtore.getText()); /** * Gibt die gespeicherten Werte der DB an. Jedes Unterarray * reprsentiert einen Datensatz. Der zweite Index ist bei 0 die * Startnummer, 1 der Name, 2 die Kategorie, 3 Lauf 1, 4 Lauf 2. */ String[][] werte = (new MySQLConnection(host.getText(), port.getText(), db.getText(), user.getText(), pw.getText(), null)).getAuswertung(starter, tore); //FileChooser einsetzen, um Speicherort zu ermitteln FileChooser fc = new FileChooser(); //Titel anzeigen fc.setTitle("Speicherort fr die Auswertung:"); //standardmig im Home-Verzeichnis starten fc.setInitialDirectory(new File(System.getProperty("user.home"))); //Alle-Dateien-Filter entfernen fc.setSelectedExtensionFilter(null); //FileFilter fr Exceldateien hinzufgen //nur "alte" Excel-Dateien knnen geschrieben werden! fc.getExtensionFilters() .addAll(new FileChooser.ExtensionFilter("Microsoft Excel 1997-2003 Dokument (.xls)", "*.xls")); //Dateien einlesen File returnVal = fc.showSaveDialog(primaryStage); //prfen, ob Datei zurckgegeben --> eine gewhlt; muss aber nicht existieren if (returnVal != null) { /** * Reprsentation der Excel-Datei. */ HSSFWorkbook workbook = new HSSFWorkbook(); /** * Alle Kategorien, die angegeben sind. */ List<String> kategorien = getKategorien(); //alle Kategorien durchgehen, fr alle eine Mappe der DB fllen. for (String kategorie : kategorien) { /** * Reprsentiert die Mappe, in der die Daten landen. */ HSSFSheet sheet; //Prfen, ob die Lnge des Kategorienamens zwischen 1 und 31 liegt --> sonst ungltig if (!kategorie.isEmpty() && kategorie.length() < 31) { //wenn ja: Kategoriename ist Mappenname sheet = workbook.createSheet(kategorie); //sonst: Standardname } else { sheet = workbook.createSheet("namenlose Kategorie"); } Map<String, List<String>> data = new HashMap<String, List<String>>(); List<String> label = new ArrayList<>(); label.add("Startnummer"); label.add("Name"); label.add("Kategorie"); label.add("reine Laufzeit- Lauf 1"); label.add("Gesamtstrafen- Lauf 1"); label.add("Laufzeit insgesamt- Lauf 1"); for (int i = 0; i < tore; i++) { label.add("Strafe Tor " + (i + 1)); } label.add("reine Laufzeit- Lauf 2"); label.add("Gesamtstrafen- Lauf 2"); label.add("Laufzeit insgesamt- Lauf 2"); for (int i = 0; i < tore; i++) { label.add("Strafe Tor " + (i + 1)); } data.put("0", label); for (int i = 0; i < werte.length; i++) { //data.put(""+(i+2), werte[i]); if (werte[i][2] != null) { if (werte[i][2].equals(kategorie)) { List<String> angaben = new ArrayList<>(); angaben.add(werte[i][0]); angaben.add(werte[i][1]); angaben.add(werte[i][2]); String lauf1 = werte[i][3]; if (werte[i][3] != null && !werte[i][3].isEmpty()) { angaben.addAll(extractList(lauf1)); } if (werte[i][4] != null && !werte[i][4].isEmpty()) { angaben.addAll(extractList(werte[i][4])); } data.put("" + (i + 1), angaben); } } } Set<String> keyset = data.keySet(); int rownum = 0; for (String key : keyset) { Row row = sheet.createRow(rownum++); List<String> objArr = data.get(key); int cellnum = 0; for (Object obj : objArr) { Cell cell = row.createCell(cellnum++); if (obj instanceof Date) { cell.setCellValue((Date) obj); } else if (obj instanceof Boolean) { cell.setCellValue((Boolean) obj); } else if (obj instanceof String) { cell.setCellValue((String) obj); } else if (obj instanceof Double) { cell.setCellValue((Double) obj); } } } for (int i = 0; i < 9 + 2 * tore; i++) { sheet.autoSizeColumn(i); } } try { FileOutputStream out = new FileOutputStream(returnVal); workbook.write(out); out.close(); System.out.println("Excel written successfully.."); out = new FileOutputStream(System.getProperty("user.home") + "/Kanu-s.a.M.-Notfall.xls"); workbook.write(out); out.close(); } catch (FileNotFoundException e) { MySQLConnection.staticExceptionDialog(e, "Schreibfehler", "Auswertung konnte nicht geschrieben werden", "Die Excel-Datei mit der Auswertung konnte nicht geschrieben werden. Bitte versuchen Sie es erneut!"); } catch (IOException e) { e.printStackTrace(); } } if (programmende) { Alert alert = new Alert(AlertType.INFORMATION); alert.setTitle("Programmende"); alert.setHeaderText("Der Programmablauf ist beendet."); alert.setContentText( "Das Programm hat seine Aufgabe erfllt und wird nun beendet. Vielen Dank fr die Benutzung des Softwaresystems!"); alert.showAndWait(); Platform.exit(); } }