java 导入Excel 为 List

 

  1. 用户需求中曾经有写需要把Excel中的数据导入数据库中,不过每次都要一一对应Excel中的数据然后写程序,太繁琐,  后来想了一下,改成这样的,以后就方便导入数据,直接遍历List就可以把数据导入进来了。使用jxl.jar包进行操作Excel的
  2. /**
    	 * 
    	 * @param filePath 文件路径
    	 * @param clazz 存放的数据是那个对象的数据:类似User.class
    	 * @param field 标题中那个标题对应那个对象中的那个字段:map.add("Excel标题", "user的字段值")
    	 * @return
    	 */
    	private static List getExcel(String filePath, Class clazz,
    			Map<String, String> field) {
    		if (!filePath.endsWith("xls")) {
    			System.out.println("文件不是Excel");
    			return null;
    		}
    		List list = new ArrayList();
    		Workbook wk = null;
    		try {
    			wk = Workbook.getWorkbook(new File(filePath));
    			Sheet sheet = wk.getSheet(0);
    			Map<Integer, String> columnMap = readTitle(field, sheet.getRow(0));
    			if (columnMap == null || columnMap.size() == 0) {
    				System.out.println("没有查到相应的标题");
    				return null;
    			}
    			for (int i = 1; i < sheet.getRows(); i++) {
    				Cell[] cells = sheet.getRow(i);
    				if (cells.length == 0)
    					continue;
    				Set<Map.Entry<Integer, String>> set = columnMap.entrySet();
    				Object obj = clazz.newInstance();
    				for (Iterator<Map.Entry<Integer, String>> iter = set.iterator(); iter
    						.hasNext();) {
    					Map.Entry<Integer, String> entry = iter.next();
    					String fieldValue = cells[entry.getKey()].getContents()
    							.trim();
    					String fieldName = entry.getValue();
    					invokeMethod(clazz, obj, fieldName, fieldValue);
    				}
    				list.add(obj);
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    			return null;
    		} finally {
    			if (wk != null)
    				wk.close();
    		}
    		return list;
    	}
    
    	private static Object invokeMethod(Class<?> clazz, Object instance,
    			String fileName, String fieldValue) throws Exception {
    		Method getMethod = clazz.getMethod("get" + toFirstUpper(fileName));
    		Class<?> paraType = getMethod.getReturnType();
    		Method setMethod = clazz.getMethod("set" + toFirstUpper(fileName),
    				paraType);
    		Object value = transfType(paraType, fieldValue);
    		if (value != null)
    			setMethod.invoke(instance, value);
    		return instance;
    	}
    
    	private static Object transfType(Class<?> paraType, String target) {
    		Object result = null;
    		if (paraType == String.class) {
    			result = target;
    		} else if (paraType == Double.class) {
    			result = new Double(Double.parseDouble(target));
    		} else if (paraType == double.class) {
    			result = Double.parseDouble(target);
    		} else if (paraType == boolean.class) {
    			result = Boolean.parseBoolean(target);
    		} else if (paraType == Boolean.class) {
    			result = Boolean.valueOf(target);
    		} else if (paraType == int.class) {
    			result = Integer.parseInt(target);
    		} else if (paraType == Integer.class) {
    			result = Integer.decode(target);
    		} else if (paraType == long.class) {
    			result = Long.parseLong(target);
    		} else if (paraType == Long.class) {
    			result = Long.decode(target);
    		} else if (paraType == float.class) {
    			result = Float.parseFloat(target);
    		} else if (paraType == Float.class) {
    			result = Float.valueOf(target);
    		}
    		return result;
    	}
    
    	public static String toFirstUpper(String str) {
    		return str.replaceFirst(str.substring(0, 1), str.substring(0, 1)
    				.toUpperCase());
    	}
    
    	private static Map<Integer, String> readTitle(Map<String, String> fieldMap,
    			Cell[] cells) {
    		Map<Integer, String> columnMap = new HashMap<Integer, String>();
    		for (int i = 0; i < cells.length; i++) {
    			String content = cells[i].getContents().trim();
    			String field = fieldMap.get(content);
    			if (field != null) {
    				columnMap.put(i, field);
    			}
    		}
    		return columnMap;
    	}
     

 

以下是使用Java的POI库将Excel数据导入到包含列表的列表中的示例代码: ```java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelImporter { public static void main(String[] args) { String filePath = "path/to/your/excel/file.xlsx"; List<List<String>> dataList = new ArrayList<>(); try (FileInputStream fis = new FileInputStream(new File(filePath)); Workbook workbook = new XSSFWorkbook(fis)) { Sheet sheet = workbook.getSheetAt(0); Iterator<Row> rowIterator = sheet.iterator(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); List<String> rowData = new ArrayList<>(); Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); rowData.add(cell.toString()); } dataList.add(rowData); } } catch (IOException e) { e.printStackTrace(); } // 打印导入的数据 for (List<String> row : dataList) { System.out.println(row); } } } ``` 这段代码将读取指定路径下的Excel文件,并将每行数据存储在一个列表中。最后,将所有行的列表存储在一个包含列表的列表中。你可以根据需要对导入的数据进行进一步的处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值