POI获取excel单元格的内容

重点是获取日期格式。日期那列的单元格格式必须设置成日期才有效,如果是以文本的形式为日期的话,那么要在getCellValue方法中的Cell.CELL_TYPE_STRING分支中做同样的处理。



import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class TestValue {
	public static void main(String[] args) {
		File file = new File("D:/test.xlsx");
		InputStream is = null;
		XSSFWorkbook wb = null;
		try {
			is = new FileInputStream(file);
			wb = new XSSFWorkbook(is);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Sheet sheet = wb.getSheetAt(0);
		int num = sheet.getLastRowNum();
		for (int i = 0; i < num; i++) {
			Row row = sheet.getRow(i);
			int c = row.getLastCellNum();
			for (int j = 0; j < c; j++) {
				System.out.println(getCellValue(row.getCell(j)));				
			}
		}
		try {
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	private static String getCellValue(Cell cell) {
		String value = "";
		int type = cell.getCellType();
		switch (type) {
		case Cell.CELL_TYPE_BOOLEAN:
			value = cell.getBooleanCellValue() + "";
			break;
		case Cell.CELL_TYPE_ERROR:
			value = "ERROR VALUE!";
			break;
		case Cell.CELL_TYPE_FORMULA:
			value = cell.getCellFormula() + "";
			break;
		case Cell.CELL_TYPE_NUMERIC:
			int SECONDS_PER_DAY = 86400;
			long DAY_MILLISECONDS = SECONDS_PER_DAY * 1000L;
			Double d = cell.getNumericCellValue();
			int wholeDays = (int)Math.floor(d);
	        int millisecondsInDay = (int)((d - wholeDays) * DAY_MILLISECONDS + 0.5);
	        Calendar calendar = new GregorianCalendar(); // 使用默认时区
	        setCalendar(calendar, wholeDays, millisecondsInDay, false);
	        SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy-MM-dd");
	        SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
	        Date date = calendar.getTime();
	        String year = yearFormat.format(date);
	        if (Integer.parseInt(year) > 1990) {
	        	value = sdFormat.format(date);				
			} else {
				value = d + "";
			}
			break;
		case Cell.CELL_TYPE_STRING:
			value = cell.getStringCellValue();
		}
		return value;
	}
	public static void setCalendar(Calendar calendar, int wholeDays,
            int millisecondsInDay, boolean use1904windowing) {
        int startYear = 1900;
        int dayAdjust = -1; // Excel 认为 2/29/1900 是有效时间, 其实不是。
        if (use1904windowing) {
            startYear = 1904;
            dayAdjust = 1; // 1904 date windowing uses 1/2/1904 as the first day
        }
        else if (wholeDays < 61) {
            // 因为excel中2/29/1900合法,所以优先使用3/1/1900
            // 如果 Excel 日期 == 2/29/1900, 在java中自动转换成 3/1/1900 
            dayAdjust = 0;
        }
        calendar.set(startYear,0, wholeDays + dayAdjust, 0, 0, 0);
        calendar.set(GregorianCalendar.MILLISECOND, millisecondsInDay);
    }
}

excel中数据:



运行结果:


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用POICellValueFormatter类来获取Excel单元格的数值格式。具体的操作如下: 1. 首先,使用POI读取Excel文件并获取一个单元格对象; 2. 然后,使用这个单元格对象的getCellType方法获取单元格的数据类型; 3. 倘若该单元格的数据类型为数值型的话,可以使用POI的DateUtil类来判断该单元格的数值格式,并进行相应的处理。 例如,以下是一个使用POI获取Excel单元格数值格式的示例代码: ```java // 导入POI相关的库 import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.poi.ss.usermodel.CellValue; import org.apache.poi.ss.usermodel.CellValue.CellTypeEnum; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.DataFormatter; public class Example { public static void main(String[] args) throws Exception { // 读取Excel文件 Workbook workbook = WorkbookFactory.create(new File("example.xlsx")); Sheet sheet = workbook.getSheetAt(0); // 获取某个单元格 Cell cell = sheet.getRow(0).getCell(0); // 判断单元格的数据类型 if (cell.getCellType() == CellType.NUMERIC) { // 判断单元格的数值格式 if (DateUtil.isCellDateFormatted(cell)) { // 处理日期型数据 Date date = cell.getDateCellValue(); String formattedDate = new SimpleDateFormat("yyyy/MM/dd").format(date); System.out.println(formattedDate); } else { // 处理普通数值型数据 Double value = cell.getNumericCellValue(); System.out.println(value); } } else { // 处理其他类型的数据 DataFormatter formatter = new DataFormatter(); String text = formatter.formatCellValue(cell); System.out.println(text); } } } ``` 以上代码使用POI读取了一个Excel文件中的单元格,并根据该单元格的数据类型和数值格式进行相应的处理。具体可以根据实际需要进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值