org.apache.poi.ss.usermodel.Workbook Java Examples

The following examples show how to use org.apache.poi.ss.usermodel.Workbook. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PoiUtil.java    From SpringBoot2.0 with Apache License 2.0 6 votes vote down vote up
public static void setContent(HttpServletRequest request, HttpServletResponse response, Workbook workbook, String name) throws IOException {
    if (workbook != null) {

        String fileName = name + DateUtil.format(new Date(), "yyyyMMddHHmmssSSS") + ".xlsx";
        // 针对IE或者以IE为内核的浏览器:
        String userAgent = request.getHeader("User-Agent");
        if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
            fileName = urlEncoder(fileName);
        } else {
            fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
        }
        response.setContentType("application/ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        response.setCharacterEncoding("UTF-8");
        OutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        IOUtils.closeQuietly(workbook);
        IOUtils.closeQuietly(outputStream);
    }
}
 
Example #2
Source File: XLSParser.java    From carina with Apache License 2.0 6 votes vote down vote up
public static String parseValue(String xls, String sheetName, String key) {
    String value = null;

    Workbook wb = XLSCache.getWorkbook(xls);

    Sheet sheet = wb.getSheet(sheetName);
    if (sheet == null) {
        throw new InvalidArgsException(String.format("No sheet: '%s' in excel file: '%s'!", sheetName, xls));
    }

    boolean isKeyFound = false;
    for (int i = 1; i <= sheet.getLastRowNum(); i++) {
        if (key.equals(getCellValue(sheet.getRow(i).getCell(0)))) {
            value = getCellValue(sheet.getRow(i).getCell(1));
            isKeyFound = true;
            break;
        }
    }

    if (!isKeyFound) {
        throw new InvalidArgsException(String.format("No key: '%s' on sheet '%s' in excel file: '%s'!", key, sheetName, xls));
    }

    return value;
}
 
Example #3
Source File: DefaultXlsTableExporter.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
*/
  @Override
  public MediaResource export(final Table table) {
      Translator translator = table.getTranslator();
      int cdcnt = table.getColumnCount();
      int rcnt = table.getRowCount();

      Workbook wb = new HSSFWorkbook();
      headerCellStyle = getHeaderCellStyle(wb);

      String tableExportTitle = translator.translate("table.export.title");
      Sheet exportSheet = wb.createSheet(tableExportTitle);
      createHeader(table, translator, cdcnt, exportSheet);
      createData(table, cdcnt, rcnt, exportSheet);

      return getMediaResourceEBL().createMediaResourceFromDocument(wb);
  }
 
Example #4
Source File: ExportResponsesBeanTest.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@Test
public void testGetAsWorkbookWide() {
    ExportResponsesBean bean = new ExportResponsesBean(wac);
    byte[] xlsData = null;
    List<List<Object>> spreadsheetData = null;
    Workbook wb = null;

    // huge test (300 columns x 5 rows)
    spreadsheetData = new ArrayList<List<Object>>();
    for (int i = 0; i < 5; i++) {
        List<Object> row = new ArrayList<Object>();
        for (int j = 0; j < 300; j++) {
            row.add("Item:"+i+":"+j);
        }
        spreadsheetData.add( row );
    }
    addSheetHeader(spreadsheetData);

    wb = bean.getAsWorkbook(spreadsheetData);
    Assert.assertNotNull(wb);
    Assert.assertNotNull(wb.getSheet("responses"));
    xlsData = wbToBytes(wb);
    Assert.assertNotNull(xlsData);
}
 
