Java 讀取excl

>表格

>處理代碼:

package com.jeefw.processutil;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;

public class excelpro {

	public static void read(String fileName) {
		String[][] t1Array = new String[20][10];
		SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
		try {
			InputStream input = new FileInputStream(fileName); // 建立輸入流
			HSSFWorkbook wb = new HSSFWorkbook(input);// 初始化
			HSSFSheet sheet = wb.getSheetAt(0);// 獲得第一個表單
			// 總行數
			int rowLength = sheet.getLastRowNum() + 1;
			HSSFRow hssfRow = sheet.getRow(0);// 得到Excel工作表的行
			int colLength = hssfRow.getLastCellNum();// 總列數  
			System.out.println("讀取excl的總行數爲:" + rowLength);
			System.out.println("讀取excl的總列數爲:" + colLength);

			int t1RowNum = 0;
			// 當兩個數組進行賦值轉換的時候(表格也可以看作一個二維數組,就要考慮其各自的行和列是怎麼對應的,不要混攪在一起)
			for (int i = 1; i < rowLength; i++) {
				HSSFRow row = sheet.getRow(i);
				// 根據每行數據組裝班期 用戶 和 各個課程成績
				for (int j = 3; j < colLength; j++) {
					HSSFCell scheduleCell = row.getCell(1);
					t1Array[t1RowNum][0] = fmt.format(scheduleCell.getDateCellValue());
					HSSFCell userNameCell = row.getCell(2);
					t1Array[t1RowNum][1] = userNameCell.getStringCellValue();
					// System.out.println(userNameCell.getStringCellValue());

					HSSFCell classCell = hssfRow.getCell(j);
					HSSFCell cell = row.getCell(j);
					if (cell != null) {
						// 將所有的需要讀的Cell表格設置爲String格式
						cell.setCellType(Cell.CELL_TYPE_STRING);
					}
					t1Array[t1RowNum][2] = classCell.getStringCellValue();
					t1Array[t1RowNum][3] = cell.getStringCellValue();
					t1RowNum++;
				}
			}

			for (int i = 0; i < t1RowNum; i++) {
				for (int j = 0; j < 4; j++) {
					System.out.print(t1Array[i][j] + "  ");
				}
				System.out.println();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws IOException {
		read("C:\\Users\\root\\Desktop\\培訓\\用戶課程成績.xls");
	}
}

>輸出結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章