Merge pull request #1977 from sppan24/v5-dev

V5 dev
This commit is contained in:
Golden Looly 2021-11-28 19:57:59 +08:00 committed by GitHub
commit 22667cb4c1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 34 additions and 2 deletions

View File

@ -4,6 +4,7 @@ import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelDateUtil;
import cn.hutool.poi.excel.cell.CellValue;
import java.util.Date;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.util.NumberToTextConverter;
@ -24,7 +25,7 @@ public class NumericCellValue implements CellValue<Object> {
*
* @param cell {@link Cell}
*/
public NumericCellValue(Cell cell){
public NumericCellValue(Cell cell) {
this.cell = cell;
}
@ -36,8 +37,13 @@ public class NumericCellValue implements CellValue<Object> {
if (null != style) {
// 判断是否为日期
if (ExcelDateUtil.isDateFormat(cell)) {
// 1899年写入会导致数据错乱读取到1899年证明这个单元格的信息不关注年月日
Date dateCellValue = cell.getDateCellValue();
if ("1899".equals(DateUtil.format(dateCellValue, "yyyy"))) {
return DateUtil.format(dateCellValue, style.getDataFormatString());
}
// 使用Hutool的DateTime包装
return DateUtil.date(cell.getDateCellValue());
return DateUtil.date(dateCellValue);
}
final String format = style.getDataFormatString();

View File

@ -0,0 +1,26 @@
package cn.hutool.poi.excel;
import cn.hutool.poi.excel.cell.values.NumericCellValue;
import java.util.Date;
import org.apache.poi.ss.usermodel.Cell;
import org.junit.Test;
public class NumericCellValueTest {
@Test
public void writeTest() {
final ExcelReader reader = ExcelUtil.getReader("1899bug_demo.xlsx");
ExcelWriter writer = ExcelUtil.getWriter("1899bug_write.xlsx");
Cell cell = reader.getCell(0, 0);
// 直接取值
// 和CellUtil.getCellValue(org.apache.poi.ss.usermodel.Cell)方法的结果一样
// 1899-12-31 04:39:00
Date cellValue = cell.getDateCellValue();
// 将这个值写入EXCEL中自定义样式的单元格结果会是-1
writer.writeCellValue(0, 0, cellValue);
// 修改后的写入单元格内容正常
writer.writeCellValue(1, 0, new NumericCellValue(cell).getValue());
writer.close();
reader.close();
}
}

Binary file not shown.