jxl 删除excel重复的行

思路:先从前到后检索excel文件,找出重复的行的行号(从0开始),然后删除之;

注意:使用removeRow(int row)删除多行时,需要从后往前遍历,因为从前往后删除时行号就乱了,跟检索时的行号不一致了,导致误删或漏删,具体见代码第79-82行;


	/**
	 * 得到excel中重复的行号,判重标准为第0列数据
	 * @param filename
	 * @return
	 */
	public static final ArrayList<Integer> getDuplicateRows(String filename) {
		
		/**
		 * 从前往后找出重复的行号
		 */
		ArrayList<String> ids = new ArrayList<String>();
		ArrayList<Integer> duplicateRows = new ArrayList<Integer>();

		File file = new File(filename);

		// 读excel文件
		if (file.exists() == true) {

			// 文件存在,读取其中原始数据
			Workbook book = null;
			try {
				System.out.println("excel文件存在: " + file.getAbsolutePath());
				book = Workbook.getWorkbook(file);
			} catch (BiffException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			Sheet sheet = book.getSheet(0);

			int rows = sheet.getRows();
			
			// 取出excel中的第0列数据
			for (int i = 0; i < rows; i++) {
				
				// 第0列数据
				Cell idCell = sheet.getCell(0, i);
				String id = idCell.getContents().trim();
								
				if (ids.contains(id) == false) {
					ids.add(id);
				} else {
					duplicateRows.add(i);
				}
			}
			
			// 关闭文件
			book.close();
			
			// 释放空间
			ids.clear();
		} else {
			System.err.println("文件不存在。。。");
			return duplicateRows;
		}
		
		return duplicateRows;
	}
	
	/**
	 * 删除filename文件rowsToRemove中的行
	 * @param filename
	 * @param rowsToRemove
	 * @return
	 */
	public static int removeRows(String filename, ArrayList<Integer> rowsToRemove) {
		Workbook wb = null;
		WritableWorkbook book = null;
		WritableSheet wsheet = null;
		File f = new File(filename);

		try {
			wb = Workbook.getWorkbook(f);
			book = Workbook.createWorkbook(f, wb);
			wsheet = book.getSheet(0);
			
			System.out.println("to delete rows: " + rowsToRemove);
			
			for (int i = rowsToRemove.size() - 1; i >= 0; i--) {
				int row = rowsToRemove.get(i);
				wsheet.removeRow(row);
			}
			
			// 关闭文件
			book.write();
			book.close();
			
			// 释放空间
			rowsToRemove.clear();

		} catch (BiffException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (WriteException e) {
			e.printStackTrace();
		}
		
		return 0;
	}
	
	/**
	 * 删除某excel中相同的行,从前往后检索,删除后面重复的行
	 * 判重条件是第0列数据
	 * @param filename
	 * @return
	 */
	public static int removeDuplicateRows(String filename) {
		
		// 从前往后找出重复的行号
		ArrayList<Integer> duplicateRows = getDuplicateRows(filename);
		
		// 根据行号删除重复的行
		removeRows(filename, duplicateRows);
		
		return 0;
	}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值