如何使用Java Apache POI库从XLSX文件中的特定单元格获取值 [英] How to get value from a specific cell from XLSX file using java Apache POI library

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

问题描述

我正在编写一个Java程序,以使用Apache POI库从excel工作表(具有XLSX扩展名)中读取数据.我能够遍历所有单元格并获得所有值.但是我无法获得特定的像元值,例如E10.有什么办法吗?

I am writing a Java program to read data from excel sheet (having XLSX extension) using Apache POI library. I am able to iterate through all the cells and get all the values. But I am unable to get a specific cell value, say E10. Is there any way to do this?

请参阅下面用于遍历单元格的代码.

Please see the code below that I used for iterating through the 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); 

注意:因为索引是基于空值的,所以减去1.

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天全站免登陆