重点是获取日期格式。日期那列的单元格格式必须设置成日期才有效,如果是以文本的形式为日期的话,那么要在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中数据:
运行结果: