<code id="ymukc"><xmp id="ymukc">

java 讀取excel內容轉為JSONArray

ScaNIV的頭像 ScaNIV 0 2016-03-04 15:02 2

 基本信息

× 1   

瀏覽數: 24043

分享時間: 2 年 前

6

需要引入的JAR

        <!--*.xls-->
        <dependency>
            <groupId>net.sourceforge.jexcelapi</groupId>
            <artifactId>jxl</artifactId>
            <version>2.6.8</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.7</version>
        </dependency>

測試類

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

import java.io.File;

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://b.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();
        }
    }
}

讀取的文件格式

輸出:

還沒有人評論,趕快來搶沙發吧!

  
六合特码资料
<code id="ymukc"><xmp id="ymukc">
<code id="ymukc"><xmp id="ymukc">