簡體   English   中英

如何將Excel文件中的單元格(字符串)值附加到JTextArea?

[英]How to append cell (String) value from Excel file to JTextArea?

這是我的問題:

我嘗試從Excel文件的單元格循環中附加值。 我使用這部分代碼:

Workbook workbook = new HSSFWorkbook(new FileInputStream(fileChooser.getSelectedFile()));
            Sheet sheet = workbook.getSheetAt(0);

            for(Iterator<Row> rit = sheet.rowIterator(); rit.hasNext();)
            {
                Row row = rit.next();

                for(Iterator<Cell> cit = row.cellIterator(); cit.hasNext();)
                {
                    Cell cell = cit.next();


                    cell.setCellType(Cell.CELL_TYPE_STRING);

                    while(cit.hasNext())
                    {
                        notatnik.append(String.valueOf(cell.getSheet().toString()) + "\n");
                    }

                System.out.print(cell.getStringCellValue() + "\t");         
                }
                System.out.println();
            }

但是只返回了值“ 1”或“ org.apache.poi.hssf.usermodel.HSSFSheet@6325a3ee”。 在Excel中,我有例如值:1 SP25 kp 5 6.5等。

我應該怎么做才能將此值從Excel取回JTextArea?

PS。 我使用POI 3.10庫。

您正在使迭代器有點混亂...

迭代器應按以下方式使用:

Iterator<Cell> cit = row.cellIterator(); // you get the iterator ...

while (cit.hasNext()) {
  // let't go cell by cell
  Cell cell = cit.next();
  System.out.println(cell.getStringCellValue());
}

不知道為什么要打印出cell.getSheet()因為這個值總是相同的(您在同一張紙上)……可能您正在尋找cell.getValue() ……或類似的東西

如果有人在尋找答案(並且會和我有同樣的問題),這是我程序中代碼的一部分:

JFileChooser fileChooser = new JFileChooser();

        if(fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
        {
            try
            {
                Workbook workbook = new HSSFWorkbook(new FileInputStream(fileChooser.getSelectedFile()));
                Sheet sheet = workbook.getSheetAt(0);

                for(Iterator<Row> rit = sheet.rowIterator(); rit.hasNext();)
                {
                    Row row = rit.next();

                    for(Iterator<Cell> cit = row.cellIterator(); cit.hasNext();)
                    {
                        Cell cell = cit.next();

                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        notatnik.append(cell.getStringCellValue() + "\t");
                    }
                    notatnik.append("\n");
                }
            } 
            catch (FileNotFoundException e1)
            {
                e1.printStackTrace();
            } 
            catch (IOException e2)
            {
                e2.printStackTrace();
            }
        }

這部分代碼從excel文件中獲取所有值,並將它們粘貼到JTextArea中,稱為``notatnik''。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM