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

The following examples show how to use org.apache.poi.ss.usermodel.Workbook. These examples are extracted from open source projects. 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
@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 2
Source Project: olat   Source File: DefaultXlsTableExporter.java    License: 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 3
Source Project: tools   Source File: PerFileSheetV2d2.java    License: 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 4
Source Project: jeasypoi   Source File: ExcelExportServer.java    License: 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 5
/**
 * 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 6
Source Project: myexcel   Source File: AbstractExcelFactory.java    License: 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 7
Source Project: tools   Source File: OriginsSheetV1d2.java    License: 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 8
Source Project: myexcel   Source File: DefaultStreamExcelBuilderTest.java    License: 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 9
Source Project: tools   Source File: ReviewersSheet.java    License: 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
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 11
Source Project: tools   Source File: AnnotationsSheet.java    License: 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 12
Source Project: development   Source File: ExcelHandlerTest.java    License: 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 13
Source Project: tools   Source File: OriginsSheetV0d9d4.java    License: 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 14
Source Project: tools   Source File: CreatorSheet.java    License: 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 15
Source Project: cymbal   Source File: NodeProcessServiceImpl.java    License: 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 16
Source Project: tools   Source File: PerFileSheet.java    License: 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 17
Source Project: jeasypoi   Source File: JeecgTemplateExcelView.java    License: 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 18
Source Project: myexcel   Source File: FileExportUtil.java    License: 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 19
Source Project: SpringBoot2.0   Source File: PoiUtil.java    License: 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 20
Source Project: carina   Source File: XLSParser.java    License: 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 21
Source Project: olat   Source File: DefaultXlsTableExporter.java    License: Apache License 2.0 5 votes vote down vote up
private CellStyle getHeaderCellStyle(final Workbook wb) {
    CellStyle cellStyle = wb.createCellStyle();
    Font boldFont = wb.createFont();
    boldFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
    cellStyle.setFont(boldFont);
    return cellStyle;
}
 
Example 22
Source Project: excel-io   Source File: CellTemplateTest.java    License: MIT License 5 votes vote down vote up
/**
 * Create custom cell.
 * @throws IOException If fails
 */
@Test
public void createsCustomCell() throws IOException {
    try (final Workbook workbook = new XSSFWorkbook()) {
        final Cell cell = new CellTemplateTest.GrayTextCell()
            .attachTo(workbook.createSheet().createRow(0));
        MatcherAssert.assertThat(
            cell.getCellStyle().getFillForegroundColor(),
            Matchers.equalTo(IndexedColors.GREY_25_PERCENT.getIndex())
        );
    }
}
 
Example 23
Source Project: excel-streaming-reader   Source File: StreamingSheetTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testEmptyCellShouldHaveGeneralStyle() throws Exception {
  try(
      InputStream is = new FileInputStream(new File("src/test/resources/large.xlsx"));
      Workbook workbook = StreamingReader.builder().open(is);
  ) {
    assertEquals(1, workbook.getNumberOfSheets());
    Sheet sheet = workbook.getSheetAt(0);
    Row row = sheet.iterator().next();
    assertEquals(CellType.NUMERIC, row.getCell(0).getCellType());
    assertNotNull(row.getCell(0).getCellStyle());
  }
}
 
Example 24
Source Project: olat   Source File: DefaultXlsTableExporter.java    License: Apache License 2.0 5 votes vote down vote up
private CellStyle getHeaderCellStyle(final Workbook wb) {
    CellStyle cellStyle = wb.createCellStyle();
    Font boldFont = wb.createFont();
    boldFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
    cellStyle.setFont(boldFont);
    return cellStyle;
}
 
Example 25
Source Project: onetwo   Source File: DefaultRowMapperWorkbookReader.java    License: Apache License 2.0 5 votes vote down vote up
public Map<String, List<Object>> readData(File file, int startSheet, int readCount){
	Assert.notNull(file, "file can not be null");
	try {
		if(!file.exists()){
			throw new FileNotFoundException("文件不存在:" + file.getPath());
		}
		
		Workbook workbook = createWorkbook(file);
		
		return readData(workbook, startSheet, readCount);
	} catch (Exception e) {
		throw ExcelUtils.wrapAsUnCheckedException("read excel file error.", e);
	}
}
 
