码迷,mamicode.com
首页 > 其他好文 > 详细

read excel to list

时间:2016-05-27 09:26:27      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:

public static List<List<String>> readExcelToList(String path, String sheetName, int rowNum, int colNum) {
		List<List<String>> resultList = new ArrayList<List<String>>();
		InputStream is = null;
		try {
			if (!new File(path).exists()) {
				return null;
			}

			is = new FileInputStream(path);
			Workbook wb = new HSSFWorkbook(is);
			Sheet sheet = wb.getSheet(sheetName);
			if (sheet != null) {
				if (rowNum <= 0) {
					rowNum = sheet.getLastRowNum() + 1;
				}
				for (int j = 0; j < rowNum; j++) {
					List<String> rowList = new ArrayList<String>();
					Row row = sheet.getRow(j);
					if (row == null) {
						row = sheet.createRow(j);
					}
					if (colNum <= 0) {
						colNum = row.getLastCellNum();
					}

					for (short k = 0; k < colNum; k = (short) (k + 1)) {
						Cell aCell = row.getCell(k);
						String cellVal = "";
						if (aCell == null) {
							aCell = row.createCell(k);
						}
						cellVal = convertCell(aCell);
						rowList.add(cellVal);
					}
					resultList.add(rowList);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (is != null)
					is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}

		return resultList;
	}



 private static String convertCell(Cell cell)
   {
     NumberFormat formater = NumberFormat.getInstance();
     formater.setGroupingUsed(false);
     String cellValue = "";
     if (cell == null) {
       return cellValue;
     }
     switch (cell.getCellType()) {
     case 0:
       cellValue = formater.format(cell.getNumericCellValue());
       break;
     case 1:
       cellValue = cell.getStringCellValue();
       break;
     case 3:
       cellValue = cell.getStringCellValue();
       break;
     case 4:
       cellValue = Boolean.valueOf(cell.getBooleanCellValue()).toString();
       break;
     case 5:
       cellValue = String.valueOf(cell.getErrorCellValue());
       break;
     case 2:
     default:
       cellValue = "";
     }
     return cellValue.trim();
   }

 

read excel to list

标签:

原文地址:http://www.cnblogs.com/zhangxuesong/p/5533380.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!