Example #5
Source File: OriginsSheetV0d9d4.java    From tools with Apache License 2.0 6 votes vote down vote up
public static void create(Workbook wb, String sheetName) {
	int sheetNum = wb.getSheetIndex(sheetName);
	if (sheetNum >= 0) {
		wb.removeSheetAt(sheetNum);
	}
	
	CellStyle headerStyle = AbstractSheet.createHeaderStyle(wb);
	CellStyle centerStyle = AbstractSheet.createCenterStyle(wb);
	CellStyle wrapStyle = AbstractSheet.createLeftWrapStyle(wb);
	Sheet sheet = wb.createSheet(sheetName);
	Row row = sheet.createRow(0);
	for (int i = 0; i < HEADER_TITLES.length; i++) {
		sheet.setColumnWidth(i, COLUMN_WIDTHS[i]*256);
		if (LEFT_WRAP[i]) {
			sheet.setDefaultColumnStyle(i, wrapStyle);
		} else if (CENTER_NOWRAP[i]) {
			sheet.setDefaultColumnStyle(i, centerStyle);
		}
		Cell cell = row.createCell(i);
		cell.setCellStyle(headerStyle);
		cell.setCellValue(HEADER_TITLES[i]);
	}
	Row dataRow = sheet.createRow(1);
	Cell ssVersionCell = dataRow.createCell(SPREADSHEET_VERSION_COL);
	ssVersionCell.setCellValue(SPDXSpreadsheet.CURRENT_VERSION);
}
 
Example #6
Source File: CreatorSheet.java    From tools with Apache License 2.0 6 votes vote down vote up
/**
 * @param wb
 * @param sheetName
 */
public static void create(Workbook wb, String sheetName) {
	int sheetNum = wb.getSheetIndex(sheetName);
	if (sheetNum >= 0) {
		wb.removeSheetAt(sheetNum);
	}
	Sheet sheet = wb.createSheet(sheetName);
	CellStyle headerStyle = AbstractSheet.createHeaderStyle(wb);
	CellStyle defaultStyle = AbstractSheet.createLeftWrapStyle(wb);
	Row row = sheet.createRow(0);
	for (int i = 0; i < MultiDocumentSpreadsheet.MAX_DOCUMENTS; i++) {
		sheet.setColumnWidth(i, COL_WIDTH*256);
		sheet.setDefaultColumnStyle(i, defaultStyle);
		Cell cell = row.createCell(i);
		cell.setCellStyle(headerStyle);
	}
}
 
Example #7
Source File: ExcelHandlerTest.java    From development with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #8
Source File: AnnotationsSheet.java    From tools with Apache License 2.0 6 votes vote down vote up
public static void create(Workbook wb, String sheetName) {
	int sheetNum = wb.getSheetIndex(sheetName);
	if (sheetNum >= 0) {
		wb.removeSheetAt(sheetNum);
	}
	Sheet sheet = wb.createSheet(sheetName);
	CellStyle headerStyle = AbstractSheet.createHeaderStyle(wb);
	CellStyle centerStyle = AbstractSheet.createCenterStyle(wb);
	CellStyle wrapStyle = AbstractSheet.createLeftWrapStyle(wb);
	Row row = sheet.createRow(0);
	for (int i = 0; i < HEADER_TITLES.length; i++) {
		sheet.setColumnWidth(i, COLUMN_WIDTHS[i]*256);
		if (LEFT_WRAP[i]) {
			sheet.setDefaultColumnStyle(i, wrapStyle);
		} else if (CENTER_NOWRAP[i]) {
			sheet.setDefaultColumnStyle(i, centerStyle);
		}
		Cell cell = row.createCell(i);
		cell.setCellStyle(headerStyle);
		cell.setCellValue(HEADER_TITLES[i]);
	}
}
 
