通过转换为XLS电子表格Java从CSV获取特定单元格的值

时间:2018-04-02 00:17:08

标签: java csv

所以我尝试构建一个带有CSV文件并返回某些特定单元格值的程序。我希望这个程序能够处理类似但不同的CSV电子表格,这意味着需要抓取的数据将始终存在,但列/行坐标可能不同。这就是我所拥有的,尽管我有一种感觉,我应该重新开始:

import java.io.*;
import java.awt.Point;
import java.util.HashMap;
import java.util.Scanner;

public class CSV {

private static HashMap<Point, String> _map = new HashMap<Point, String>();
private int _cols;
private int _rows;

public void open(File file) throws FileNotFoundException, IOException {
    open(file, ',');
}

public void open(File file, char delimiter)
        throws FileNotFoundException, IOException {
    Scanner scanner = new Scanner(file);
    scanner.useDelimiter(Character.toString(delimiter));

    clear();

    while(scanner.hasNextLine()) {
        String[] values = scanner.nextLine().split(Character.toString(delimiter));

        int col = 0;
        for ( String value: values ) {
            _map.put(new Point(col, _rows), value);
            _cols = Math.max(_cols, ++col);
        }
        _rows++;
    }
    scanner.close();
}

public void save(File file) throws IOException {
    save(file, ',');
}

public void save(File file, char delimiter) throws IOException {
    FileWriter fw = new FileWriter(file);
    BufferedWriter bw = new BufferedWriter(fw);

    for (int row = 0; row < _rows; row++) {
        for (int col = 0; col < _cols; col++) {
            Point key = new Point(col, row);
            if (_map.containsKey(key)) {
                bw.write(_map.get(key));
            }

            if ((col + 1) < _cols) {
                bw.write(delimiter);
            }
        }
        bw.newLine();
    }
    bw.flush();
    bw.close();
}

public static String get(int col, int row) {
    String val = "";
    Point key = new Point(col, row);
    if (_map.containsKey(key)) {
        val = _map.get(key);
    }
    return val;
}


public void put(int col, int row, String value) {
    _map.put(new Point(col, row), value);
    _cols = Math.max(_cols, col+1);
    _rows = Math.max(_rows, row+1);
}

public void clear() {
    _map.clear();
    _cols = 0;
    _rows = 0;
}

public int rows() {
    return _rows;
}

public int cols() {
    return _cols;
}

public static void main(String[] args) {
    try {
        CSV csv = new CSV();

        csv.open(new File("mycsv.csv"));
        System.out.println(get(1,1));

    } catch (Exception e) {
    }
}
}

我最初的想法是使用&#34; for&#34;循环只是通过get()函数,直到我找到数据应该在的右行(电子表格的最左边标有单词)。

public static String getStreamTW(){
    for (int i = 0; i < 300; i++){
        if(CSV.get(0,i)=="Audio"){
            return(CSV.get(1,i));
        }
    }
    return "N/A";
}

是的,只是没有工作,有时数据全部被削减,所以我不认为这有什么好处。你们都觉得怎么样?有没有什么可以通过单元格获取数据?认为格式化已经搞砸了所以我想通过单元格处理这个问题。我正在考虑将CSV转换为excel电子表格,然后从那里开始工作。这是一个好主意/你们都有一些资源吗?

0 个答案:

没有答案