【问题标题】:How to set the data format for the row in Excel?Excel中如何设置行的数据格式?
【发布时间】:2015-11-25 11:36:20
【问题描述】:

我正在尝试将 Excel 中行的数据类型设置为日期格式('yyyy-MM-dd'),为此我编写了以下代码:

....
Row r = null;
    CellStyle cellStyle = workbook.createCellStyle();
    //CreationHelper createHelper = workbook.getCreationHelper();
    cellStyle.setDataFormat(
            workbook.createDataFormat().getFormat("yyyy-MM-dd"));
    for(int i =0;i < 2;i++){
        switch(i){
            case 0:
                r = sheet.getRow(0);
                r.setRowStyle(cellStyle);
                break;
            case 1:
                r = sheet.getRow(1);
                r.setRowStyle(cellStyle);
                break;
            default:
                break;
        }
    }
....

我只发布了前两行的格式供参考。但是当我运行我的代码并打开 Excel 表并检查前两行中单元格的格式时,它只是一般的。更改未反映在 Excel 工作表中。我没有明白我在这里做错了什么。

【问题讨论】:

  • 这些行中有现有的单元格吗?如果是这样,当您也在这些单元格上设置新样式时会发生什么?
  • 我正在新建excel表格。所以一开始不会有任何数据。

标签: java excel apache-poi


【解决方案1】:

如果您是从头开始创建此 Excel 工作表,那么它还没有行。我在一张新表中得到了getRow(0) 上的NullPointerException。尝试改用createRow(0)

public static void main(String[] args) throws JDOMException, IOException {
        File excelFile = new File("C:/temp/test.xls");
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("sheetname");

        Row r = null;
        CellStyle cellStyle = workbook.createCellStyle();
        // CreationHelper createHelper = workbook.getCreationHelper();
        cellStyle.setDataFormat(workbook.createDataFormat().getFormat("yyyy-MM-dd"));
        for (int i = 0; i < 2; i++) {
            switch (i) {
            case 0:
                r = sheet.createRow(0);
                r.setRowStyle(cellStyle);
                break;
            case 1:
                r = sheet.createRow(1);
                r.setRowStyle(cellStyle);
                break;
            default:
                break;
            }
        }

        try (FileOutputStream out = new FileOutputStream(excelFile)) {
            workbook.write(out);
        }
        Desktop.getDesktop().open(excelFile);
    }

【讨论】:

  • 我建议不要使用开关盒。更好的解决方案是使用当前迭代索引来创建新行。
  • 我使用 switch 是因为对于不同的不同行组,我会有不同的样式。
  • @Moh-AW:当我运行您的代码时,它运行良好。但是当我在我的代码中使用它时,它没有提供所需的格式。我从正在创建 excel 文件的实用程序类中获取工作簿。不知道那里出了什么问题
  • @Madhusudan 您能否将工作簿创建代码添加到您的问题中?
  • 嘿...对不起。它现在正在工作。我犯了一个小错误。谢谢:)
猜你喜欢
  • 2019-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-07
  • 2013-12-23
  • 1970-01-01
  • 2011-06-12
  • 1970-01-01
相关资源
最近更新 更多