Example #9
Source File: PerFileSheetV2d2.java    From tools with Apache License 2.0 6 votes vote down vote up
public static void create(Workbook wb, String sheetName) {
	int sheetNum = wb.getSheetIndex(sheetName);
	if (sheetNum >= 0) {
		wb.removeSheetAt(sheetNum);
	}
	Sheet sheet = wb.createSheet(sheetName);
	CellStyle headerStyle = AbstractSheet.createHeaderStyle(wb);	
	CellStyle centerStyle = AbstractSheet.createCenterStyle(wb);
	CellStyle wrapStyle = AbstractSheet.createLeftWrapStyle(wb);
	Row row = sheet.createRow(0);
	for (int i = 0; i < HEADER_TITLES.length; i++) {
		sheet.setColumnWidth(i, COLUMN_WIDTHS[i]*256);
		if (LEFT_WRAP[i]) {
			sheet.setDefaultColumnStyle(i, wrapStyle);
		} else if (CENTER_NOWRAP[i]) {
			sheet.setDefaultColumnStyle(i, centerStyle);
		}
		Cell cell = row.createCell(i);
		cell.setCellStyle(headerStyle);
		cell.setCellValue(HEADER_TITLES[i]);
	}
}
 
Example #10
Source File: ExcelExportServer.java    From jeasypoi with Apache License 2.0 6 votes vote down vote up
/**
 * 创建 表头改变
 * 
 * @param entity
 * @param sheet
 * @param workbook
 * @param feildWidth
 */
public int createHeaderRow(ExportParams entity, Sheet sheet, Workbook workbook, int feildWidth) {
	Row row = sheet.createRow(0);
	row.setHeight(entity.getTitleHeight());
	createStringCell(row, 0, entity.getTitle(), getExcelExportStyler().getHeaderStyle(entity.getHeaderColor()), null);
	for (int i = 1; i <= feildWidth; i++) {
		createStringCell(row, i, "", getExcelExportStyler().getHeaderStyle(entity.getHeaderColor()), null);
	}
	sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, feildWidth));
	if (entity.getSecondTitle() != null) {
		row = sheet.createRow(1);
		row.setHeight(entity.getSecondTitleHeight());
		CellStyle style = workbook.createCellStyle();
		style.setAlignment(CellStyle.ALIGN_RIGHT);
		createStringCell(row, 0, entity.getSecondTitle(), style, null);
		for (int i = 1; i <= feildWidth; i++) {
			createStringCell(row, i, "", getExcelExportStyler().getHeaderStyle(entity.getHeaderColor()), null);
		}
		sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, feildWidth));
		return 2;
	}
	return 1;
}
 
Example #11
Source File: ImportDemoDataServiceImpl.java    From axelor-open-suite with GNU Affero General Public License v3.0 6 votes vote down vote up
private boolean validateExcel(File excelFile, FileOutputStream out)
    throws FileNotFoundException, IOException, AxelorException {
  Workbook workBook = new XSSFWorkbook(new FileInputStream(excelFile));
  boolean flag = true;
  for (int i = 0; i < workBook.getNumberOfSheets(); i++) {

    Sheet sheet = workBook.getSheetAt(i);
    StringBuilder errorList = new StringBuilder();
    errorList.append("\n" + "Sheet : " + sheet.getSheetName());

    if (!this.validateSheet(sheet, errorList)) {
      out.write(errorList.toString().getBytes());

      flag = false;
      out.write("\n".getBytes());
    }
  }

  return flag;
}
 
Example #12
Source File: RosterPOIEntityProvider.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * Gets the output data.
 *
 * Does not require a HTTP request/response
 *
 * @param out
 * @param reference
 * @param parameters
 * @throws IOException
 */
@EntityCustomAction(action = "get-export", viewKey = EntityView.VIEW_SHOW)
public ActionReturn getExport(final OutputStream out, final EntityReference reference,
		final Map<String, Object> parameters) {

	final String userId = getUserId(reference);
	final String siteId = getSiteId(reference);

	try {
		if (this.sakaiProxy.hasUserSitePermission(userId, RosterFunctions.ROSTER_FUNCTION_EXPORT, siteId)) {
			final RosterSite site = getSite(reference, siteId);
			final Workbook workbook = getExportData(userId, site, parameters);
			workbook.write(out);
			out.close();
			final ActionReturn actionReturn = new ActionReturn("base64",
					"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", out);
			return actionReturn;

		} else {
			throw new EntityException(MSG_NO_EXPORT_PERMISSION, reference.getReference());
		}
	} catch (final IOException e) {
		log.error(MSG_NO_FILE_CREATED, e);
		throw new EntityException(MSG_NO_FILE_CREATED, reference.getReference());
	}
}
 
