@RequestMapping(value = "/test2.xlsx", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE) @ResponseBody byte[] testDown() throws IOException, InvalidFormatException { Workbook workbook = new SXSSFWorkbook(); Sheet sheet = workbook.createSheet(); for (int i = 0; i < 60000; i++) { Row newRow = sheet.createRow(i); for (int j = 0; j < 100; j++) { newRow.createCell(j).setCellValue("test" + Math.random()); } } ByteArrayOutputStream os = new ByteArrayOutputStream(); workbook.write(os); byte[] bytes = os.toByteArray(); return bytes; }
/** * Returns the default data cell style. Obtained from: * http://svn.apache.org/repos/asf/poi * /trunk/src/examples/src/org/apache/poi/ss/examples/TimesheetDemo.java * * @param wb the wb * @return the cell style */ protected CellStyle defaultDataCellStyle(final Workbook wb) { CellStyle style; style = wb.createCellStyle(); style.setAlignment(HorizontalAlignment.CENTER); style.setWrapText(true); style.setBorderRight(BorderStyle.THIN); style.setRightBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderLeft(BorderStyle.THIN); style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderTop(BorderStyle.THIN); style.setTopBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderBottom(BorderStyle.THIN); style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); style.setDataFormat(doubleDataFormat); return style; }
public void setCellStyleFont(Workbook workbook, CellStyle style, int i) { Font font = workbook.createFont(); if (i == 0) { // 正常 } else if (i == 4) { // 下划线 font.setUnderline(Font.U_SINGLE); style.setFont(font); } else if (i == 2) { // 倾斜 font.setItalic(true); style.setFont(font); } else if (i == 1) { // 加粗 font.setBold(true); style.setFont(font); } }
public CellStyle createIndentationCellStyle(Workbook workbook, int s) { CellStyle dataStyle1 = this.createBorderCellStyle(workbook, true); Font dataFont = workbook.createFont(); dataFont.setColor((short) 12); dataFont.setFontHeightInPoints((short) 10); dataStyle1.setFillPattern(FillPatternType.SOLID_FOREGROUND); dataStyle1.setFillForegroundColor((short) 11); dataStyle1.setFont(dataFont); dataStyle1.setVerticalAlignment(VerticalAlignment.CENTER); dataStyle1.setAlignment(HorizontalAlignment.LEFT); dataStyle1.setIndention(Short.valueOf(String.valueOf((s)))); return dataStyle1; }
@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); }
public static <T> ImportResult<T> importExcel(ExcelFileType fileType,InputStream inputStream,Class<T> clazz) throws Exception{ if(importInfoMap.get(clazz) == null){//初始化信息 initTargetClass(clazz); } ImportInfo importInfo = importInfoMap.get(clazz); Integer headRow = importInfo.getHeadRow(); Workbook workbook = createWorkbook(fileType, inputStream); int sheetNum = workbook.getNumberOfSheets(); if(sheetNum < 1 ){ return null; } Sheet sheet = workbook.getSheetAt(0); int rowCount = sheet.getPhysicalNumberOfRows(); if(rowCount < (headRow+1)){// return null; } List<String> headNameList = createHeadNameList(sheet, headRow); return readData(clazz, importInfo, workbook,headNameList); }
/** * 分批写出20w条数据 * * @throws IOException */ @Test public void batchesExport() throws IOException { Map<String, String> map = new HashMap<String,String>(); map.put("msg", "用户信息导出报表"); map.put("status", "导出成功"); Workbook workbook = null; //分两次写入20w条数据 List<UserPlus> list; for(int i = 0 ; i < 2 ; i++){ list = getData(i*100000, 100000); workbook = ExcelExportUtil.exportExcel03(UserPlus.class, list, map,workbook); } FileOutputStream outputStream = new FileOutputStream("D:/test/user1.xls"); workbook.write(outputStream); outputStream.flush(); outputStream.close(); }
/**@throws IOException * @Excel(headRow=2,dataRow=5,sheetName="用户统计表",sheetSize=65536) * 分sheet测试 */ @Test public void separateSheet() throws IOException { //获取10w条数据 List<UserPlus> list = getData(0, 100000); Map<String, String> map = new HashMap<String,String>(); map.put("msg", "用户信息导出报表"); map.put("status", "导出成功"); long start = System.currentTimeMillis(); Workbook workbook = ExcelExportUtil.exportExcel03(UserPlus.class, list, map); long end = System.currentTimeMillis(); System.out.println("耗时:" + (end - start ) + "毫秒"); FileOutputStream outputStream = new FileOutputStream("D:/test/user.xls"); workbook.write(outputStream); outputStream.flush(); outputStream.close(); }
@Test public void testExcel07() throws IOException{ List<UserPlus> list = getData(0, 20000); Map<String, String> map = new HashMap<String,String>(); map.put("msg", "用户信息导出报表"); map.put("status", "导出成功"); long start = System.currentTimeMillis(); Workbook workbook = ExcelExportUtil.exportExcel07(UserPlus.class, list, map, true); long end = System.currentTimeMillis(); System.out.println("耗时:" + (end - start ) + "毫秒"); FileOutputStream outputStream = new FileOutputStream("D:/test/user.xlsx"); workbook.write(outputStream); if(SXSSFWorkbook.class.equals(workbook.getClass())){ SXSSFWorkbook wb = (SXSSFWorkbook)workbook; wb.dispose(); } outputStream.flush(); outputStream.close(); }
/** * Creates an excel file to export message data. * The excel workbook will have several sheets named after the map key. * Each sheet of the file will have the default form: * <ul> * <li>Line 1 (Header): KEY | de | fr | more iso-language-codes ...</li> * <li>Line 2..n (Values): message.key | Deutsch | Francaise | other translation</li> * </ul> * The header columns are defined by the provided languages in the resources lists. * The concrete row and column numbers can be configured to match more requirements like comments. * * @param input a list of message information to write to excel * @param output if you want to create xls (Excel 97-2003) files, DO NOT use BufferedOutputStream due to library * issue. * @param format use constants FORMAT_EXCEL_97 or FORMAT_EXCEL_2007 * @throws I18nException if a problem occures */ public void createExcel(Map<String, List<MessageResourceEntry>> input, OutputStream output, String format) throws I18nException { Workbook wb = createWorkbook(format); for (Entry<String, List<MessageResourceEntry>> entry : input.entrySet()) { createSheet(entry.getValue(), entry.getKey(), wb); } try { LOG.info("Write data to output stream"); wb.write(output); } catch (IOException e) { throw new I18nException("Problem writing to stream", e); } }
@Test public void createExcel_keyFoundInDefaultProperty() throws Exception { // given List<String> keyList = new ArrayList<String>(); keyList.add(KEY1); Map<String, Properties> localizedProperties = prepareProperties(null, KEY2, VALUE + "2"); Map<String, ResourceBundle> defaultProperties = prepareDefaultProperties( null, KEY1, VALUE + "1"); List<Locale> locales = prepareLocaleList(null); prepareFacesContextStub(Locale.GERMAN, Locale.ENGLISH); // when Workbook result = ExcelHandler.createExcel(keyList, defaultProperties, localizedProperties, null, BaseBean.LABEL_USERINTERFACE_TRANSLARIONS, locales); // then verifyCreatedResult(result, "User interface", "Add your language code here"); assertEquals(VALUE + "1", result.getSheetAt(0).getRow(1).getCell(1) .getStringCellValue()); }
@Test public void createExcel_keyNotFoundInDefaultProperty() throws Exception { // given List<String> keyList = new ArrayList<String>(); keyList.add(KEY1); Map<String, Properties> localizedProperties = prepareProperties(null, KEY2, VALUE + "2"); Map<String, ResourceBundle> defaultProperties = prepareDefaultProperties( null, KEY3, VALUE + "3"); List<Locale> locales = prepareLocaleList(null); prepareFacesContextStub(Locale.GERMAN, Locale.ENGLISH); // when Workbook result = ExcelHandler.createExcel(keyList, defaultProperties, localizedProperties, null, BaseBean.LABEL_USERINTERFACE_TRANSLARIONS, locales); // then verifyCreatedResult(result, "User interface", "Add your language code here"); assertEquals("", result.getSheetAt(0).getRow(1).getCell(1) .getStringCellValue()); }
@Test public void createExcel_onlyStandardLanguages() throws Exception { // given List<String> keyList = new ArrayList<String>(); keyList.add(KEY1); Map<String, ResourceBundle> defaultProperties = prepareDefaultProperties( null, KEY1, VALUE + "1"); List<Locale> locales = prepareLocaleList(null); prepareFacesContextStub(Locale.GERMAN, Locale.ENGLISH); // when Workbook result = ExcelHandler.createExcel(keyList, defaultProperties, null, null, BaseBean.LABEL_USERINTERFACE_TRANSLARIONS, locales); // then verifyCreatedResult(result, "User interface", "Add your language code here"); }
@Test public void createExcel_withOneMoreStandardLanguage() throws Exception { // given List<String> keyList = new ArrayList<String>(); keyList.add(KEY1); Map<String, Properties> localizedProperties = prepareProperties(DE, KEY1, VALUE + "1"); Map<String, ResourceBundle> defaultProperties = prepareDefaultProperties( null, KEY1, VALUE + "1"); List<Locale> locales = prepareLocaleList(DE); prepareFacesContextStub(Locale.GERMAN, Locale.ENGLISH); // when Workbook result = ExcelHandler.createExcel(keyList, defaultProperties, localizedProperties, null, BaseBean.LABEL_USERINTERFACE_TRANSLARIONS, locales); // then verifyCreatedResult(result, "User interface", DE); }
@Test public void createExcel_withOneMoreStandardLanguage_NewValueImported() throws Exception { // given List<String> keyList = new ArrayList<String>(); keyList.add(KEY1); Map<String, Properties> localizedProperties = prepareProperties(DE, KEY1, VALUE + "2"); Map<String, ResourceBundle> defaultProperties = prepareDefaultProperties( null, KEY1, VALUE + "1"); List<Locale> locales = prepareLocaleList(DE); prepareFacesContextStub(Locale.GERMAN, Locale.ENGLISH); // when Workbook result = ExcelHandler.createExcel(keyList, defaultProperties, localizedProperties, null, BaseBean.LABEL_USERINTERFACE_TRANSLARIONS, locales); // then verifyCreatedResult(result, "User interface", DE); assertEquals("value1", result.getSheetAt(0).getRow(1).getCell(1) .getStringCellValue()); assertEquals("value2", result.getSheetAt(0).getRow(1).getCell(4) .getStringCellValue()); }
@Test public void createExcel_withOneMoreStandardLanguage_NoValueInDB() throws Exception { // given List<String> keyList = new ArrayList<String>(); keyList.add(KEY1); Map<String, Properties> localizedProperties = prepareProperties(DE, null, null); Map<String, ResourceBundle> defaultProperties = prepareDefaultProperties( null, KEY1, VALUE + "1"); List<Locale> locales = prepareLocaleList(DE); prepareFacesContextStub(Locale.GERMAN, Locale.ENGLISH); // when Workbook result = ExcelHandler.createExcel(keyList, defaultProperties, localizedProperties, null, BaseBean.LABEL_USERINTERFACE_TRANSLARIONS, locales); // then verifyCreatedResult(result, "User interface", DE); assertEquals("value1", result.getSheetAt(0).getRow(1).getCell(1) .getStringCellValue()); assertEquals("", result.getSheetAt(0).getRow(1).getCell(4) .getStringCellValue()); }
@Test public void createExcel_withOneNotStandardLanguage() throws Exception { // given List<String> keyList = new ArrayList<String>(); keyList.add(KEY1); Map<String, Properties> localizedProperties = prepareProperties(ZH, KEY1, VALUE + "1"); Map<String, ResourceBundle> defaultProperties = prepareDefaultProperties( null, KEY1, VALUE + "1"); List<Locale> locales = prepareLocaleList(ZH); prepareFacesContextStub(Locale.GERMAN, Locale.ENGLISH); // when Workbook result = ExcelHandler.createExcel(keyList, defaultProperties, localizedProperties, null, BaseBean.LABEL_USERINTERFACE_TRANSLARIONS, locales); // then verifyCreatedResult(result, "User interface", ZH); }
private void verifyCreatedResult(Workbook result, String sheetName, String LastCellValue) { assertNotNull(null, result); assertEquals(sheetName, result.getSheetAt(0).getSheetName()); assertEquals(5, result.getSheetAt(0).getRow(0).getLastCellNum()); assertEquals("Key ", result.getSheetAt(0).getRow(0).getCell(0) .getStringCellValue()); assertEquals("de system", result.getSheetAt(0).getRow(0).getCell(1) .getStringCellValue()); assertEquals("en system", result.getSheetAt(0).getRow(0).getCell(2) .getStringCellValue()); assertEquals("ja system", result.getSheetAt(0).getRow(0).getCell(3) .getStringCellValue()); assertEquals(LastCellValue, result.getSheetAt(0).getRow(0).getCell(4) .getStringCellValue()); }
@Test public void createExcel_TranslationBean_KeyNotFoundInDB() throws Exception { // given List<String> keyList = new ArrayList<String>(); keyList.add(KEY1); Map<String, ResourceBundle> defaultProperties = prepareDefaultProperties( null, KEY1, VALUE + "1"); Map<String, Properties> localizedProperties = prepareProperties(null, KEY2, VALUE + "2"); List<Locale> locales = prepareLocaleList(null); prepareFacesContextStub(Locale.GERMAN, Locale.ENGLISH); // when Workbook result = ExcelHandler.createExcel(keyList, defaultProperties, localizedProperties, null, BaseBean.LABEL_SHOP_TRANSLARIONS, locales); // then verifyCreatedResultForTranslationBean(result, "Customize texts", 4, JA); assertEquals(VALUE + "1", result.getSheetAt(0).getRow(1).getCell(1) .getStringCellValue()); }
@Restrict({@Group("ADMIN")}) public Result reportAllExams(String from, String to) throws IOException { final DateTime start = DateTime.parse(from, DTF); final DateTime end = DateTime.parse(to, DTF); List<ExamParticipation> participations = Ebean.find(ExamParticipation.class) .fetch("exam") .where() .gt("started", start) .lt("ended", end) .disjunction() .eq("exam.state", Exam.State.GRADED) .eq("exam.state", Exam.State.GRADED_LOGGED) .eq("exam.state", Exam.State.ARCHIVED) .endJunction() .findList(); Workbook wb = new XSSFWorkbook(); generateParticipationSheet(wb, participations, true); response().setHeader("Content-Disposition", "attachment; filename=\"all_exams.xlsx\""); return ok(encode(wb)); }
@Override protected void fillTrie(Logger logger, Trie<List<String>> trie, Corpus corpus) throws IOException, ModuleException { Iterator<InputStream> inputStreams = xlsFile.getInputStreams(); while (inputStreams.hasNext()) { try (InputStream is = inputStreams.next()) { Workbook wb = WorkbookFactory.create(is); for (int sheetNumber : sheets) { Sheet sheet = wb.getSheetAt(sheetNumber); fillSheetEntries(trie, sheet); } } catch (EncryptedDocumentException|InvalidFormatException e) { rethrow(e); } } }
@Test public void test1() throws Exception { File file = folder.newFile("temp.xlsx"); try (Workbook wb = new XSSFWorkbook()) { Sheet sheet1 = wb.createSheet("Sheet1"); for (int row = 10; row <= 110; row++) { ExcelUtils.writeCell(sheet1, row, 20, "ISSUE-" + row); } try (OutputStream out = new FileOutputStream(file)) { wb.write(out); } } Context context = new MockContext(); Read re = new Read(file.getAbsolutePath(), "Sheet1", "U"); TextList list = re.execute(context, None.getInstance()); assertNotNull(list); List<Text> texts = list.remaining(Hint.none()); assertNotNull(texts); assertEquals(101, texts.size()); assertEquals("ISSUE-10", texts.get(0).getText()); assertEquals("ISSUE-110", texts.get(100).getText()); }
@Override public Workbook workbook() { try { return WorkbookFactory.create(poijiFile.file()); } catch (InvalidFormatException | IOException e) { throw new PoijiException("Problem occurred while creating HSSFWorkbook", e); } }
private void testGenerator(ScriptGenerator generator) throws IOException { try (InputStream is = getClass().getResourceAsStream("/Users.xlsx"); Workbook workbook = new XSSFWorkbook(is)) { Sheet sheet = workbook.getSheetAt(0); List<String> lines = generator.generate(sheet); assertThat(lines.size()).isEqualTo(44); assertThat(lines.get(0)).isEqualTo("insert into ApplicationPermission(user_id, application_id) values('t.wilson', 2237);"); assertThat(lines.get(15)).isEqualTo("insert into ApplicationPermission(user_id, application_id) values('p.romero', 3657);"); assertThat(lines.get(22)).isEqualTo("insert into ApplicationPermission(user_id, application_id) values('b.walton', 4352);"); assertThat(lines.get(43)).isEqualTo("insert into ApplicationPermission(user_id, application_id) values('e.nash', 5565);"); } }
@Override public <T> Workbook toExcel(ExcelResponseBody excelResponseBody, List<T> excelVoList) throws Exception{ ExcelType excelType = excelResponseBody.type(); ExcelConverter converter = getExcelConverter(excelType); if (converter == null) { throw new IllegalArgumentException("Unknown converter type [" + excelType.name() + "]"); } return converter.toExcel(excelResponseBody, excelVoList); }
public static int main(String[] args) { try { if (args.length == 0) throw new RuntimeException("A pdf file name is necessary"); PDFToText pdfExtractor = new PDFToTextImpl(); String diarioText = pdfExtractor.fromPath(args[0]); IndicacaoExtractor extractor = new IndicacaoExtractorImpl(); List<Indicacao> indicacoes = extractor.extractFromText(diarioText); System.out.println("Extraction completed"); System.out.println("Creating workbook..."); WorkbookExport workbookExporter = new WorkbookExportImpl(); Workbook workbook = workbookExporter.createWorkbook(indicacoes); WorkbookFileWriter workbootFileWriter = new WorkbookFileWriterImpl(); System.out.println("Workbook created"); System.out.println("Writing to file..."); String xlsFileName = "default.xls"; if (args.length > 1) xlsFileName = args[1]; workbootFileWriter.write(workbook, xlsFileName); System.out.println("Process finished!"); return indicacoes.size(); } catch (Exception ex) { System.out.println(ex.getMessage()); return 0; } }
/** * 抽象出图片生成业务代码 * * @throws IOException */ private void extractPicturePortion(String svgString, XSSFWorkbook wb, XSSFSheet sheet, int startCol, int endCol, int startRow, int endRow) throws IOException { // 图片 if (org.apache.commons.lang3.StringUtils.isNotBlank(svgString)) { byte[] safeDataBytes = new BASE64Decoder().decodeBuffer(svgString); int pictureIdx = wb.addPicture(safeDataBytes, Workbook.PICTURE_TYPE_JPEG); CreationHelper helper = wb.getCreationHelper(); // Create the drawing patriarch. This is the top level container for // all shapes. Drawing drawing = sheet.createDrawingPatriarch(); // add a picture shape ClientAnchor anchor = helper.createClientAnchor(); // set top-left corner of the picture, // subsequent call of Picture#resize() will operate relative to it anchor.setCol1(startCol); anchor.setCol2(endCol); anchor.setRow1(startRow); anchor.setRow2(endRow); anchor.setDx1(0); anchor.setDy1(0); anchor.setDx2(0); anchor.setDy2(0); anchor.setAnchorType(ClientAnchor.MOVE_DONT_RESIZE); Picture pict = drawing.createPicture(anchor, pictureIdx); pict.resize(1); } }
private int buildImageFormat(Image img){ int type=Workbook.PICTURE_TYPE_PNG; String path=img.getPath(); if(path==null){ return type; } path=path.toLowerCase(); if(path.endsWith("jpg") || path.endsWith("jpeg")){ type=Workbook.PICTURE_TYPE_JPEG; } return type; }
/** 实际创建CellStyle Map * @param workbook * @param exportInfo * @param isHead * @return */ private static Map<Field, CellStyle> doCreateStyleMap(Workbook workbook, ExportInfo exportInfo,boolean isHead) { Map<ExportCellStyleInfo, CellStyle> tempCacheMap = new HashMap<ExportCellStyleInfo, CellStyle>(); Map<Field, CellStyle> styleMap = new HashMap<Field, CellStyle>(); CellStyle style; for(Map.Entry<Field,ExportFieldInfo> entry : exportInfo.getFieldInfoMap().entrySet()){ ExportCellStyleInfo styleInfo ; if(isHead){ styleInfo = entry.getValue().getHeadStyle(); }else{ styleInfo = entry.getValue().getDataStyle(); } if(!StringUtils.isEmpty(entry.getValue().getDataFormat())){ //当存在格式化时,即使是来自通用的样式,但是格式不一样,所以需要new专属格式的样式 //由于格式化属于专属,因此也不需要放到临时缓存map之中 style = doCreateCellStyle(workbook,styleInfo,entry.getValue().getDataFormat()); }else{ style = tempCacheMap.get(styleInfo); if(style == null){ style = doCreateCellStyle(workbook,styleInfo,null); tempCacheMap.put(styleInfo, style); } } if(style != null ){ styleMap.put(entry.getKey(),style); } } tempCacheMap.clear(); return styleMap.isEmpty() ? null : styleMap; }
public CellStyle builderLabelCellStyle(ReportForm reportFormModel, Workbook workbook) { List<ReportFormData> list = reportFormModel.getListReportFormDataModel(); ReportFormData reportFormDataModel; if (list.size() > 0) { reportFormDataModel = list.get(0); int labelAlign = reportFormDataModel.getLabelAlign(); CellStyle labelStyle = createBorderCellStyle(workbook, reportFormModel.isShowBorder()); setCellStyleAligment(labelStyle, labelAlign); labelStyle.setVerticalAlignment(VerticalAlignment.CENTER); return labelStyle; } return null; }
@Test public void exportExcel() throws FileNotFoundException, Exception { File file = new File("D:/test/test/ppp44.xls"); FileOutputStream outputStream = new FileOutputStream(file); List<Person> list = getData(); Workbook workbook = null; long start = System.currentTimeMillis(); workbook = ExcelExportUtil.exportExcel03(Person.class, list); // workbook = ExcelExportUtil.exportExcel(Person.class,list,ExcelFileType.XLS,null,null,true); // list = getData(); // workbook = ExcelExportUtil.exportExcel(UserPlus.class,list,ExcelFileType.XLSX,map,workbook,true); long end = System.currentTimeMillis(); System.out.println("耗时:" + (end-start) + "毫秒"); System.out.println("****************************"); workbook.write(outputStream); if(SXSSFWorkbook.class.equals(workbook.getClass())){ SXSSFWorkbook wb = (SXSSFWorkbook)workbook; wb.dispose(); } outputStream.flush(); outputStream.close(); }
private static XSSFCellStyle createCellStyle(Workbook workbook) { XSSFCellStyle xstyle = (XSSFCellStyle) workbook.createCellStyle(); XSSFFont font = (XSSFFont) workbook.createFont(); font.setFontHeightInPoints((short) 11); xstyle.setFont(font); return xstyle; }
public static CellStyle createHeaderStyle(Workbook workbook) { XSSFCellStyle headerStyle = createCellStyle(workbook); XSSFColor header = new XSSFColor(new byte[]{(byte) 79, (byte) 129, (byte) 189}); headerStyle.setFillForegroundColor(header); headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); headerStyle.getFont().setColor(IndexedColors.WHITE.index); return headerStyle; }
/** * excel 下载 */ @RequestMapping(value = "downLoad") public void downLoad(HttpServletRequest request, HttpServletResponse response) throws Exception { Workbook wb = null; try { logger.info(">>>>>>>>ReportViewController.downLoad start>>"); //=======================================数据 List<Map<String,Object>> datas = Lists.newArrayList(); Map<String,Object> data0 = Maps.newHashMap(); data0.put("date", "2017-01-01"); data0.put("date1", "2017-01-01"); Map<String,Object> data1 = Maps.newHashMap(); data1.put("shoujidai","100"); data1.put("daxuedai","100"); data1.put("zirandai","100"); data0.put("zidonghebishu",data1); datas.add(data0); //========================================== //设置excel模板 Map<String, Object> templateParams = Maps.newHashMap(); XLSTransformer transformer = new XLSTransformer(); wb = transformer.transformXLS(App.class.getResourceAsStream("/xls/excel.xlsx"), templateParams); Sheet billInfoSheet = wb.getSheet("sheet1"); //设置excel展示配置 ExcelExportSetting excelExportSetting = new ExcelExportSetting(); List<PoiCell> cellList = Lists.newArrayList(); //一行数据的第一列 cellList.add(new ExcelMergeCell("日期","date")); cellList.add(new ExcelMergeCell("日期1","date1")); //一行数据的第二个列合并单元格的 ExcelMergeCell excelMergeCell = new ExcelMergeCell("自动电核笔数","zidonghebishu", Arrays.asList(new ExcelCell("大学贷","daxuedai"), new ExcelCell("手机贷","shoujidai"), new ExcelCell("自然贷","zirandai"))); cellList.add(excelMergeCell); excelExportSetting.setHeaderRow(cellList);//设置表头 excelExportSetting.setDataList(datas);//设置数据 //写入excel ExcelPoiHelp.poiWrite(wb, billInfoSheet, excelExportSetting); //写入response String outFile = "outputFile.xls"; response.reset(); response.addHeader("Content-Disposition", "attachment;filename="+ new String(outFile.getBytes())); OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/vnd.ms-excel;charset=utf-8"); wb.write(toClient); } catch (Exception e) { e.printStackTrace(); } finally { wb.close(); } }
private static CellStyle getCellStyle(int type, Workbook wb, Map<Integer, CellStyle> excelCellStype) { if (!excelCellStype.containsKey(type)) { excelCellStype = new HashMap<Integer, CellStyle>(); CellStyle cellStyle = null; //1货币,2百分比,3日期,0标题 cellStyle = wb.getSheet("格式").getRow(type).getCell(1).getCellStyle(); excelCellStype.put(type, cellStyle); return cellStyle; } else { return excelCellStype.get(type); } }
/** * Returns the default totals row style for Integer data. Obtained from: * http://svn.apache.org/repos/asf/poi * /trunk/src/examples/src/org/apache/poi/ss/examples/TimesheetDemo.java * * @param wb the wb * @return the cell style */ protected CellStyle defaultTotalsIntegerCellStyle(final Workbook wb) { CellStyle style; style = wb.createCellStyle(); style.setAlignment(HorizontalAlignment.CENTER); style.setVerticalAlignment(VerticalAlignment.CENTER); style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); style.setFillPattern(FillPatternType.SOLID_FOREGROUND); style.setDataFormat(integerDataFormat); return style; }
public RWorkbook(Workbook i_Workbook) { this.workbook = i_Workbook; this.fonts = new TablePartitionRID<RTemplate ,Font>(); this.cellStyles = new TablePartitionRID<RTemplate ,CellStyle>(); this.fontsByCopy = new Hashtable<String ,Short>(); this.cellStylesByCopy = new Hashtable<String ,Short>(); }
private static Result examToExcel(Exam exam) throws IOException { Map<String, String> values = new LinkedHashMap<>(); values.put("Creator ID", exam.getCreator().getId().toString()); values.put("First name", exam.getCreator().getFirstName()); values.put("Last name", exam.getCreator().getLastName()); values.put("Exam type", exam.getExamType().getType()); values.put("Course code", exam.getCourse().getCode()); values.put("Course name", exam.getCourse().getName()); values.put("Course credits", exam.getCourse().getCredits().toString()); values.put("Course unit type", forceNotNull(exam.getCourse().getCourseUnitType())); values.put("Course level", forceNotNull(exam.getCourse().getLevel())); values.put("Created", ISODateTimeFormat.date().print(new DateTime(exam.getCreated()))); values.put("Begins", ISODateTimeFormat.date().print(new DateTime(exam.getExamActiveStartDate()))); values.put("Ends", ISODateTimeFormat.date().print(new DateTime(exam.getExamActiveEndDate()))); values.put("Duration", exam.getDuration() == null ? "N/A" : exam.getDuration().toString()); values.put("Grade scale", exam.getGradeScale() == null ? "N/A" : exam.getGradeScale().getDescription()); values.put("State", exam.getState().toString()); values.put("Attachment", exam.getAttachment() == null ? "" : exam.getAttachment().getFilePath() + exam.getAttachment().getFileName()); values.put("Instructions", forceNotNull(exam.getInstruction())); values.put("Shared", Boolean.valueOf(exam.isShared()).toString()); Workbook wb = new XSSFWorkbook(); Sheet sheet = wb.createSheet(exam.getName()); Row headerRow = sheet.createRow(0); int i = 0; for (String key : values.keySet()) { headerRow.createCell(i++).setCellValue(key); } Row dataRow = sheet.createRow(1); i = 0; for (String value : values.values()) { dataRow.createCell(i++).setCellValue(value); } response().setHeader("Content-Disposition", "attachment; filename=\"exams.xlsx\""); return ok(encode(wb)); }
/** * Creates an excel sheet in the provided workbook using provided parameters. * * @param input the data to put in the sheet- * @param sheetName the name to user for the sheet. * @param wb the workbook to create the sheet in. */ private void createSheet( List<MessageResourceEntry> input, String sheetName, Workbook wb) { // create a new sheet String name = StringUtils.isBlank(sheetName) ? this.defaultSheetName : sheetName; LOG.info("Create sheet with name " + name); Sheet sheet = wb.createSheet(name); sheet.setZoom(this.zoom, 100); Map<Locale, Integer> langs = getLanguageInformation(input); createHeader(sheet, langs); CellStyle keyStyle = sheet.getWorkbook().createCellStyle(); keyStyle.setAlignment(CellStyle.ALIGN_LEFT); keyStyle.setBorderBottom(CellStyle.BORDER_THIN); keyStyle.setBorderRight(CellStyle.BORDER_MEDIUM); Font f = sheet.getWorkbook().createFont(); f.setBoldweight(Font.BOLDWEIGHT_NORMAL); keyStyle.setFont(f); CellStyle valueStyle = sheet.getWorkbook().createCellStyle(); valueStyle.setAlignment(CellStyle.ALIGN_LEFT); valueStyle.setVerticalAlignment(CellStyle.VERTICAL_TOP); valueStyle.setBorderBottom(CellStyle.BORDER_THIN); valueStyle.setBorderRight(CellStyle.BORDER_THIN); valueStyle.setBorderTop(CellStyle.BORDER_THIN); valueStyle.setBorderLeft(CellStyle.BORDER_THIN); valueStyle.setFont(f); valueStyle.setWrapText(true); CellStyle emptyStyle = sheet.getWorkbook().createCellStyle(); emptyStyle.setAlignment(CellStyle.ALIGN_LEFT); emptyStyle.setVerticalAlignment(CellStyle.VERTICAL_TOP); emptyStyle.setBorderBottom(CellStyle.BORDER_THIN); emptyStyle.setBorderRight(CellStyle.BORDER_THIN); emptyStyle.setBorderTop(CellStyle.BORDER_THIN); emptyStyle.setBorderLeft(CellStyle.BORDER_THIN); emptyStyle.setFont(f); emptyStyle.setFillForegroundColor(IndexedColors.LAVENDER.getIndex()); emptyStyle.setFillPattern(CellStyle.SOLID_FOREGROUND); emptyStyle.setWrapText(true); LOG.info("Write data to sheet " + name); int rowIndex = this.languageHeaderRow + 1; for (MessageResourceEntry entry : input) { Row row = sheet.createRow(rowIndex); createContentRow(entry, row, langs, keyStyle, valueStyle, emptyStyle); rowIndex++; } sizeColumns(sheet, langs); sheet.createFreezePane(this.firstLanguageColumn, this.languageHeaderRow + 1, this.firstLanguageColumn, this.languageHeaderRow + 1); }
/** * Creates a cell and aligns it a certain way. * * @param wb the workbook * @param row the row to create the cell in * @param column the column number to create the cell in * @param halign the horizontal alignment for the cell. */ private static void createCell(Workbook wb, Row row, short column, short halign, short valign) { Cell cell = row.createCell(column); cell.setCellValue("Align It"); CellStyle cellStyle = wb.createCellStyle(); cellStyle.setAlignment(halign); cellStyle.setVerticalAlignment(valign); cell.setCellStyle(cellStyle); }