java 读取 xlsx

package test;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class T {
    public static void main(String[] args) throws IOException {
        new T().readXlsx("D:\\data\\parse_result.xlsx", 1);
        
    }
    
    /**
     * 
     * @param path  xlsx文件路径
     * @param numSheet  读取第几张表(从 0 开始)
     * @return
     * @throws IOException
     */
    public List<DeviceInfo> readXlsx(String path, int numSheet) throws IOException {
        InputStream is = new FileInputStream(path);
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);
        DeviceInfo deviceInfo = null;
        List<DeviceInfo> list = new ArrayList<DeviceInfo>();
            //读取第几张表
            XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(numSheet);
            //读取行
            for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
                XSSFRow xssfRow = xssfSheet.getRow(rowNum);
                if (xssfRow != null) {
                    deviceInfo = new DeviceInfo();
                    XSSFCell SN = xssfRow.getCell(0);
                    XSSFCell cpu = xssfRow.getCell(1);
                    XSSFCell ram = xssfRow.getCell(2);
                    XSSFCell times = xssfRow.getCell(3);
                    XSSFCell WAN = xssfRow.getCell(4);
                    XSSFCell value = xssfRow.getCell(5);
                    XSSFCell PPPOEStatus = xssfRow.getCell(3);
                    
                    try {
                        deviceInfo.setSN(SN.toString());
                        deviceInfo.setCpu(cpu.toString());
                        deviceInfo.setRam(ram.toString());
                        deviceInfo.setTimes(times.toString());
                        deviceInfo.setWAN(WAN.toString());
                        deviceInfo.setValue(value.toString());
                        deviceInfo.setPPPOEStatus(PPPOEStatus.toString());
                    } catch (NullPointerException e) {
                    }
                    list.add(deviceInfo);
                }
            }
        for(DeviceInfo d: list) {
            System.out.println(d.getSN());
        }
        return list;
    }

    private String getValue(XSSFCell sN) {
        return null;
    }
}

猜你喜欢

转载自www.cnblogs.com/redhat0019/p/8945949.html