使用Apache POI将XLS文件读入Java中的2D数组

时间:2015-09-01 09:41:18

标签: java arrays apache-poi xls

我的任务是阅读一个看起来像这样的Excel文件 http://postimg.org/image/jxgc6ng51/ 然后将匹配产品ID的单位相加,并以类似的列/行格式打印出来。对不起,如果这是一个草率的方式,我是java的新手,我对java API的了解目前非常有限......这是我的代码:

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class Read {

            public static void readXLSFile() throws IOException{
        InputStream ExcelFile = new FileInputStream("C:/Sales Data.xls");
        HSSFWorkbook wb = new HSSFWorkbook(ExcelFile);
                HSSFSheet sheet=wb.getSheetAt(0);
                int numRows=sheet.getPhysicalNumberOfRows();
                int[][]idSale=new int[numRows][2];

                for(int i=1;i<numRows;i++){
                    HSSFCell proId = sheet.getRow(i).getCell(1);
                    HSSFCell sales = sheet.getRow(i).getCell(2);
                    idSale[i][0]=(int)proId.getNumericCellValue();
                    idSale[i][1]=(int)sales.getNumericCellValue();
                    //the data from the excel sheet is copied into the 2D array at this point
                }

                /*for loop to attempt to compare id number of array to the rest of the array
                problem is there are duplicate ID's and it is re-comparing and adding
                the sales total into the duplicate as well. 
                How to make it so it ignores all duplicate ID's or make it so it 
                only prints out the element the first time the ID pops up and doesn't print the other elements with the same ID?*/
                for(int j=1;j<numRows;j++){
                    for(int jj=j+1;jj<numRows;jj++)
                    if(idSale[j][0]==idSale[jj][0]){
                        idSale[j][1]+=idSale[jj][1];
                    }
                }
            }



            public static void main(String[] args) throws IOException {
        readXLSFile();
            }
}

1 个答案:

答案 0 :(得分:1)

你可以尝试使用Map,你只需要一个for循环,如下所示: -

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *proc(const char *cmd, const char *id){//id : start with id
    char *str = strdup(cmd);//make copy
    char *to, *from;
    size_t id_len = strlen(id);

    to = from = str;
    while(*from){
        if(strncmp(from, id, id_len)==0){
            while(*from && *from++ != ';'); //skip upto ;
        } else {
            while((*to = *from) && (++to, *from++ != ';'));//copy upto ;
        }
    }
    *to = '\0';

    return str;
}

int main(void){
    const char *Cmd = "start;more;muchmore;123 45;rest";

    Cmd = proc(Cmd, "123");
    puts(Cmd);
    free((void*)Cmd);

    return 0;
}