在網上找到的一些資料與自己例子的結合,記下來供自己參考。
首先是要有個jxl.jar包。在http://www.andykhan.com/jexcelapi/download.html裡去下了最新版本,發現運行起來有問題,錯誤提示版本不符什麼的。然後搜到說JDK1.6該用JExcelApi v2.6.9這個版本,確實如此。
還有一個問題就是貌似.xlsx檔案沒辦法解析,只能是.xls的。
然後就是以下對excel檔案匯入的demo。要實現的是把使用者資訊從userInfo.xls裡匯入到一個UserInfo的List裡,並在控制台輸出。
UserInfo的類此處不給出了。
package test;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.util.List;import java.util.ArrayList;import jxl.Cell;import jxl.Sheet;import jxl.Workbook;import jxl.read.biff.BiffException;public class ReadFile {public List<UserInfo> ReadInfo() throws BiffException, IOException {List<UserInfo> userInfoList = new ArrayList<UserInfo>();UserInfo userInfo;String filePath = "F:\\userInfo.xls";InputStream inputStream = new FileInputStream(filePath);try {Workbook workbook = Workbook.getWorkbook(inputStream);Sheet sheet = workbook.getSheet(0);String sheetName = sheet.getName();//System.out.println("sheet name :" + sheetName);if (sheetName != null) {// 擷取表格總列數int columns = sheet.getColumns();//System.out.println("sheet columns: " + columns);// 擷取表格總行數int rows = sheet.getRows();//System.out.println("sheet rows: " + rows);// 訪問每個單元for (int i = 1; i < rows; ++i) {Cell[] cells = sheet.getRow(i);userInfo = new UserInfo();userInfo.setUserId(cells[0].getContents());userInfo.setUserName(cells[1].getContents());userInfo.setEmail(cells[2].getContents());userInfoList.add(userInfo);}}workbook.close();return userInfoList;} catch (Exception e) {e.printStackTrace();return userInfoList;}}public static void main(String[] args) {List<UserInfo> userInfoList = new ArrayList<UserInfo>();ReadFile readFile = new ReadFile();try {userInfoList = readFile.ReadInfo();System.out.println("使用者ID使用者名稱Email");for(int i=0; i<userInfoList.size(); ++i){System.out.println(userInfoList.get(i).getUserId()+""+userInfoList.get(i).getUserName()+""+userInfoList.get(i).getEmail());}} catch (Exception e) {e.printStackTrace();}}}