Example #13
Source File: AbstractExcelFactory.java    From myexcel with Apache License 2.0 6 votes vote down vote up
/**
 * 初始化默认单元格样式
 *
 * @param workbook workbook
 */
protected void initCellStyle(Workbook workbook) {
    if (useDefaultStyle) {
        defaultCellStyleMap = new EnumMap<>(HtmlTableParser.HtmlTag.class);
        defaultCellStyleMap.put(HtmlTableParser.HtmlTag.th, new ThDefaultCellStyle().supply(workbook));
        defaultCellStyleMap.put(HtmlTableParser.HtmlTag.td, new TdDefaultCellStyle().supply(workbook));
        defaultCellStyleMap.put(HtmlTableParser.HtmlTag.link, new LinkDefaultCellStyle().supply(workbook));
    } else {
        if (workbook instanceof HSSFWorkbook) {
            HSSFPalette palette = ((HSSFWorkbook) workbook).getCustomPalette();
            customColor = new CustomColor(true, palette);
        } else {
            customColor = new CustomColor();
        }
    }
}
 
Example #14
Source File: NodeProcessServiceImpl.java    From cymbal with Apache License 2.0 6 votes vote down vote up
private List<Node> getNodesFromExcelFile(final String excelFilePath) {
    List<Node> nodes = new ArrayList<>();
    try (Workbook workbook = new XSSFWorkbook(new FileInputStream(excelFilePath))) {
        Sheet sheet = workbook.getSheetAt(0);

        for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
            Row currentRow = sheet.getRow(rowNum);
            if (Objects.isNull(currentRow.getCell(0)) || Strings
                    .isNullOrEmpty(currentRow.getCell(0).getStringCellValue())) {
                break;
            }
            nodes.add(getNodeFromExcelRow(currentRow));
        }

        if (nodes.isEmpty()) {
            throw new ParseExcelFileException("No node info in uploaded excel file.");
        }
        return nodes;
    } catch (final IOException | IllegalArgumentException e) {
        throw new ParseExcelFileException(e);
    }
}
 
Example #15
Source File: FileExportUtil.java    From myexcel with Apache License 2.0 6 votes vote down vote up
/**
 * 导出
 *
 * @param workbook workbook
 * @param file     file
 * @throws IOException IOException
 */
public static void export(Workbook workbook, File file) throws IOException {
    String suffix = Constants.XLSX;
    if (workbook instanceof HSSFWorkbook) {
        if (file.getName().endsWith(suffix)) {
            String absolutePath = file.getAbsolutePath();
            file = Paths.get(absolutePath.substring(0, absolutePath.length() - 1)).toFile();
        }
        suffix = Constants.XLS;
    }
    if (!file.getName().endsWith(suffix)) {
        file = Paths.get(file.getAbsolutePath() + suffix).toFile();
    }
    try (OutputStream os = new FileOutputStream(file)) {
        workbook.write(os);
    } finally {
        if (workbook instanceof SXSSFWorkbook) {
            ((SXSSFWorkbook) workbook).dispose();
        }
        workbook.close();
    }
}
 
