Java POI - 读取列中的所有数值

时间:2016-11-16 17:25:08

标签: java excel file arraylist apache-poi

我试图在xlsx文件工作表的列中获取所有数值(整数)。所有数值都在文本单元格中可用,并且没有列名称。

我尝试使用下面的代码但是我无法获得预期的结果,因为它显示了一些工作表本身不可用的数值。

B栏中的数据

qeweqwqe
Acc#
1212121
aaffssd
ACC#
20930293
9000sds
67623283309089789
Acc#
90909093

Java代码:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Iterator;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ReadWriteExcel {

    public static void main(String[] args) {
        extractExcelContentByColumnIndex(1);
    }

    public static ArrayList<String> extractExcelContentByColumnIndex(
            int columnIndex) {
        ArrayList<String> columndata = null;
        try {
            File f = new File("path/Sample.xlsx");
            FileInputStream ios = new FileInputStream(f);
            XSSFWorkbook workbook = new XSSFWorkbook(ios);
            XSSFSheet sheet = workbook.getSheetAt(0);
            Iterator<Row> rowIterator = sheet.iterator();
            columndata = new ArrayList<>();

            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                Iterator<Cell> cellIterator = row.cellIterator();
                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();

                    if (row.getRowNum() > 0) { // To filter column headings
                        if (cell.getColumnIndex() == columnIndex) {// To match
                                                                    // column
                                                                    // index
                            switch (cell.getCellType()) {
                            case Cell.CELL_TYPE_NUMERIC:
                                columndata.add(cell.getNumericCellValue() + "");
                                break;
                            case Cell.CELL_TYPE_STRING:
                                cell.setCellType(cell.CELL_TYPE_NUMERIC);
                                columndata.add(cell.getNumericCellValue() + "");
                                break;
                            }
                        }
                    }
                }
            }
            ios.close();
            System.out.println(columndata);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return columndata;
    }
}

0 个答案:

没有答案