java excel 单元格类型_Java如何获取Excel的单元格数据类型?

在此示例中,我们尝试获取Excel的单元格数据类型,以便我们可以使用正确的方法读取该值。要读取的数据在名为的文件中celltype.xls。下面的矩阵描述了文件的状态。|   COL

ROW |   0       1   2   3   4

----|-------------------------

0   |   1       2   A   B   TRUE

1   |   FALSE   X   Y   Z   10package org.nhooo.example.poi;

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.ss.usermodel.CellType;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.util.Iterator;

public class ObtainingCellType {

public static void main(String[] args) throws Exception {

String filename = "celltype.xls";

try (FileInputStream fis = new FileInputStream(filename)) {

HSSFWorkbook workbook = new HSSFWorkbook(fis);

HSSFSheet sheet = workbook.getSheetAt(0);

Iterator rows = sheet.rowIterator();

while (rows.hasNext()) {

HSSFRow row = (HSSFRow) rows.next();

Iterator cells = row.cellIterator();

while (cells.hasNext()) {

HSSFCell cell = (HSSFCell) cells.next();

CellType type = cell.getCellType();

if (type == CellType.STRING) {

System.out.println("[" + cell.getRowIndex() + ", "

+ cell.getColumnIndex() + "] = STRING; Value = "

+ cell.getRichStringCellValue().toString());

} else if (type == CellType.NUMERIC) {

System.out.println("[" + cell.getRowIndex() + ", "

+ cell.getColumnIndex() + "] = NUMERIC; Value = "

+ cell.getNumericCellValue());

} else if (type == CellType.BOOLEAN) {

System.out.println("[" + cell.getRowIndex() + ", "

+ cell.getColumnIndex() + "] = BOOLEAN; Value = "

+ cell.getBooleanCellValue());

} else if (type == CellType.BLANK) {

System.out.println("[" + cell.getRowIndex() + ", "

+ cell.getColumnIndex() + "] = BLANK CELL");

}

}

}

} catch (FileNotFoundException e) {

e.printStackTrace();

}

}

}

我们的程序迭代Excel文件的行和单元格,并产生以下

输出:[0, 0] = NUMERIC; Value = 1.0

[0, 1] = NUMERIC; Value = 2.0

[0, 2] = STRING; Value = A

[0, 3] = STRING; Value = B

[0, 4] = BOOLEAN; Value = true

[1, 0] = BOOLEAN; Value = false

[1, 1] = STRING; Value = X

[1, 2] = STRING; Value = Y

[1, 3] = STRING; Value = Z

[1, 4] = NUMERIC; Value = 10.0

Maven依赖

org.apache.poi

poi

4.1.0

poi.svg?label=Maven%20Central

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值