Example #16
Source File: OriginsSheetV1d2.java    From tools with Apache License 2.0 6 votes vote down vote up
public static void create(Workbook wb, String sheetName) {
	int sheetNum = wb.getSheetIndex(sheetName);
	if (sheetNum >= 0) {
		wb.removeSheetAt(sheetNum);
	}
	
	CellStyle headerStyle = AbstractSheet.createHeaderStyle(wb);
	CellStyle centerStyle = AbstractSheet.createCenterStyle(wb);
	CellStyle wrapStyle = AbstractSheet.createLeftWrapStyle(wb);
	Sheet sheet = wb.createSheet(sheetName);
	Row row = sheet.createRow(0);
	for (int i = 0; i < HEADER_TITLES.length; i++) {
		sheet.setColumnWidth(i, COLUMN_WIDTHS[i]*256);
		if (LEFT_WRAP[i]) {
			sheet.setDefaultColumnStyle(i, wrapStyle);
		} else if (CENTER_NOWRAP[i]) {
			sheet.setDefaultColumnStyle(i, centerStyle);
		}
		Cell cell = row.createCell(i);
		cell.setCellStyle(headerStyle);
		cell.setCellValue(HEADER_TITLES[i]);
	}
	Row dataRow = sheet.createRow(1);
	Cell ssVersionCell = dataRow.createCell(SPREADSHEET_VERSION_COL);
	ssVersionCell.setCellValue(SPDXSpreadsheet.CURRENT_VERSION);
}
 
Example #17
Source File: DefaultStreamExcelBuilderTest.java    From myexcel with Apache License 2.0 6 votes vote down vote up
@Test
void continueBuild() throws Exception {
    DefaultStreamExcelBuilder<CommonPeople> excelBuilder = null;
    try {
        excelBuilder = DefaultStreamExcelBuilder.of(CommonPeople.class)
                .fixedTitles()
                .widths(15, 20, 25, 30)
                .start();
        data(excelBuilder, 10000);
        Workbook workbook = excelBuilder.build();

        excelBuilder = DefaultStreamExcelBuilder.of(CommonPeople.class, workbook)
                .fixedTitles()
                .start();
        data(excelBuilder, 10000);
        FileExportUtil.export(workbook, new File(TEST_OUTPUT_DIR + "continue_build.xlsx"));
    } catch (Throwable e) {
        if (excelBuilder != null) {
            excelBuilder.clear();
        }
        throw new RuntimeException(e);
    }
}
 
Example #18
Source File: PerFileSheet.java    From tools with Apache License 2.0 6 votes vote down vote up
/**
 * Open a specific version of the PerFileSheet
 * @param workbook
 * @param perFileSheetName
 * @param version spreadsheet version
 * @return
 */
public static PerFileSheet openVersion(Workbook workbook,
		String perFileSheetName, String version) {
	if (version.compareToIgnoreCase(SPDXSpreadsheet.VERSION_0_9_4) <= 0) {
		return new PerFileSheetV09d3(workbook, perFileSheetName, version);
	} else if (version.compareToIgnoreCase(SPDXSpreadsheet.VERSION_1_1_0) <= 0) {
		return new PerFileSheetV1d1(workbook, perFileSheetName, version);
	} else if (version.compareToIgnoreCase(SPDXSpreadsheet.VERSION_1_2_0) <=0) {
		return new PerFileSheetV1d2(workbook, perFileSheetName, version);
	} else if (version.compareTo(SPDXSpreadsheet.VERSION_2_1_0) <= 0) {
		// Note: No changes in version 2.1 for the file
		return new PerFileSheetV2d0(workbook, perFileSheetName, version);
	} else {
		return new PerFileSheetV2d2(workbook, perFileSheetName, version);
	}
}
 
