You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Apache POI生成Excel后日期格式仅双击生效问题求助

问题原因

你当前的代码是把CSV中的日期字符串直接写入Excel单元格,Excel会将其识别为文本类型存储。即便你给单元格设置了日期格式,文本内容不会自动应用格式规则——只有双击单元格时,Excel触发了文本到日期的自动转换,才会显示你设置的d/MMM/yyyy格式。

解决方法

核心是先把CSV里的mm-dd-yyyy格式字符串解析为Java日期对象,再以日期类型写入Excel单元格,同时绑定日期格式样式。

步骤1:添加日期解析逻辑

根据Java版本选择合适的工具:

  • Java 8及以上推荐用DateTimeFormatter(线程安全)
  • 兼容旧版本可使用SimpleDateFormat

步骤2:修改代码,区分日期列与普通列

假设CSV中第3列(索引为2)是日期列,以下是修改后的完整代码示例:

Java 8+ 版本(推荐)

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import java.io.*;

public class CsvToExcelConverter {
    public static void main(String[] args) throws Exception {
        XSSFWorkbook workBook = new XSSFWorkbook();
        Sheet sheet = workBook.createSheet("Data");
        
        // 定义日期解析和格式化规则
        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("MM-dd-yyyy");

        // 创建日期单元格样式
        CellStyle dateStyle = workBook.createCellStyle();
        CreationHelper createHelper = workBook.getCreationHelper();
        dateStyle.setDataFormat(createHelper.createDataFormat().getFormat("d/MMM/yyyy"));

        BufferedReader br = new BufferedReader(new FileReader("input.csv"));
        String currentLine;
        int rowNum = 0;

        while ((currentLine = br.readLine()) != null) {
            String[] str = currentLine.split(",");
            Row currentRow = sheet.createRow(rowNum);
            rowNum++;

            for (int i = 0; i < str.length; i++) {
                String value = str[i];
                Cell cell = currentRow.createCell(i);
                
                // 仅对日期列进行解析转换,按需修改索引值
                if (i == 2) {
                    try {
                        LocalDate date = LocalDate.parse(value, inputFormatter);
                        cell.setCellValue(date);
                        cell.setCellStyle(dateStyle);
                    } catch (Exception e) {
                        // 解析失败时按文本写入
                        cell.setCellValue(value);
                    }
                } else {
                    // 普通列直接写文本
                    cell.setCellValue(value);
                }
            }
        }

        // 写入输出文件并关闭资源
        try (FileOutputStream fileOutStream = new FileOutputStream("output.xlsx")) {
            workBook.write(fileOutStream);
        }
        workBook.close();
        br.close();
    }
}

旧版本Java(使用SimpleDateFormat)

import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import java.io.*;

public class CsvToExcelConverter {
    public static void main(String[] args) throws Exception {
        XSSFWorkbook workBook = new XSSFWorkbook();
        Sheet sheet = workBook.createSheet("Data");
        
        SimpleDateFormat inputSdf = new SimpleDateFormat("MM-dd-yyyy");

        CellStyle dateStyle = workBook.createCellStyle();
        CreationHelper createHelper = workBook.getCreationHelper();
        dateStyle.setDataFormat(createHelper.createDataFormat().getFormat("d/MMM/yyyy"));

        BufferedReader br = new BufferedReader(new FileReader("input.csv"));
        String currentLine;
        int rowNum = 0;

        while ((currentLine = br.readLine()) != null) {
            String[] str = currentLine.split(",");
            Row currentRow = sheet.createRow(rowNum);
            rowNum++;

            for (int i = 0; i < str.length; i++) {
                String value = str[i];
                Cell cell = currentRow.createCell(i);
                
                if (i == 2) { // 日期列索引,按需修改
                    try {
                        Date date = inputSdf.parse(value);
                        cell.setCellValue(date);
                        cell.setCellStyle(dateStyle);
                    } catch (Exception e) {
                        cell.setCellValue(value);
                    }
                } else {
                    cell.setCellValue(value);
                }
            }
        }

        try (FileOutputStream fileOutStream = new FileOutputStream("output.xlsx")) {
            workBook.write(fileOutStream);
        }
        workBook.close();
        br.close();
    }
}

关键注意事项

  • 务必根据你的CSV结构修改日期列的索引值(示例中i == 2)
  • 添加异常处理,避免因日期格式不规范导致程序崩溃
  • 使用try-with-resources语法自动关闭流资源,避免内存泄漏

内容的提问来源于stack exchange,提问作者Prashant Naik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 00:30:57