如何使用apache poi从excel获取价值

时间:2014-07-22 14:44:52

标签: java excel apache-poi

我只是试图从excel文件中获取每个单元格值但是我已经将每个单元格合并但我希望每个单元格不同

import java.io.File;import java.io.FileInputStream;import java.util.Iterator;import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.ss.usermodel.Row;import org.apache.poi.xssf.usermodel.XSSFSheet;import org.apache.poi.xssf.usermodel.XSSFWorkbook;public class Read {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub

            try
            {
                FileInputStream file = new FileInputStream(new File("D://new/excelnew/student_usr_mst_dtls.xlsx"));

                //Create Workbook instance holding reference to .xlsx file
                XSSFWorkbook workbook = new XSSFWorkbook(file);

                //Get first/desired sheet from the workbook
                XSSFSheet sheet = workbook.getSheetAt(0);

                //Iterate through each rows one by one
                Iterator<Row> rowIterator = sheet.iterator();
                while (rowIterator.hasNext())
                {
                    Row row = rowIterator.next();
                    //For each row, iterate through all the columns

                    Iterator<Cell> cellIterator = row.cellIterator();

                    while (cellIterator.hasNext())
                    {
                        Cell cell = cellIterator.next();
                        //Check the cell type and format accordingly
                        switch (cell.getCellType())
                        {
                            case Cell.CELL_TYPE_NUMERIC:
                                System.out.print(cell.getNumericCellValue() + "t");
                                break;
                            case Cell.CELL_TYPE_STRING:
                                System.out.print(cell.getStringCellValue());
                                break;
                        }
                    }
                    System.out.println("");
                }
                file.close();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }

}

和OutPut就像字符串

IDNAMELASTNAME 1.0tAmitShukla 2.0tLokeshGupta

我希望每个单元格都是唯一的,以便如何做到这一点。如果可能请举个例子。

1 个答案:

答案 0 :(得分:2)

在您打印的每个单元格值后面加一个逗号。

System.out.print(cell.getNumericCellValue() + "t,");

System.out.print(cell.getStringCellValue() + ",");