title: Java操做Excel文件
date: 2017-05-01 11:36:20java
今天,我來教你們怎麼實現Java操做Excel文件。json
import java.io.File;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
/** * @author HuangQinJian 上午11:04:58 2017年5月1日 */
public class ExcelOperate {
public static void main(String[] args) {
Sheet sheet;
Workbook book;
Cell cell1, cell2, cell3, cell4, cell5;
JSONArray array = new JSONArray();
try {
// 爲要讀取的excel文件名
book = Workbook.getWorkbook(new File("D://test.xls"));
// 得到第一個工做表對象(ecxel中sheet的編號從0開始,0,1,2,3,....)
sheet = book.getSheet(0);
for (int i = 1; i < sheet.getRows(); i++) {
// 獲取每一行的單元格
cell1 = sheet.getCell(0, i);// (列,行)
cell2 = sheet.getCell(1, i);
cell3 = sheet.getCell(2, i);
cell4 = sheet.getCell(3, i);
cell5 = sheet.getCell(4, i);
if ("".equals(cell1.getContents())) {// 若是讀取的數據爲空
break;
}
JSONObject object = new JSONObject();
object.put("ID", cell1.getContents());
object.put("編號", cell2.getContents());
object.put("姓名", cell3.getContents());
object.put("數量", cell4.getContents());
object.put("住址", cell5.getContents());
array.add(object);
}
System.out.println(array.toString());
book.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}複製代碼
在這個過程當中你可能會遇到一個錯誤,以下圖:spa
這是由於不支出讀取 excel 2007 文件(.xlsx)。只支持 excel 2003 (.xls)。3d
輸入的數據格式:excel
輸出結果:code
[{"編號":"11","姓名":"黃","住址":"遼寧","ID":"1","數量":"3"},{"編號":"22","姓名":"欽","住址":"大連","ID":"2","數量":"32"},{"編號":"33","姓名":"建","住址":"開發區","ID":"3","數量":"32"},{"編號":"44","姓名":"黃","住址":"軟件學院","ID":"4","數量":"32"},{"編號":"55","姓名":"欽建","住址":"大黑山","ID":"5","數量":"3232"}]cdn
更多內容歡迎訪問個人我的主頁對象