1. 程式人生 > >Java 讀取excel指定行列資料以及將資料儲存到txt檔案中

Java 讀取excel指定行列資料以及將資料儲存到txt檔案中

在使用的軟體中經常要用到一些資料的匯入匯出,以及準確的定位資料,這些經常會涉及excle表格,因此把今天學習到的關於如何利用Java準確獲取到excle中的某一列資料,同時將此列資料輸出到txt檔案格式中。

使用的jar包:jxl.jar 

相關的API:http://jxl.sourceforge.net/javadoc/index.html(還是比較強大的,感興趣的可以學一下)

1.首先是測試用的excle


2.要求:可以獲取到第一列或者第二列有效資料,即“人物”、“年齡”等標題字元濾去。

jxl的用法在網上有很多,要獲取到全部資訊很簡單,只需要巢狀兩個for迴圈遍歷excel中的每一個元素。

下面來獲取第二列的年齡,只獲取數字,程式碼如下:

public static void readSpecify(File file)throws Exception{
	ArrayList<String> columnList = new ArrayList<String>();
	Workbook readwb = null;
	InputStream io = new FileInputStream(file.getAbsoluteFile());
	readwb = Workbook.getWorkbook(io);
	Sheet readsheet = readwb.getSheet(0);
	int rsRows = readsheet.getRows();
	int rsColumns = readsheet.getColumns();
	for (int i = 1; i < rsRows; i++) {
		Cell cell = readsheet.getCell(1, i);
		columnList.add(cell.getContents());
		System.out.println(columnList);
	}
	String[] ageString = new String[columnList.size()];
	int[] age = new int[ageString.length];
	for (int i = 0; i < columnList.size(); i++) {
		ageString[i] = columnList.get(i);
		age[i] = Integer.parseInt(ageString[i]);
		System.out.println(age[i]);
	}		
}
這段程式碼需要注意的地方是,在第一個for迴圈中,這裡並沒有全部遍歷元素,因為我們明確的知道,需要獲取的是第二列第二行的元素一直到最後一行的元素,所以,for迴圈裡的 i = 1 是代表從第二列開始,readsheet.getCell(1,i)裡的1則表示從第二行開始。這種方式的優點在於能夠快速準確的獲取到值,缺點在於必須得確定起始位置,因為excel的行跟列都是從0開始的。同時cell.getContents返回值型別為java.lang.string,所以需要根據具體的資料型別進行轉換。

效果如下:


3.要求:將excle檔案中需要的行列資料匯出到另一個excel或者txt文字中。

具體到這個例子,將第二列資料匯出到excel和txt檔案中,儲存位置為當期資料夾,程式碼如下:

public static void copy_excel(File file) throws Exception {
	FileWriter fWriter = null;
	PrintWriter out = null;
	String fliename = file.getName().replace(".xls", "");
	fWriter = new FileWriter(file.getParent() + "/" + fliename + ".txt");//輸出格式為.txt
	fWriter = new FileWriter(file.getParent()+ "/agetwo.xls");//輸出格式為.xls
	out = new PrintWriter(fWriter);
	InputStream is = new FileInputStream(file.getAbsoluteFile());
	Workbook wb = null;
	wb = Workbook.getWorkbook(is);
	int sheet_size = wb.getNumberOfSheets();
	Sheet sheet = wb.getSheet(0);
	for (int j = 1; j < sheet.getRows(); j++) {
		String cellinfo = sheet.getCell(1, j).getContents();//讀取的是第二列資料,沒有標題,標題起始位置在for迴圈中定義
		out.println(cellinfo);
	}
	out.close();//關閉流
	fWriter.close();
	out.flush();//重新整理快取
	System.out.println("輸出完成!");
}
這段程式碼同樣需要注意具體到行列,輸出的文字名稱可以自定義設定,這裡取和原檔案相同名字。但是要注意,out.println()一次只能寫入一個文字,所以要確定寫入的是txt還是excel,否則會出現文字生成了,但是卻是空文字的情況。

效果如下: