如何使用java apache poi从xlsx文件的特定单元格获取值 [英] How to get value from a specific cell of an xlsx file using java apache poi

查看:626
本文介绍了如何使用java apache poi从xlsx文件的特定单元格获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个java程序来使用apache poi读取excel表(xlsx)。我可以遍历所有单元格并获取所有值。但E10说,我无法获得特定的细胞价值。
有什么办法可以找到这个吗?

i am writing a java program to read an excel sheet (xlsx) using apache poi. I can be able to iterate over all the cells and get all the values. But i am not able to get a specific cell value, say E10. Is there any way to find this?

请参阅我用于迭代所有单元格的代码。

Please see the code that i used for iterating over all cells.

package application;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

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;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ReadFromXLSX {
    public static void readXLSXFile() throws IOException
    {
        InputStream ExcelFileToRead = new FileInputStream("C:\\Test.xlsx");
        XSSFWorkbook  wb = new XSSFWorkbook(ExcelFileToRead);
        XSSFWorkbook test = new XSSFWorkbook(); 
        XSSFSheet sheet = wb.getSheetAt(0);
        XSSFRow row; 
        XSSFCell cell;
        Iterator rows = sheet.rowIterator();
        while (rows.hasNext())
        {
            row=(XSSFRow) rows.next();
            Iterator cells = row.cellIterator();
            while (cells.hasNext())
            {
                cell=(XSSFCell) cells.next();   
                if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING)
                {
                    System.out.print(cell.getStringCellValue()+" ");
                }
                else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC)
                {
                    System.out.print(cell.getNumericCellValue()+" ");
                }
                else
                {
                }
            }
            System.out.println();
        }
    }   
}


推荐答案

例如,要获取第一个工作表的E10:

For example, to get E10 of the first worksheet:

wb.getSheetAt(0).getRow(9).getCell(4); 

注意:减去一,因为索引是基于空的。

Note: subtract one because the indices are null-based.

您也可以使用此便捷方法将E映射到4。

You can also use this convenience method to map E to 4.

wb.getSheetAt(0).getRow(9).getCell(CellReference.convertColStringToIndex("E"));

这篇关于如何使用java apache poi从xlsx文件的特定单元格获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