List of usage examples for org.apache.poi.xssf.streaming SXSSFWorkbook write
@Override public void write(OutputStream stream) throws IOException
From source file:com.romeikat.datamessie.core.base.util.FileUtil.java
License:Open Source License
public synchronized File createXlsxFile(final String dir, String filename, final SXSSFWorkbook xlsxWorkbook) { try {// ww w . jav a 2 s. c o m filename = normalizeFilename(filename); Path file = Paths.get(dir, filename + ".xlsx"); file = getNonExisting(file); Files.createFile(file); final FileOutputStream fileOutputStream = new FileOutputStream(file.toFile()); xlsxWorkbook.write(fileOutputStream); fileOutputStream.close(); return file.toFile(); } catch (final Exception e) { LOG.error("Could not create Excel file", e); return null; } }
From source file:com.sitech.chn.s98800.s98820.s882q.util.XLSXCovertCSVReader.java
License:Apache License
public static void writeToXlSX(HttpServletResponse response, List data, String FileName) throws Exception { String filePath = ServletActionContext.getServletContext().getRealPath("/upload") + "/" + FileName; SXSSFWorkbook wb = new SXSSFWorkbook(10000); File exprotFile = new File(filePath); if (exprotFile.exists()) { exprotFile.delete();/*ww w . jav a 2s . c om*/ exprotFile = new File(filePath); } System.out.println("" + new Date()); FileOutputStream fos = new FileOutputStream(exprotFile); Sheet sh = wb.createSheet(); String[] temp = null; for (int i = 0; i < data.size(); i++) { temp = (String[]) data.get(i); Row row = sh.createRow(i); for (int j = 0; j < temp.length; j++) { Cell cell = row.createCell(j); cell.setCellValue(temp[j] == null ? "" : temp[j].replaceAll("\"", "") + " "); } } wb.write(fos); wb.close();// fos.close(); System.out.println("" + new Date() + exprotFile.getAbsolutePath()); InputStream inStream = new BufferedInputStream(new FileInputStream(exprotFile)); response.reset(); response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setHeader("content-disposition", "attachment; filename=" + URLEncoder.encode(FileName, "UTF-8")); response.addHeader("Content-Length", exprotFile.length() + ""); byte[] b = new byte[1024 * 10]; int len; while ((len = inStream.read(b)) > 0) { response.getOutputStream().write(b, 0, len); } inStream.close(); }
From source file:com.softtek.mdm.web.institution.UserController.java
/** * ?/*from w w w. ja va 2 s .co m*/ * * @param request * @param response * @throws Exception */ @RequestMapping(value = "/getuserexcelmodel", method = RequestMethod.GET) @ResponseBody public void getuserexcelmodel(HttpServletRequest request, HttpServletResponse response) throws Exception { ExportData exportData = new ExportData(); String headers[][] = { { messageSource.getMessage("web.institution.usercontroller.export.excel.label1", null, LocaleContextHolder.getLocale()), "String" }, { messageSource.getMessage("web.institution.usercontroller.export.excel.label2", null, LocaleContextHolder.getLocale()), "String" }, { messageSource.getMessage("web.institution.usercontroller.export.excel.label3", null, LocaleContextHolder.getLocale()), "String" }, { messageSource.getMessage("web.institution.usercontroller.export.excel.label4", null, LocaleContextHolder.getLocale()), "String" }, { messageSource.getMessage("web.institution.usercontroller.export.excel.label5", null, LocaleContextHolder.getLocale()), "String" }, { messageSource.getMessage("web.institution.usercontroller.export.excel.label6", null, LocaleContextHolder.getLocale()), "String" }, { messageSource.getMessage("web.institution.usercontroller.export.excel.label7", null, LocaleContextHolder.getLocale()), "String" }, { messageSource.getMessage("web.institution.usercontroller.export.excel.label8", null, LocaleContextHolder.getLocale()), "String" }, { messageSource.getMessage("web.institution.usercontroller.export.excel.label9", null, LocaleContextHolder.getLocale()), "String" }, { messageSource.getMessage("web.institution.usercontroller.export.excel.label10", null, LocaleContextHolder.getLocale()), "String" }, { messageSource.getMessage("web.institution.usercontroller.export.excel.label11", null, LocaleContextHolder.getLocale()), "String" } }; SXSSFWorkbook workbook = exportData.getwb(headers, "sheet1"); // XSSFWorkbook workbook = new XSSFWorkbook(); response.setCharacterEncoding("UTF-8"); response.setContentType("application/x-msdownload"); OutputStream os = null; String fileName = messageSource.getMessage("web.institution.usercontroller.export.excel.model", null, LocaleContextHolder.getLocale()); response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8")); os = response.getOutputStream(); workbook.write(os); os.flush(); os.close(); }
From source file:com.softtek.mdm.web.institution.UserController.java
/** * /* www. j a v a 2s . co m*/ * * @param request * @param response * @throws Exception */ @RequestMapping(value = "/exportuser", method = RequestMethod.GET) @ResponseBody public void exportuser(String groupid, HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception { @SuppressWarnings("unchecked") List<StructureModel> list = (List<StructureModel>) session .getAttribute(SessionStatus.SOFTTEK_DEPARTMENT.toString()); Integer id = Integer.parseInt(groupid); String name = structureService.queryNameById(id); request.setAttribute("name", name); List<Integer> idList = new ArrayList<Integer>(); structureService.queryAllChildrenId(id, list, idList); idList.add(id); // ?ID? List<UserExportModel> userExportModel = userService.exportUsersById(idList); // ?? for (int i = 0; i < idList.size(); i++) { StructureModel temp = structureService.getParents(idList.get(i)); String belongStr = temp.getName(); if (temp != null) { for (int j = 0; j < userExportModel.size(); j++) { if (userExportModel.get(j).getGroup_id().equals(idList.get(i))) { // String belongStr = temp.getName(); while (temp.getParent() != null) { belongStr = StringUtil.insert(belongStr, temp.getParent().getName() + "/"); temp = temp.getParent(); } userExportModel.get(j).setGroup_name(belongStr); } } } } ExportData exportData = new ExportData(); String headers[][] = { { messageSource.getMessage("web.institution.usercontroller.export.users.label1", null, LocaleContextHolder.getLocale()), "String" }, { messageSource.getMessage("web.institution.usercontroller.export.users.label2", null, LocaleContextHolder.getLocale()), "String" }, { messageSource.getMessage("web.institution.usercontroller.export.users.label3", null, LocaleContextHolder.getLocale()), "String" }, { messageSource.getMessage("web.institution.usercontroller.export.users.label4", null, LocaleContextHolder.getLocale()), "String" }, { messageSource.getMessage("web.institution.usercontroller.export.users.label5", null, LocaleContextHolder.getLocale()), "String" }, { messageSource.getMessage("web.institution.usercontroller.export.users.label6", null, LocaleContextHolder.getLocale()), "String" }, { messageSource.getMessage("web.institution.usercontroller.export.users.label7", null, LocaleContextHolder.getLocale()), "String" } }; SXSSFWorkbook workbook = exportData.getwb(headers, "sheet1"); int currentRow = 1; Sheet sheet = workbook.getSheetAt(0); CellStyle cellStyle = workbook.createCellStyle(); // cellStyle.setAlignment(CellStyle.ALIGN_CENTER); for (int i = 0; i < userExportModel.size(); i++) { Row row = sheet.createRow(currentRow); for (int j = 0; j < 7; j++) { Cell cell = row.createCell(j); if (j == 0) { cell.setCellValue(userExportModel.get(i).getGroup_name()); cell.setCellStyle(cellStyle); } if (j == 1) { cell.setCellValue(userExportModel.get(i).getUser_name()); cell.setCellStyle(cellStyle); } if (j == 2) { cell.setCellValue(userExportModel.get(i).getReal_name()); cell.setCellStyle(cellStyle); } if (j == 3) { cell.setCellValue(userExportModel.get(i).getPhone()); cell.setCellStyle(cellStyle); } if (j == 4) { cell.setCellValue(userExportModel.get(i).getEmail()); cell.setCellStyle(cellStyle); } if (j == 5) { cell.setCellValue(userExportModel.get(i).getMark()); cell.setCellStyle(cellStyle); } if (j == 6) { String sex = messageSource.getMessage("web.institution.usercontroller.sex.woman", null, LocaleContextHolder.getLocale()); if (userExportModel.get(i).getGender().equals("1")) { sex = messageSource.getMessage("web.institution.usercontroller.sex.man", null, LocaleContextHolder.getLocale()); } cell.setCellValue(sex); cell.setCellStyle(cellStyle); } } currentRow++; } // XSSFWorkbook workbook = new XSSFWorkbook(); response.setCharacterEncoding("UTF-8"); response.setContentType("application/x-msdownload"); OutputStream os = null; String fileName = messageSource.getMessage("web.institution.usercontroller.export.users.model", null, LocaleContextHolder.getLocale()); response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8")); os = response.getOutputStream(); workbook.write(os); os.flush(); os.close(); }
From source file:ec.tss.sa.output.SpreadsheetOutput.java
License:EUPL
@Override public void end(Object context) throws Exception { String file = new File(folder_, config_.getFileName()).getAbsolutePath(); file = Paths.changeExtension(file, "xlsx"); File ssfile = new File(file); //File ssfile = new File("C:\\test.xls"); SXSSFWorkbook workbook = new SXSSFWorkbook(null, 100, false, true); try (FileOutputStream stream = new FileOutputStream(ssfile)) { switch (config_.getLayout()) { case ByComponent: { HashMap<String, List<NamedObject<TsData>>> allData = new HashMap<>(); for (DefaultSummary summary : summaries_) { for (Entry<String, TsData> keyValue : summary.getAllSeries().entrySet()) { List<NamedObject<TsData>> list = null; if (!allData.containsKey(keyValue.getKey())) { list = new ArrayList<>(); allData.put(keyValue.getKey(), list); } else { list = allData.get(keyValue.getKey()); }/*from w ww . j a va 2s.co m*/ String name; if (fullName) { name = MultiLineNameUtil.join(summary.getName(), " * "); } else { name = MultiLineNameUtil.last(summary.getName()); } list.add(new NamedObject<>(name, keyValue.getValue())); } } for (Entry<String, List<NamedObject<TsData>>> keyValue : allData.entrySet()) { TsDataTable byComponentTable = new TsDataTable(); List<NamedObject<TsData>> value = keyValue.getValue(); String[] headers = new String[value.size()]; for (int i = 0; i < headers.length; i++) { NamedObject<TsData> data = value.get(i); headers[i] = data.name; byComponentTable.insert(-1, data.object); } //ADD SHEET XSSFHelper.addSheet(workbook, keyValue.getKey(), new String[] { keyValue.getKey() }, headers, byComponentTable, config_.isVerticalOrientation()); } break; } case BySeries: { for (int i = 0; i < summaries_.size(); i++) { DefaultSummary summary = summaries_.get(i); Set<Entry<String, TsData>> tmp = summary.getAllSeries().entrySet(); TsDataTable bySeriesTable = new TsDataTable(); String[] componentHeaders = new String[tmp.size()]; int j = 0; for (Entry<String, TsData> keyValue : tmp) { componentHeaders[j++] = keyValue.getKey(); bySeriesTable.insert(-1, keyValue.getValue()); } //ADD SHEET String name; if (fullName) { name = MultiLineNameUtil.join(summary.getName(), " * "); } else { name = MultiLineNameUtil.last(summary.getName()); } XSSFHelper.addSheet(workbook, "Series" + Integer.toString(i), new String[] { name }, componentHeaders, bySeriesTable, config_.isVerticalOrientation()); } break; } case OneSheet: { List<String> headers0 = new ArrayList<>(); List<String> headers1 = new ArrayList<>(); TsDataTable oneSheetTable = new TsDataTable(); for (DefaultSummary summary : summaries_) { String name; if (fullName) { name = MultiLineNameUtil.join(summary.getName(), " * "); } else { name = MultiLineNameUtil.last(summary.getName()); } headers0.add(name); Map<String, TsData> data = summary.getAllSeries(); for (Entry<String, TsData> keyValue : data.entrySet()) { headers1.add(keyValue.getKey()); oneSheetTable.insert(-1, keyValue.getValue()); } for (int i = 1; i < data.size(); i++) { headers0.add(""); } } //ADD SHEET XSSFHelper.addSheet(workbook, "Series", Iterables.toArray(headers0, String.class), Iterables.toArray(headers1, String.class), oneSheetTable, config_.isVerticalOrientation()); break; } } workbook.write(stream); } finally { workbook.dispose(); } }
From source file:ec.util.spreadsheet.poi.ExcelBookFactory.java
License:EUPL
@Override public void store(OutputStream stream, Book book) throws IOException { // Currenty, inline string is not supported in FastPoiBook -> use of shared strings table SXSSFWorkbook target = new SXSSFWorkbook(null, 100, false, true); try {/*ww w.ja v a2 s.c o m*/ PoiBookWriter.copy(book, target); target.write(stream); } finally { // dispose of temporary files backing this workbook on disk target.dispose(); } }
From source file:edu.harvard.hms.dbmi.bd2k.irct.ws.rs.resultconverter.XSLXTabularDataConverter.java
License:Mozilla Public License
@Override public StreamingOutput createStream(final Result result) { StreamingOutput stream = new StreamingOutput() { @Override//from www . j a v a 2 s .c o m public void write(OutputStream outputStream) throws IOException, WebApplicationException { ResultSet rs = null; SXSSFWorkbook wb = null; try { rs = (ResultSet) result.getData(); rs.load(result.getResultSetLocation()); wb = new SXSSFWorkbook(100); // Create Sheet Sheet sh = wb.createSheet("Results"); // Create Header CellStyle headerStyle = wb.createCellStyle(); Font font = wb.createFont(); font.setBoldweight(Font.BOLDWEIGHT_BOLD); headerStyle.setFont(font); Row headerRow = sh.createRow(0); for (int i = 0; i < rs.getColumnSize(); i++) { Cell cell = headerRow.createCell(i); cell.setCellStyle(headerStyle); cell.setCellValue(rs.getColumn(i).getName()); } // Add data rs.beforeFirst(); int rowNum = 1; while (rs.next()) { Row row = sh.createRow(rowNum); for (int i = 0; i < rs.getColumnSize(); i++) { String value = rs.getString(i); Cell cell = row.createCell(i); if (value != null) { cell.setCellValue(rs.getString(i)); } } rowNum++; } wb.write(outputStream); } catch (ResultSetException | PersistableException e) { log.info("Error creating XSLX Stream: " + e.getMessage()); } finally { if (wb != null) { wb.close(); } if (rs != null && !rs.isClosed()) { try { rs.close(); } catch (ResultSetException e) { e.printStackTrace(); } } if (outputStream != null) { outputStream.close(); } } } }; return stream; }
From source file:excelmasivo.ExcelMasivo.java
/** * @param args the command line arguments *///from w w w . jav a 2 s . c o m public static void main(String[] args) { String driver = "oracle.jdbc.OracleDriver"; String user = "DRKL"; String pass = "DRKL"; String url = "jdbc:oracle:thin:@localhost:1521:XE"; String query = "SELECT * FROM PRODUCTOS ORDER BY TO_NUMBER(SUBSTR(CODIGO_PRODUCTO,7))"; Connection con; Statement st; ResultSet rs; ResultSetMetaData rsm; SXSSFWorkbook libro = new SXSSFWorkbook(); SXSSFSheet hoja = libro.createSheet("Reporte"); SXSSFRow fila; SXSSFCell celda; FileOutputStream out; int x = 0; CellStyle cs = libro.createCellStyle(); cs.getFillForegroundColor(); Font f = libro.createFont(); //f.setBoldweight(Font.BOLDWEIGHT_BOLD); f.setFontHeightInPoints((short) 12); cs.setFont(f); try { Class.forName(driver); con = DriverManager.getConnection(url, user, pass); st = con.createStatement(); rs = st.executeQuery(query); rsm = rs.getMetaData(); while (rs.next()) { //crear la fila fila = hoja.createRow(x++); for (int i = 1; i <= rsm.getColumnCount(); i++) { //recorrer las columnas celda = fila.createCell(i); celda.setCellStyle(cs); celda.setCellValue(rs.getString(i)); //System.out.print(rs.getString(i)); } //System.out.println(); if (x % 50000 == 0) { System.out.println("Se procesaron:" + x); } } out = new FileOutputStream(new File("D:\\java\\Productos_" + GregorianCalendar.MILLISECOND + ".xlsx")); libro.write(out); out.close(); System.out.println("Archivo generado con exito"); } catch (ClassNotFoundException | SQLException | FileNotFoundException ex) { Logger.getLogger(ExcelMasivo.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ExcelMasivo.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:exporter.ExcelExporter.java
public static void writeXlsx(OutputStream outputStream, String dbResource, String queryString, String... args) throws NamingException { Context initContext = null;/*from ww w.j a v a 2s. co m*/ try { initContext = new InitialContext(); } catch (NamingException ex) { Logger.getLogger(ExcelExporter.class.getName()).log(Level.SEVERE, null, ex); } Context envContext = (Context) initContext.lookup("java:/comp/env/"); DataSource datasource = (DataSource) envContext.lookup(dbResource); try { PreparedStatement ps = datasource.getConnection().prepareStatement(queryString); ResultSet rSet = ps.executeQuery(); ResultSetMetaData rsMetaData = rSet.getMetaData(); int columnCount = rsMetaData.getColumnCount(); SXSSFWorkbook workBook = new SXSSFWorkbook(); SXSSFSheet sheet = (SXSSFSheet) workBook.createSheet("cics"); String currentLine = null; int rowNum = 0; int types[] = new int[columnCount]; Row intestazione = sheet.createRow(rowNum); for (int i = 0; i < columnCount; i++) { intestazione.createCell(i).setCellValue(rsMetaData.getColumnLabel(i + 1)); types[i] = rsMetaData.getColumnType(i + 1); } rowNum++; while (rSet.next()) { rowNum++; Row currentRow = sheet.createRow(rowNum); for (int k = 0; k < columnCount; k++) { switch (types[k]) { case Types.INTEGER: currentRow.createCell(k).setCellValue(rSet.getInt(k + 1)); break; case Types.FLOAT: currentRow.createCell(k).setCellValue(rSet.getFloat(k + 1)); break; case Types.BIGINT: currentRow.createCell(k).setCellValue(rSet.getInt(k + 1)); break; case Types.DOUBLE: currentRow.createCell(k).setCellValue(rSet.getDouble(k + 1)); break; case Types.DATE: currentRow.createCell(k).setCellValue(rSet.getDate(k + 1)); break; case Types.TIMESTAMP: currentRow.createCell(k).setCellValue(rSet.getTimestamp(k + 1)); break; default: currentRow.createCell(k).setCellValue(rSet.getString(k + 1)); break; } currentRow.createCell(k).setCellValue(rSet.getString(k + 1)); } } try { workBook.write(outputStream); } catch (IOException ex) { Logger.getLogger(ExcelExporter.class.getName()).log(Level.SEVERE, null, ex); } } catch (SQLException ex) { Logger.getLogger(ExcelExporter.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:exporter.XlsxExporter.java
public static void writeXLSX(OutputStream outputStream, String resourceDbPath, String queryString, String... args) {//from ww w . j a v a 2 s . c om try { ResourceBundle rb = ResourceBundle.getBundle(resourceDbPath); Class.forName(rb.getString("driver")); Connection conn = DriverManager.getConnection(rb.getString("url"), rb.getString("user"), rb.getString("password")); PreparedStatement pStatement = conn.prepareStatement(queryString, java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY); int paramCount = 1; for (String arg : args) { pStatement.setString(paramCount++, arg); } ResultSet rSet = pStatement.executeQuery(); ResultSetMetaData rsMetaData = rSet.getMetaData(); int columnCount = rsMetaData.getColumnCount(); SXSSFWorkbook workBook = new SXSSFWorkbook(); SXSSFSheet sheet = (SXSSFSheet) workBook.createSheet("cics"); String currentLine = null; int rowNum = 0; int types[] = new int[columnCount]; Row intestazione = sheet.createRow(rowNum); for (int i = 0; i < columnCount; i++) { intestazione.createCell(i).setCellValue(rsMetaData.getColumnLabel(i + 1)); types[i] = rsMetaData.getColumnType(i + 1); } rowNum++; while (rSet.next()) { rowNum++; Row currentRow = sheet.createRow(rowNum); for (int k = 0; k < columnCount; k++) { switch (types[k]) { case Types.INTEGER: currentRow.createCell(k).setCellValue(rSet.getInt(k + 1)); break; case Types.FLOAT: currentRow.createCell(k).setCellValue(rSet.getFloat(k + 1)); break; case Types.BIGINT: currentRow.createCell(k).setCellValue(rSet.getInt(k + 1)); break; case Types.DOUBLE: currentRow.createCell(k).setCellValue(rSet.getDouble(k + 1)); break; case Types.DATE: currentRow.createCell(k).setCellValue(rSet.getDate(k + 1)); break; case Types.TIMESTAMP: currentRow.createCell(k).setCellValue(rSet.getTimestamp(k + 1)); break; default: currentRow.createCell(k).setCellValue(rSet.getString(k + 1)); break; } currentRow.createCell(k).setCellValue(rSet.getString(k + 1)); } } rSet.close(); pStatement.close(); conn.close(); workBook.write(outputStream); System.out.println("Done"); } catch (ClassNotFoundException ex) { System.out.println(ex.getMessage() + "Exception in try"); } catch (SQLException ex) { System.out.println(ex.getMessage() + "Exception in try"); } catch (IOException ex) { System.out.println(ex.getMessage() + "Exception in try"); } }