使用java读取excel表时,列不按顺序读取

时间:2016-08-11 13:39:33

标签: java excel apache-poi

我有一个包含200列数据的Excel工作表,可以导入到DB i&m 下面的代码

private File upp;
InputStream input =  new FileInputStream(upp);
POIFSFileSystem fs = new POIFSFileSystem(input);
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);

Iterator rows = sheet.rowIterator();

while(rows.hasNext()) { 
    String data="";
    HSSFRow row = (HSSFRow) rows.next();
    if(row.getRowNum() == 0 || row.getRowNum() == 1) {
        Iterator rowCells = row.cellIterator();
        while(rowCells.hasNext()) {
            HSSFCell cell = (HSSFCell) rowCells.next();
            for(int i=0; i <= cell.getCellNum(); i++) {

            }             
            data = data + cell.getCellNum() + " ,";
        }
        System.out.println(data);
    }
    slrow++;
}

除了输出

之外我不知道
0 ,1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10 ,11 ,12 ,13 ,14 ,15 ,16 ,17 ,18 ,

但输出是

0 ,1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10 ,11 ,12 ,13 ,14 ,15 ,17 ,16 ,18 ,

它没有按预期顺序读取我无法找出此代码中的错误位置

1 个答案:

答案 0 :(得分:-1)

使用JXL库

<dependency>
    <groupId>net.sourceforge.jexcelapi</groupId>
    <artifactId>jxl</artifactId>
    <version>2.6</version>
</dependency

代码示例

FileInputStream inputStream = new FileInputStream(file);
            Workbook wb = Workbook.getWorkbook(inputStream);

            // TO get the access to the sheet. 
//For single sheet
            Sheet sheet = wb.getSheet(0);

            // To get the number of rows present in sheet
            int totalNoOfRows = sheet.getRows();

            // To get the number of columns present in sheet
            int totalNoOfCols = sheet.getColumns();

            Map<String, String> map = new HashMap<>();
            for (int row = 1; row < totalNoOfRows; row++) {

                for (int col = 0; col < totalNoOfCols; col++) {
                    map.put(sheet.getCell(col, 0).getContents(),
                            sheet.getCell(col, row).getContents());

                }
            }

我希望这会有所帮助。