good way to represent a excel sheet value in Java

被刻印的时光 ゝ 提交于 2019-12-11 06:05:22

问题


Consider that I've a excel sheet in below format:

person age
Foo 29
Bar 27

Now I want to read these values (using POI HSSF) and have to process them. What's the best way to do that?

Note that I do not have a Object Person in my application, becasue the values that may come in excel sheet is arbitrary (i.e. it may not be the person name and age). So, I need to use some kinda HashMap to store these values. In case multiple rows, is it good to have a List !?


回答1:


public class Grid {
    private Row headerColumns;
    private List<Row> dataRows;

    public Grid() {
        dataRows = new LinkedList<Row>();
    }

    public Grid(int rowCount) {
        dataRows = new ArrayList<Row>(rowCount);
    }

    public void addHeaderRow(List<String> headers) {
        this.headerColumns = new Row(headers);
    }

    public void addDataRow(List<String> data) {
        this.dataRows.add( new Row(data) );
    }

    public List<Row> getAllData() {
        List<Row> data = new ArrayList<Row>(1+dataRows.size());
        data.add(this.headerColumns);
        data.addAll(dataRows);
        return data;
    }

    public Row getHeaderColumns() {
        return headerColumns;
    }

    public List<Row> getDataRows() {
        return dataRows;
    }
}

class Row {
    private List<String> data;

    public Row(List<String> data) {
        this.data = data;
    }

    public void addColumn(String columnData) {
        data.add(columnData);
    }

    public List<String> getData() {
        return data;
    }
}



回答2:


If the format is defined, make a class that accomodates all those fields.

If the format isn't defined, pass Row-s around, or Lists, or even DOM from excel-to-dom transformation. You have no choice. I'd recommend just stick to POI's native Row and Cell objects.




回答3:


Yes, you cannot use map if you have multiple key values. And i didn't find some build-in class for this issue. You can try write some kind of wrapper. If you don't care of speed use simple 2D array like this:

String[][] filter = new String[initial width][initial height];

it can be Object instead of String;



来源:https://stackoverflow.com/questions/857380/good-way-to-represent-a-excel-sheet-value-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!