Example #19
Source File: JeecgTemplateExcelView.java    From jeasypoi with Apache License 2.0 6 votes vote down vote up
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
	String codedFileName = "临时文件";
	Workbook workbook = ExcelExportUtil.exportExcel((TemplateExportParams) model.get(TemplateExcelConstants.PARAMS), (Class<?>) model.get(TemplateExcelConstants.CLASS), (List<?>) model.get(TemplateExcelConstants.LIST_DATA), (Map<String, Object>) model.get(TemplateExcelConstants.MAP_DATA));
	if (model.containsKey(NormalExcelConstants.FILE_NAME)) {
		codedFileName = (String) model.get(NormalExcelConstants.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();
}
 
Example #20
Source File: ReviewersSheet.java    From tools with Apache License 2.0 6 votes vote down vote up
public static void create(Workbook wb, String sheetName) {
	int sheetNum = wb.getSheetIndex(sheetName);
	if (sheetNum >= 0) {
		wb.removeSheetAt(sheetNum);
	}
	Sheet sheet = wb.createSheet(sheetName);
	CellStyle headerStyle = AbstractSheet.createHeaderStyle(wb);
	CellStyle centerStyle = AbstractSheet.createCenterStyle(wb);
	CellStyle wrapStyle = AbstractSheet.createLeftWrapStyle(wb);
	Row row = sheet.createRow(0);
	for (int i = 0; i < HEADER_TITLES.length; i++) {
		sheet.setColumnWidth(i, COLUMN_WIDTHS[i]*256);
		if (LEFT_WRAP[i]) {
			sheet.setDefaultColumnStyle(i, wrapStyle);
		} else if (CENTER_NOWRAP[i]) {
			sheet.setDefaultColumnStyle(i, centerStyle);
		}
		Cell cell = row.createCell(i);
		cell.setCellStyle(headerStyle);
		cell.setCellValue(HEADER_TITLES[i]);
	}
}
 
Example #21
Source File: VelocityExcelBuilderExampleController.java    From myexcel with Apache License 2.0 5 votes vote down vote up
/**
 * encrypt .xlsx excel
 *
 * @param response response
 */
@GetMapping("/velocity/autoWidth/example")
public void buildWithAutoWidth(HttpServletResponse response) throws Exception {
    try (ExcelBuilder excelBuilder = new VelocityExcelBuilder()) {
        Map<String, Object> dataMap = this.getDataMap();

        Workbook workbook = excelBuilder
                .template("/templates/velocityToExcelExample.vm")
                .useDefaultStyle()
                .autoWidthStrategy(AutoWidthStrategy.AUTO_WIDTH)
                .build(dataMap);
        AttachmentExportUtil.export(workbook, "velocity_excel", response);
    }
}
 
Example #22
Source File: BeetlExcelBuilderExampleController.java    From myexcel with Apache License 2.0 5 votes vote down vote up
/**
 * build .xls excel
 *
 * @param response response
 */
@GetMapping("/beetl/xls/example")
public void buildWithXLS(HttpServletResponse response) throws IOException {
    try (ExcelBuilder excelBuilder = new BeetlExcelBuilder()) {
        Map<String, Object> dataMap = this.getDataMap();

        Workbook workbook = excelBuilder
                .template("/templates/beetlToExcelExample.btl")
                .workbookType(WorkbookType.XLS)
                .useDefaultStyle()
                .build(dataMap);
        AttachmentExportUtil.export(workbook, "beetl_excel", response);
    }
}
 
Example #23
Source File: DownloadEventBean.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
private void excelSpreadsheet(OutputStream os, List<SignupMeetingWrapper> meetingWrappers,
		String downloadType) throws IOException {
	EventWorksheet worksheet = new EventWorksheet(getSakaiFacade());
	worksheet.setSignupMeetingService(getSignupMeetingService());

	Workbook wb = worksheet.getEventWorkbook(meetingWrappers, downloadType);
	wb.write(os);
}
 
Example #24
Source File: AbstractXlsxStreamingView.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * This implementation disposes of the {@link SXSSFWorkbook} when done with rendering.
 * @see org.apache.poi.xssf.streaming.SXSSFWorkbook#dispose()
 */
@Override
protected void renderWorkbook(Workbook workbook, HttpServletResponse response) throws IOException {
	super.renderWorkbook(workbook, response);

	// Dispose of temporary files in case of streaming variant...
	((SXSSFWorkbook) workbook).dispose();
}
 
Example #25
Source File: ImportBaseService.java    From easypoi with Apache License 2.0 5 votes vote down vote up
public void saveThisExcel(ImportParams params, Class<?> pojoClass, boolean isXSSFWorkbook,
                          Workbook book) throws Exception {
    String path = PoiPublicUtil.getWebRootPath(getSaveExcelUrl(params, pojoClass));
    File savefile = new File(path);
    if (!savefile.exists()) {
        savefile.mkdirs();
    }
    SimpleDateFormat format = new SimpleDateFormat("yyyMMddHHmmss");
    FileOutputStream fos = new FileOutputStream(path + "/" + format.format(new Date()) + "_"
                                                + Math.round(Math.random() * 100000)
                                                + (isXSSFWorkbook == true ? ".xlsx" : ".xls"));
    book.write(fos);
    fos.close();
}
 
Example #26
Source File: Exporter.java    From ramus with GNU General Public License v3.0 5 votes vote down vote up
private static CellStyle createBorderedStyle(Workbook wb) {
    CellStyle style = wb.createCellStyle();
    style.setBorderRight(CellStyle.BORDER_THIN);
    style.setRightBorderColor(IndexedColors.BLACK.getIndex());
    style.setBorderBottom(CellStyle.BORDER_THIN);
    style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
    style.setBorderLeft(CellStyle.BORDER_THIN);
    style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
    style.setBorderTop(CellStyle.BORDER_THIN);
    style.setTopBorderColor(IndexedColors.BLACK.getIndex());
    return style;
}
 
Example #27
Source File: ExcelToQuestionUtils.java    From Exam-Online with Apache License 2.0 5 votes vote down vote up
public static List<Question> readQuestions(InputStream inputStream) 
		throws EncryptedDocumentException, InvalidFormatException, IOException {
	
	Workbook workbook = WorkbookFactory.create(inputStream);
	List<Question> questions = readQuestions(workbook.getSheetAt(0)); 
	workbook.close();
	return questions;
}
 
Example #28
Source File: ExcelExportStylerBorderImpl.java    From jeasypoi with Apache License 2.0 5 votes vote down vote up
@Override
public CellStyle stringNoneStyle(Workbook workbook, boolean isWarp) {
	CellStyle style = workbook.createCellStyle();
	style.setBorderLeft((short) 1); // 左边框
	style.setBorderRight((short) 1); // 右边框
	style.setBorderBottom((short) 1);
	style.setBorderTop((short) 1);
	style.setAlignment(CellStyle.ALIGN_CENTER);
	style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
	style.setDataFormat(STRING_FORMAT);
	if (isWarp) {
		style.setWrapText(true);
	}
	return style;
}
 
Example #29
Source File: ImportBaseService.java    From jeasypoi with Apache License 2.0 5 votes vote down vote up
public void saveThisExcel(ImportParams params, Class<?> pojoClass, boolean isXSSFWorkbook, Workbook book) throws Exception {
	String path = PoiPublicUtil.getWebRootPath(getSaveExcelUrl(params, pojoClass));
	File savefile = new File(path);
	if (!savefile.exists()) {
		savefile.mkdirs();
	}
	SimpleDateFormat format = new SimpleDateFormat("yyyMMddHHmmss");
	FileOutputStream fos = new FileOutputStream(path + "/" + format.format(new Date()) + "_" + Math.round(Math.random() * 100000) + (isXSSFWorkbook == true ? ".xlsx" : ".xls"));
	book.write(fos);
	fos.close();
}
 
Example #30
Source File: ExcelExportServer.java    From autopoi with Apache License 2.0 5 votes vote down vote up
private int createHeaderAndTitle(ExportParams entity, Sheet sheet, Workbook workbook, List<ExcelExportEntity> excelParams) {
	int rows = 0, feildWidth = getFieldWidth(excelParams);
	if (entity.getTitle() != null) {
		rows += createHeaderRow(entity, sheet, workbook, feildWidth);
	}
	rows += createTitleRow(entity, sheet, workbook, rows, excelParams);
	sheet.createFreezePane(0, rows, 0, rows);
	return rows;
}