@Test public void test() throws IOException { HSSFWorkbook workbook = createWorkbook(); byte[] buffer; try (ByteArrayOutputStream stream = new ByteArrayOutputStream(1024)) { workbook.write(stream); stream.flush(); buffer = stream.toByteArray(); } Map<String, BoundaryPoint> boundaryPoints; try (InputStream stream = new ByteArrayInputStream(buffer)) { BoundaryPointXlsParser parser = new BoundaryPointXlsParser(); boundaryPoints = parser.parse(stream); } assertEquals(1, boundaryPoints.size()); BoundaryPoint point = boundaryPoints.get("BoundaryPoint FR-BE"); assertNotNull(point); assertEquals("BoundaryPoint FR-BE", point.getName()); assertEquals(Country.FR, point.getBorderFrom()); assertEquals(Country.BE, point.getBorderTo()); }
/** * 获取单元格式样式 * * @param wb * @param color * @return */ private static HSSFCellStyle getCellStyle(HSSFWorkbook wb, int color) { if (STYLE_MAP.get(color) != null) { return STYLE_MAP.get(color); } HSSFCellStyle style = wb.createCellStyle(); if (color != -1) { style.setFillForegroundColor(Short.valueOf(color + "")); style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); style.setAlignment(CellStyle.ALIGN_CENTER); } style.setBorderBottom(CellStyle.BORDER_THIN); style.setBorderLeft(CellStyle.BORDER_THIN); style.setBorderRight(CellStyle.BORDER_THIN); style.setBorderTop(CellStyle.BORDER_THIN); style.setBottomBorderColor(HSSFColor.BLACK.index); style.setLeftBorderColor(HSSFColor.BLACK.index); style.setRightBorderColor(HSSFColor.BLACK.index); style.setTopBorderColor(HSSFColor.BLACK.index); STYLE_MAP.put(color, style); return style; }
private void insertItemToSheet(String table, HSSFSheet sheet, ArrayList<String> columns) { HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); Cursor cursor = database.rawQuery("select * from " + table, null); cursor.moveToFirst(); int n = 1; while (!cursor.isAfterLast()) { HSSFRow rowA = sheet.createRow(n); for (int j = 0; j < columns.size(); j++) { HSSFCell cellA = rowA.createCell(j); if (cursor.getType(j) == Cursor.FIELD_TYPE_BLOB) { HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) j, n, (short) (j + 1), n + 1); anchor.setAnchorType(3); patriarch.createPicture(anchor, workbook.addPicture(cursor.getBlob(j), HSSFWorkbook.PICTURE_TYPE_JPEG)); } else { cellA.setCellValue(new HSSFRichTextString(cursor.getString(j))); } } n++; cursor.moveToNext(); } cursor.close(); }
private HSSFCellStyle createHSSFCellStyle(Workbook wb, int[] bgColor, int[] fontColor, int fontSize) { HSSFWorkbook workbook = (HSSFWorkbook) wb; HSSFPalette palette = workbook.getCustomPalette(); palette.setColorAtIndex((short) 9, (byte) fontColor[0], (byte) fontColor[1], (byte) fontColor[2]); palette.setColorAtIndex((short) 10, (byte) bgColor[0], (byte) bgColor[1], (byte) bgColor[2]); HSSFFont titleFont = workbook.createFont(); titleFont.setCharSet(HSSFFont.DEFAULT_CHARSET); titleFont.setFontName("宋体"); titleFont.setColor((short) 9); titleFont.setBold(true); titleFont.setFontHeightInPoints((short) fontSize); HSSFCellStyle titleStyle = (HSSFCellStyle) createBorderCellStyle(workbook, true); titleStyle.setFont(titleFont); titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); titleStyle.setFillForegroundColor((short) 10); titleStyle.setAlignment(HorizontalAlignment.CENTER); titleStyle.setVerticalAlignment(VerticalAlignment.CENTER); return titleStyle; }
/** * Read the Excel 2003-2007 * * @param path * the path of the Excel * @return * @throws IOException */ public static String readXls(String path) throws IOException { InputStream is = new FileInputStream(path); HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is); StringBuffer sb = new StringBuffer(""); // Read the Sheet for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) { HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet); if (hssfSheet == null) { continue; } // Read the Row for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) { HSSFRow hssfRow = hssfSheet.getRow(rowNum); if (hssfRow != null) { HSSFCell no = hssfRow.getCell(0); HSSFCell name = hssfRow.getCell(1); sb.append(no + ":" + name); sb.append(";"); } } } return sb.toString().substring(0, sb.toString().length() - 1); }
public Map<String, BoundaryPoint> parse(InputStream is) throws IOException { Map<String, BoundaryPoint> boundaryPoints = new HashMap<>(); HSSFWorkbook workbook = new HSSFWorkbook(is); HSSFSheet sheet = workbook.getSheetAt(0); Iterator<Row> rowIterator = sheet.iterator(); rowIterator.next(); rowIterator.next(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); Cell boundaryPointNameCell = row.getCell(13); Cell borderFromCell = row.getCell(14); Cell borderToCell = row.getCell(15); String boundaryPointName = boundaryPointNameCell.getStringCellValue(); if (boundaryPointName.equals("-")) { continue; } Country borderFrom = toCountry(borderFromCell.getStringCellValue()); Country borderTo = toCountry(borderToCell.getStringCellValue()); boundaryPoints.put(boundaryPointName, new BoundaryPoint(boundaryPointName, borderFrom, borderTo)); } return boundaryPoints; }
/** * 导出Excel对象 * * @param sheetDataListArr Excel数据 * @return */ public static Workbook exportWorkbook(List<?>... sheetDataListArr){ // data array valid if (sheetDataListArr==null || sheetDataListArr.length==0) { throw new RuntimeException(">>>>>>>>>>> xxl-excel error, data array can not be empty."); } // book (HSSFWorkbook=2003/xls、XSSFWorkbook=2007/xlsx) Workbook workbook = new HSSFWorkbook(); // sheet for (List<?> dataList: sheetDataListArr) { makeSheet(workbook, dataList); } return workbook; }
/** * 构造函数 * * @param fileName 导入文件对象 * @param headerNum 标题行号,数据行号=标题行号+1 * @param sheetIndex 工作表编号 * @throws InvalidFormatException * @throws IOException */ public ImportExcel(String fileName, InputStream is, int headerNum, int sheetIndex) throws InvalidFormatException, IOException { if (StringUtils.isBlank(fileName)) { throw new RuntimeException("Import file is empty!"); } else if (fileName.toLowerCase().endsWith("xls")) { this.wb = new HSSFWorkbook(is); } else if (fileName.toLowerCase().endsWith("xlsx")) { this.wb = new XSSFWorkbook(is); } else { throw new RuntimeException("Invalid import file type!"); } if (this.wb.getNumberOfSheets() < sheetIndex) { throw new RuntimeException("No sheet in Import file!"); } this.sheet = this.wb.getSheetAt(sheetIndex); this.headerNum = headerNum; log.debug("Initialize success."); }
public byte[] createExcel() throws IOException, ObjectNotFoundException { String selectedLanguage = model.getSelectedLanguageCode(); Map<String, Properties> localizedProperties = new HashMap<String, Properties>(); List<POLocalizedData> poLocalizedDatas = getLocalizedDataService() .exportProperties(selectedLanguage); Workbook wb = new HSSFWorkbook(); List<Locale> locales = generateLocaleList(); for (POLocalizedData data : poLocalizedDatas) { localizedProperties = data.getPropertiesMap(); if (data.getType().equals(LocalizedDataType.MessageProperties)) { createSheet(localizedProperties, wb, BaseBean.LABEL_USERINTERFACE_TRANSLARIONS, locales); } if (data.getType().equals(LocalizedDataType.MailProperties)) { createSheet(localizedProperties, wb, BaseBean.LABEL_MAIL_TRANSLARIONS, locales); } if (data.getType().equals(LocalizedDataType.PlatformObjects)) { createSheet(localizedProperties, wb, BaseBean.LABEL_PLATFORM_TRANSLARIONS, locales); } } return createByteArrayForWorkbook(wb); }
/** * 获取合并单元格式 * * @param sheet * @param row * @param columnFrom * @param columnTo * @return */ private static void setRegionBorder(HSSFSheet sheet, int row, int columnFrom, int columnTo) { CellRangeAddress region = new CellRangeAddress(row, row, columnFrom, columnTo); sheet.addMergedRegion(region); final short border = CellStyle.BORDER_THIN; HSSFWorkbook wb = sheet.getWorkbook(); RegionUtil.setBorderBottom(border, region, sheet, wb); RegionUtil.setBorderTop(border, region, sheet, wb); RegionUtil.setBorderLeft(border, region, sheet, wb); RegionUtil.setBorderRight(border, region, sheet, wb); RegionUtil.setBottomBorderColor(HSSFColor.BLACK.index, region, sheet, wb); RegionUtil.setTopBorderColor(HSSFColor.BLACK.index, region, sheet, wb); RegionUtil.setLeftBorderColor(HSSFColor.BLACK.index, region, sheet, wb); RegionUtil.setRightBorderColor(HSSFColor.BLACK.index, region, sheet, wb); }
public static void writeXLSFile() throws IOException { HSSFWorkbook wbObj = new HSSFWorkbook(); HSSFSheet sheet = wbObj.createSheet(sheetName); for (int row = 0; row < tableData.size(); row++) { HSSFRow rowObj = sheet.createRow(row); rowData = tableData.get(row); for (int col = 0; col < rowData.size(); col++) { HSSFCell cellObj = rowObj.createCell(col); cellObj.setCellValue(rowData.get(col)); } } FileOutputStream fileOut = new FileOutputStream(excelFileName); wbObj.write(fileOut); wbObj.close(); fileOut.flush(); fileOut.close(); }
/** * {@inheritDoc} */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { List<PollOption> results = null; try { Long pollId = (Long) req.getSession().getAttribute("pollID"); results = DAOProvider.getDao().getPollOptions(pollId); } catch (Exception ex) { results = new ArrayList<>(); } HSSFWorkbook workbook = DBUtility.getXLS(results); resp.setContentType("application/vnd.ms-excel"); resp.setHeader("Content-Disposition", "attachment; filename=votingResults.xls"); workbook.write(resp.getOutputStream()); workbook.close(); }
/** * Creates XLS document from given list of {@link PollOption} objects. * * @param results List of {@link PollOption} objects. * @return XLS document. */ public static HSSFWorkbook getXLS(List<PollOption> results) { HSSFWorkbook document = new HSSFWorkbook(); HSSFSheet sheet = document.createSheet("Results"); HSSFRow rowhead = sheet.createRow(0); rowhead.createCell(0).setCellValue("Ime opcije:"); rowhead.createCell(1).setCellValue("Broj glasova:"); for (int i = 0; i < results.size(); i++) { HSSFRow row = sheet.createRow(i + 1); row.createCell(0).setCellValue(results.get(i).getName()); row.createCell(1).setCellValue( Double.valueOf(results.get(i).getVotes())); } return document; }
/** * Creates XLS document based on given input parameters. * * @param a Start number. * @param b End number. * @param n Last power. * @return Created XLS document. */ private HSSFWorkbook getXLS(Integer a, Integer b, Integer n) { HSSFWorkbook workbook = new HSSFWorkbook(); for (int i = 1; i <= n; i++) { HSSFSheet sheet = workbook.createSheet(i + "-th power."); HSSFRow rowHead = sheet.createRow(0); rowHead.createCell(0).setCellValue("x"); rowHead.createCell(1).setCellValue("x^" + i); int rowCounter = 1; for (int j = a; j <= b; j++) { HSSFRow row = sheet.createRow(rowCounter++); row.createCell(0).setCellValue(Double.valueOf(j)); row.createCell(1).setCellValue(Math.pow(Double.valueOf(j), i)); } } return workbook; }
/** * {@inheritDoc} */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String definitionFile = req.getServletContext().getRealPath( "/WEB-INF/glasanje-definicija.txt"); String resultFile = req.getServletContext().getRealPath( "/WEB-INF/glasanje-rezultati.txt"); List<Band> results = ServerUtilty .getResults(definitionFile, resultFile); HSSFWorkbook workbook = ServerUtilty.getXLS(results); resp.setContentType("application/vnd.ms-excel"); resp.setHeader("Content-Disposition", "attachment; filename=votingResults.xls"); workbook.write(resp.getOutputStream()); workbook.close(); }
/** * Creates XLS document based from given list of bands. * * @param results List of bands. * @return XLS document. */ public static HSSFWorkbook getXLS(List<Band> results) { HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("Voting results"); HSSFRow rowHead = sheet.createRow(0); rowHead.createCell(0).setCellValue("Band name:"); rowHead.createCell(1).setCellValue("Number of votes:"); for (int i = 0, size = results.size(); i < size; i++) { HSSFRow row = sheet.createRow(i + 1); row.createCell(0).setCellValue(results.get(i).getName()); row.createCell(1).setCellValue( Double.valueOf(results.get(i).getVotes())); } return workbook; }
/** * 创建颜色。 * * 写本方法的原因是:从2003版本的模板中复制单元格颜色时,会出现颜色失真的问题。 * * 但最终也没有解决。因为:当单元格的颜色设置为非标准颜色时,就会失真,但设置为标准颜色时,是正常的。 * * 也因为此,本方法与 i_ToCellStyle.setFillBackgroundColor(i_FromCellStyle.getFillBackgroundColor()); 的效果是相同的。 * * 本方法作为研究使用而保留下来,但不没有使用价值。 * * @author ZhengWei(HY) * @createDate 2017-03-21 * @version v1.0 * * @param i_FromColor * @param i_DataWorkbook * @return */ @Deprecated public final static HSSFColor createColor(HSSFColor i_FromColor ,HSSFWorkbook i_DataWorkbook) { short [] v_RGBHex = i_FromColor.getTriplet(); byte v_ByteRed = (byte)v_RGBHex[0]; byte v_ByteGreen = (byte)v_RGBHex[1]; byte v_ByteBlue = (byte)v_RGBHex[2]; HSSFPalette v_Palette = i_DataWorkbook.getCustomPalette(); HSSFColor v_DataColor = v_Palette.findColor(v_ByteRed ,v_ByteGreen ,v_ByteBlue); if ( v_DataColor == null ) { v_Palette.setColorAtIndex(i_FromColor.getIndex() ,v_ByteRed ,v_ByteGreen ,v_ByteBlue); return v_Palette.getColor(i_FromColor.getIndex()); } return v_DataColor; }
/** * 构造函数 * * @param path 导入文件对象 * @param headerNum 标题行号,数据行号=标题行号+1 * @param sheetIndex 工作表编号 * @throws InvalidFormatException * @throws IOException */ public ImportExcel(String fileName, InputStream is, int headerNum, int sheetIndex) throws InvalidFormatException, IOException { if (StringUtils.isBlank(fileName)) { throw new RuntimeException("导入文档为空!"); } else if (fileName.toLowerCase().endsWith("xls")) { this.wb = new HSSFWorkbook(is); } else if (fileName.toLowerCase().endsWith("xlsx")) { this.wb = new XSSFWorkbook(is); } else { throw new RuntimeException("文档格式不正确!"); } if (this.wb.getNumberOfSheets() < sheetIndex) { throw new RuntimeException("文档中没有工作表!"); } this.sheet = this.wb.getSheetAt(sheetIndex); this.headerNum = headerNum; log.debug("Initialize success."); }
@Test public void test2() throws IOException { User user = new User("小红", "女", new Date()); user.setPet(new Pet("小猫", new Date())); user.setAge(90); user.setAddress("uiijji"); List<User> list = new ArrayList<User>(); list.add(user); Workbook workbook = new HSSFWorkbook(); // workbook File file = new File("C:\\Users\\h_kx1\\Desktop\\test.xls"); OutputStream os = new FileOutputStream(file); WriteExcelUtils.writeWorkBook(workbook, list); WriteExcelUtils.writeWorkBookToExcel(workbook, os); CommonUtils.closeIOStream(null, os); }
private Sheet createSheet(HSSFWorkbook wb,Paper paper,String name){ Sheet sheet = null; if(name==null){ sheet=wb.createSheet(); }else{ sheet=wb.createSheet(name); } PaperType paperType=paper.getPaperType(); HSSFPrintSetup printSetup=(HSSFPrintSetup)sheet.getPrintSetup(); Orientation orientation=paper.getOrientation(); if(orientation.equals(Orientation.landscape)){ printSetup.setLandscape(true); } setupPaper(paperType, printSetup); int leftMargin=paper.getLeftMargin(); int rightMargin=paper.getRightMargin(); int topMargin=paper.getTopMargin(); int bottomMargin=paper.getBottomMargin(); sheet.setMargin(Sheet.LeftMargin, UnitUtils.pointToInche(leftMargin)); sheet.setMargin(Sheet.RightMargin, UnitUtils.pointToInche(rightMargin)); sheet.setMargin(Sheet.TopMargin, UnitUtils.pointToInche(topMargin)); sheet.setMargin(Sheet.BottomMargin, UnitUtils.pointToInche(bottomMargin)); return sheet; }
private void exportTables(List<String> tables, final String fileName) throws Exception { workbook = new HSSFWorkbook(); for (int i = 0; i < tables.size(); i++) { if (!tables.get(i).equals("android_metadata")) { HSSFSheet sheet = workbook.createSheet(tables.get(i)); createSheet(tables.get(i), sheet); } } File file = new File(mExportPath, fileName); FileOutputStream fos = new FileOutputStream(file); workbook.write(fos); fos.flush(); fos.close(); workbook.close(); database.close(); }
private void createExcel(OutputStream out, IDocument doc, WebInput wi) throws IOException, ServletException { this.setContentType("application/vnd.ms-excel"); HSSFWorkbook wb = new HSSFWorkbook(); DocInfo di = new DocInfo(IDocument.TYPE_MS_EXCEL); try { di.setExcelDocument(wb); doc.createContent(wi, di); wb.write(out); } catch (Exception e) { throw new ServletException(e); } finally { if (out != null) { out.flush(); out.close(); out = null; } di = null; doc = null; wb = null; } }
/** * Write the value to the cell. Override this method if you have complex data types that may need to be exported. * @param value the value of the cell * @param cell the cell to write it to */ protected void writeCell(Object value, HSSFCell cell, HSSFWorkbook wb) { if (value instanceof Number) { Number num = (Number) value; cell.setCellValue(num.doubleValue()); } else if (value instanceof Date) { HSSFCellStyle cellStyle = wb.createCellStyle(); cellStyle.setDataFormat( wb.getCreationHelper().createDataFormat().getFormat("dd/MM/yyyy HH:mm")); cell.setCellStyle(cellStyle); cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC); cell.setCellValue((Date) value); } else if (value instanceof Calendar) { cell.setCellValue((Calendar) value); } else { cell.setCellValue(new HSSFRichTextString(escapeColumnValue(value))); } }
/** * Get Workbook * * @param completeFilePath * @param fileExtension * @return workbook * @throws ParserException */ private Workbook getWorkbook(File completeFilePath, String fileExtension) throws ParserException { /* Open & Read File */ try (FileInputStream inputStream = new FileInputStream(completeFilePath)) { /* Get Type Based On File Extension */ return fileExtension.equals(Constants.EXT_XLSX) ? (XSSFWorkbook) WorkbookFactory .create(inputStream) : fileExtension .equals(Constants.EXT_XLS) ? (HSSFWorkbook) WorkbookFactory .create(inputStream) : null; } catch (Exception ex) { /* Catch, Log & Throw Exception */ LOGGER.error("Error Occured While Parsing File!", ex); throw new ParserException(exceptionFactory.create( ExceptionType.PARSER, "PAR003", completeFilePath.getAbsolutePath()), ex); } }
public void setImage(final HSSFWorkbook workbook, final HSSFSheet sheet) { final CellLocation cellLocation = POIUtils.findMatchCell(sheet, "\\" + KEYWORD_ER + ".*"); if (cellLocation != null) { int width = -1; int height = -1; final String value = POIUtils.getCellValue(sheet, cellLocation); final int startIndex = value.indexOf("("); if (startIndex != -1) { final int middleIndex = value.indexOf(",", startIndex + 1); if (middleIndex != -1) { width = Integer.parseInt(value.substring(startIndex + 1, middleIndex).trim()); height = Integer.parseInt(value.substring(middleIndex + 1, value.length() - 1).trim()); } } this.setImage(workbook, sheet, cellLocation, width, height); } }
/** エクセル出力 */ @Execute(validator = false) public String createExcel(){ ExcelDto dto = new ExcelDto(); dto.setMeetingName(partyDto.meetingName); dto.setMemberList(partyDto.tMemberOn); HSSFWorkbook wb = excelFpao.excelTemplate(dto); httpServletResponse.setHeader( "Content-Disposition", "attachment; filename=" + partyDto.meetingName + System.currentTimeMillis() + ".xls"); try { OutputStream out = httpServletResponse.getOutputStream(); wb.write(out); out.close(); } catch (IOException e) {} return null; }
@Override public void generate(final ProgressMonitor monitor, final HSSFWorkbook workbook, final int sheetNo, final boolean useLogicalNameAsSheetName, final Map<String, Integer> sheetNameMap, final Map<String, ObjectModel> sheetObjectMap, final ERDiagram diagram, final Map<String, LoopDefinition> loopDefinitionMap) throws InterruptedException { for (final Trigger trigger : diagram.getDiagramContents().getTriggerSet()) { final String name = trigger.getName(); final HSSFSheet newSheet = createNewSheet(workbook, sheetNo, name, sheetNameMap); final String sheetName = workbook.getSheetName(workbook.getSheetIndex(newSheet)); monitor.subTaskWithCounter("[Trigger] " + sheetName); sheetObjectMap.put(sheetName, trigger); setTriggerData(workbook, newSheet, trigger); monitor.worked(1); } }
/** * {@inheritDoc} */ @Override public void generate(ProgressMonitor monitor, HSSFWorkbook workbook, int sheetNo, boolean useLogicalNameAsSheetName, Map<String, Integer> sheetNameMap, Map<String, ObjectModel> sheetObjectMap, ERDiagram diagram, Map<String, LoopDefinition> loopDefinitionMap) throws InterruptedException { String sheetName = this.getSheetName(); HSSFSheet newSheet = createNewSheet(workbook, sheetNo, sheetName, sheetNameMap); sheetName = workbook.getSheetName(workbook.getSheetIndex(newSheet)); monitor.subTaskWithCounter(sheetName); sheetObjectMap.put(sheetName, new StringObjectModel(sheetName)); this.setHistoryListData(workbook, newSheet, sheetObjectMap, diagram); monitor.worked(1); }
/** * 获取Excel2003图片 * * @param sheet * 当前sheet对象 * @param workbook * 工作簿对象 * @return Map key:图片单元格索引(1_1)String,value:图片流PictureData */ public static Map<String, PictureData> getSheetPictrues03(HSSFSheet sheet, HSSFWorkbook workbook) { Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>(); List<HSSFPictureData> pictures = workbook.getAllPictures(); if (!pictures.isEmpty()) { for (HSSFShape shape : sheet.getDrawingPatriarch().getChildren()) { HSSFClientAnchor anchor = (HSSFClientAnchor) shape.getAnchor(); if (shape instanceof HSSFPicture) { HSSFPicture pic = (HSSFPicture) shape; int pictureIndex = pic.getPictureIndex() - 1; HSSFPictureData picData = pictures.get(pictureIndex); String picIndex = String.valueOf(anchor.getRow1()) + "_" + String.valueOf(anchor.getCol1()); sheetIndexPicMap.put(picIndex, picData); } } return sheetIndexPicMap; } else { return sheetIndexPicMap; } }
@Override protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { String codedFileName = "临时文件"; Workbook workbook = ExcelExportUtil.exportExcel( (ExportParams) model.get(MapExcelConstants.PARAMS), (List<ExcelExportEntity>) model.get(MapExcelConstants.ENTITY_LIST), (Collection<? extends Map<?, ?>>) model.get(MapExcelConstants.MAP_LIST)); if (model.containsKey(MapExcelConstants.FILE_NAME)) { codedFileName = (String) model.get(MapExcelConstants.FILE_NAME); } if (workbook instanceof HSSFWorkbook) { codedFileName += HSSF; } else { codedFileName += XSSF; } if (isIE(request)) { codedFileName = java.net.URLEncoder.encode(codedFileName, "UTF8"); } else { codedFileName = new String(codedFileName.getBytes("UTF-8"), "ISO-8859-1"); } response.setHeader("content-disposition", "attachment;filename=" + codedFileName); ServletOutputStream out = response.getOutputStream(); workbook.write(out); out.flush(); }
private Function<Table, File> toWorkbookFunction(final Supplier<Workbook> supplier) { return new Function<Table, File>() { @Override public File apply(Table table) { try { String ext = supplier.get() instanceof HSSFWorkbook ? ".xls" : ".xlsx"; final File file = File.createTempFile("xls", ext); file.deleteOnExit(); try (final FileOutputStream out = new FileOutputStream(file)) { table.toWorkBook(supplier.get()) .write(out); return file; } } catch (IOException e) { throw Throwables.propagate(e); } } }; }
private HSSFCellStyle createMatrixCellStyle(final HSSFWorkbook workbook, final HSSFCellStyle matrixHeaderTemplateCellStyle, final boolean top, final boolean right, final boolean bottom, final boolean left) { final HSSFCellStyle cellStyle = POIUtils.copyCellStyle(workbook, matrixHeaderTemplateCellStyle); if (top) { cellStyle.setBorderTop(CellStyle.BORDER_THIN); } if (right) { cellStyle.setBorderRight(CellStyle.BORDER_THIN); } if (bottom) { cellStyle.setBorderBottom(CellStyle.BORDER_THIN); } if (left) { cellStyle.setBorderLeft(CellStyle.BORDER_THIN); } return cellStyle; }
/** * 构造函数 * @param path 导入文件对象 * @param headerNum 标题行号,数据行号=标题行号+1 * @param sheetIndex 工作表编号 * @throws InvalidFormatException * @throws IOException */ public ImportExcel(String fileName, InputStream is, int headerNum, int sheetIndex) throws InvalidFormatException, IOException { if (StringUtils.isBlank(fileName)){ throw new RuntimeException("导入文档为空!"); }else if(fileName.toLowerCase().endsWith("xls")){ this.wb = new HSSFWorkbook(is); }else if(fileName.toLowerCase().endsWith("xlsx")){ this.wb = new XSSFWorkbook(is); }else{ throw new RuntimeException("文档格式不正确!"); } if (this.wb.getNumberOfSheets()<sheetIndex){ throw new RuntimeException("文档中没有工作表!"); } this.sheet = this.wb.getSheetAt(sheetIndex); this.headerNum = headerNum; log.debug("Initialize success."); }
/** * 获取Excel2003图片 * * @param sheet * 当前sheet对象 * @param workbook * 工作簿对象 * @return Map key:图片单元格索引(1_1)String,value:图片流PictureData */ public static Map<String, PictureData> getSheetPictrues03(HSSFSheet sheet, HSSFWorkbook workbook) { Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>(); List<HSSFPictureData> pictures = workbook.getAllPictures(); if (!pictures.isEmpty()) { for (HSSFShape shape : sheet.getDrawingPatriarch().getChildren()) { HSSFClientAnchor anchor = (HSSFClientAnchor) shape.getAnchor(); if (shape instanceof HSSFPicture) { HSSFPicture pic = (HSSFPicture) shape; int pictureIndex = pic.getPictureIndex() - 1; HSSFPictureData picData = pictures.get(pictureIndex); String picIndex = String.valueOf(anchor.getRow1()) + "_" + String.valueOf(anchor.getCol1()); sheetIndexPicMap.put(picIndex, picData); } } return sheetIndexPicMap; } else { return null; } }
private void setComplexUniqueKeyMatrix(final HSSFWorkbook workbook, final HSSFSheet sheet, final ERTable table) { final CellLocation logicalCellLocation = POIUtils.findCell(sheet, KEYWORD_LOGICAL_COMPLEX_UNIQUE_KEY_MATRIX); if (logicalCellLocation != null) { if (logicalComplexUniqueKeyMatrixCellStyle == null) { logicalComplexUniqueKeyMatrixCellStyle = this.createMatrixCellStyle(workbook, sheet, logicalCellLocation); } setComplexUniqueKeyMatrix(workbook, sheet, table, logicalCellLocation, logicalComplexUniqueKeyMatrixCellStyle, true); } final CellLocation physicalCellLocation = POIUtils.findCell(sheet, KEYWORD_PHYSICAL_COMPLEX_UNIQUE_KEY_MATRIX); if (physicalCellLocation != null) { if (physicalComplexUniqueKeyMatrixCellStyle == null) { physicalComplexUniqueKeyMatrixCellStyle = this.createMatrixCellStyle(workbook, sheet, physicalCellLocation); } this.setComplexUniqueKeyMatrix(workbook, sheet, table, physicalCellLocation, physicalComplexUniqueKeyMatrixCellStyle, false); } }
/** * Provides a list of filenames that contain workbooks that are linked with the current one. Officially supported only for new Excel format. For the old Excel format this is experimental * * @return list of filenames (without path) belonging to linked workbooks * */ @Override public List<String> getLinkedWorkbooks() { List<String> result = new ArrayList<>(); if (this.currentWorkbook instanceof HSSFWorkbook) { result = getLinkedWorkbooksHSSF(); } else if (this.currentWorkbook instanceof XSSFWorkbook) { // use its API for (ExternalLinksTable element: ((XSSFWorkbook)this.currentWorkbook).getExternalLinksTable()) { result.add(element.getLinkedFileName()); } } else { LOG.warn("Cannot determine linked workbooks"); } return result; }