java中excel檔案資料的匯入

來源:互聯網
上載者:User

在網上找到的一些資料與自己例子的結合,記下來供自己參考。

首先是要有個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();}}}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.