java调用Excel中Find的实现方法(jacob)

		ActiveXComponent activeXApp = null;
		try {
			activeXApp = new ActiveXComponent("Excel.Application");
			activeXApp.setProperty("Visible", new Variant(false));
			activeXApp.setProperty("DisplayAlerts", new Variant(false));

			Dispatch workbooks = activeXApp.getProperty("Workbooks").toDispatch();

			String xlsFilePath = null;
			String value = null;

			Dispatch sheet = null;
			Dispatch sheets = null;
			Dispatch usedRange = null;

			Variant result = null;
			Variant address = null;
			Variant nextResult = null;
			Variant nextAddress = null;

			Dispatch workbook = Dispatch.invoke(workbooks, "Open", 
					Dispatch.Method, new Object[] { xlsFilePath, new Variant(false),
					new Variant(false) }, new int[1]).toDispatch();

			sheets = Dispatch.get(workbook, "Sheets").toDispatch();
			
			int count = Dispatch.get(sheets, "Count").getInt();

			for (int j = 1; j <= count; j++) {

				sheet = Dispatch.invoke(sheets, "Item", Dispatch.Get, 
						new Object[] { new Integer(j) }, new int[1]).toDispatch();

				usedRange = Dispatch.get(sheet, "UsedRange").toDispatch();

				result = Dispatch.invoke(usedRange, "Find", Dispatch.Method, 
						new Object[] { "[*]" }, new int[1]);

				if (!result.isNull()) {
					value = Dispatch.get(result.toDispatch(), "Value").toString();

					address = Dispatch.get(result.toDispatch(), "Address");

					nextResult = Dispatch.invoke(usedRange, "FindNext", 
							Dispatch.Method, new Object[] { result }, new int[1]);
					nextAddress = Dispatch.get(nextResult.toDispatch(), "Address");

					while (!address.toString().equals(nextAddress.toString())) {
						value = Dispatch.get(nextResult.toDispatch(), "Value").toString();

						nextResult = Dispatch.invoke(usedRange, "FindNext", 
								Dispatch.Method, new Object[] { nextResult }, new int[1]);
						nextAddress = Dispatch.get(nextResult.toDispatch(), "Address");
					}
				}
			}
			Dispatch.call(workbook, "Close", new Variant(false));
		} catch (Exception e) {
			throw e;
		} finally {
			if (activeXApp != null) {
				activeXApp.invoke("Quit", new Variant[] {});
			}
			ComThread.Release();
		}

你可能感兴趣的:(java,Excel,J#)