Example 26
Source Project: lams   Source File: LinkTable.java    License: GNU General Public License v2.0 5 votes vote down vote up
public int linkExternalWorkbook(String name, Workbook externalWorkbook) {
       int extBookIndex = getExternalWorkbookIndex(name);
       if (extBookIndex != -1) {
           // Already linked!
           return extBookIndex;
       }
       
       // Create a new SupBookRecord
       String[] sheetNames = new String[externalWorkbook.getNumberOfSheets()];
       for (int sn=0; sn<sheetNames.length; sn++) {
           sheetNames[sn] = externalWorkbook.getSheetName(sn);
       }
       String url = "\000" + name;
       ExternalBookBlock block = new ExternalBookBlock(url, sheetNames);
       
       // Add it into the list + records
       extBookIndex = extendExternalBookBlocks(block);

       // add the created SupBookRecord before ExternSheetRecord
       int idx = findFirstRecordLocBySid(ExternSheetRecord.sid);
       if (idx == -1) {
           idx = _workbookRecordList.size();
       }
       _workbookRecordList.add(idx, block.getExternalBookRecord());
       
       // Setup links for the sheets
       for (int sn=0; sn<sheetNames.length; sn++) {
           _externSheetRecord.addRef(extBookIndex, sn, sn);
       }
       
       // Report where it went
       return extBookIndex;
}
 
Example 27
private int
  clipAndEncodeImage( final Image image, final long width, final long height, final double deviceScaleFactor )
    throws UnsupportedEncoderException, IOException {
  final int imageWidth = (int) StrictGeomUtility.toExternalValue( width );
  final int imageHeight = (int) StrictGeomUtility.toExternalValue( height );
  // first clip.
  final BufferedImage bi = ImageUtils.createTransparentImage( imageWidth, imageHeight );
  final Graphics2D graphics = (Graphics2D) bi.getGraphics();
  graphics.scale( deviceScaleFactor, deviceScaleFactor );

  if ( image instanceof BufferedImage ) {
    if ( graphics.drawImage( image, null, null ) == false ) {
      logger.debug( "Failed to render the image. This should not happen for BufferedImages" ); // NON-NLS
    }
  } else {
    final WaitingImageObserver obs = new WaitingImageObserver( image );
    obs.waitImageLoaded();

    while ( graphics.drawImage( image, null, obs ) == false ) {
      obs.waitImageLoaded();
      if ( obs.isError() ) {
        logger.warn( "Error while loading the image during the rendering." ); // NON-NLS
        break;
      }
    }
  }

  graphics.dispose();
  final byte[] data = RenderUtility.encodeImage( bi );
  return printerBase.getWorkbook().addPicture( data, Workbook.PICTURE_TYPE_PNG );
}
 
Example 28
Source Project: xcelite   Source File: CellStylesBank.java    License: Apache License 2.0 5 votes vote down vote up
public static CellStyles get(Workbook workbook) {
  if (cellStylesMap.containsKey(workbook)) {
    return cellStylesMap.get(workbook);
  }
  CellStyles cellStyles = new CellStyles(workbook);
  cellStylesMap.put(workbook, cellStyles);
  return cellStyles;
}
 
Example 29
Source Project: autopoi   Source File: StylerHelper.java    License: Apache License 2.0 5 votes vote down vote up
private void prontFonts(Workbook wb) {
	for (short i = 0, le = wb.getNumberOfFonts(); i <= le; i++) {
		Font font = wb.getFontAt(i);
		out.format(".%s .%s {%n", DEFAULTS_CLASS, "font_" + i + "_" + cssRandom);
		fontStyle(font);
		out.format("}%n");
	}

}
 
Example 30
/**
 * use default-style excel builder
 *
 * @param response response
 */
@GetMapping("/freemarker/defaultStyle/example")
public void buildWithDefaultStyle(HttpServletResponse response) throws IOException {
    try (ExcelBuilder excelBuilder = new FreemarkerExcelBuilder()) {
        Map<String, Object> dataMap = this.getDataMap();

        Workbook workbook = excelBuilder
                .template("/templates/freemarkerToExcelExample.ftl")
                .useDefaultStyle()
                .build(dataMap);
        AttachmentExportUtil.export(workbook, "freemarker_excel", response);
    }
}