java读取excel的两种方法(jxl、poi)

jxl实现:

public static void readExcelContent(File file) {
	Workbook book = null;
	Sheet[] sheets = null;
	StringBuffer sbf = new StringBuffer();
	StringBuffer sBuffer = new StringBuffer();
	try {
		book = Workbook.getWorkbook(file);
		sheets = book.getSheets();
		//获得第一个sheet(每个excel可能有多个sheet)
		//sheet = book.getSheet(0); 
		for(int m=0; m<sheets.length; m++) {
			int rowsCount = sheets[m].getRows();
			int columnsCount = sheets[m].getColumns();
			for (int i = 1; i < rowsCount; i++) {
				for (int j = 0; j < columnsCount; j++) {
					sBuffer.append(sheets[m].getCell(j, i).getContents()
							+ (j + 1 < columnsCount ? "\t" : ""));
				}
				sBuffer.append(LogConstant.LINE_SEPERATOR);
			}
		}
	} catch (BiffException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
	sbf.append(sBuffer);
	System.out.println(sbf.toString());
}

poi实现:

public static void readExcelContent(File file) {
	FileInputStream is = null;
	StringBuffer sbf = new StringBuffer();
	StringBuffer sBuffer = new StringBuffer();
	try {
		is = new FileInputStream(file);
		HSSFWorkbook wb = new HSSFWorkbook(is);
		// 获取excel中sheet的个数
		int sheetNum = wb.getNumberOfSheets();
		for (int m = 0; m < sheetNum; m++) {
			HSSFSheet sheet = wb.getSheetAt(m);
			//获得该sheet中行数
			int rowsCount = sheet.getPhysicalNumberOfRows();
			for (int i = 1; i < rowsCount; i++) {
				HSSFRow sheetRow = sheet.getRow(i);
				for (int j = 0; j < sheetRow.getPhysicalNumberOfCells(); j++) {
					HSSFCell cell = sheetRow.getCell((short) j);
					if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
						sBuffer.append(cell.getStringCellValue().toString()
								+ (j + 1 < sheetRow.getPhysicalNumberOfCells() ? "\t" : ""));
					}
				}
				sBuffer.append(LogConstant.LINE_SEPERATOR);
			}
			sbf.append(sBuffer);
		}
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		if (is != null) {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	System.out.println(sbf.toString());
}



你可能感兴趣的:(java读取excel的两种方法(jxl、poi))