2015-09-01 123 views
0

我的任務是讀取一個如下所示的Excel文件 http://postimg.org/image/jxgc6ng51/ 然後求和匹配產品ID的單位並以相似的列/行格式打印出來。很抱歉,如果這是這樣做的一個草率的方式,我是新來的Java和我的Java API的知識很有限目前...這裏是我的代碼:將使用Apache POI的XLS文件讀取到Java中的2D數組中

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

您可以在此與地圖,你試試僅需要一個for循環,如下: -

Map<Integer, Integer> map = new HashMap<Integer, Integer>(); 
    for(int i=1;i<numRows;i++){ 
     HSSFCell proId = sheet.getRow(i).getCell(1); 
     HSSFCell sales = sheet.getRow(i).getCell(2); 
     int prodId =(int)proId.getNumericCellValue(); 
     int currentSales =(int)sales.getNumericCellValue(); 
     //the data from the excel sheet is copied into the 2D array at this point 
     if (map.containsKey(i)) { 
      int prevSales = map.get(i); 
      map.put(i, prevSales+currentSales); 
     } else { 
      map.put(i, currentSales); 
     } 
    } 
+0

優雅的解決方案 – MihaiC

+0

所以我調整了這個代碼一點,我認爲這是正確的?現在我不確定如何打印整個地圖。我將int proId更改爲int proId1,並將每個「i」從if(map.containsKey(i)up map.put(i,currentSales)和proId1開始。 – Jnewbie

+0

解決了它!謝謝! – Jnewbie

相關問題