gpt4 book ai didi

excel - POI-XSSF : user defined data formats

转载 作者:行者123 更新时间:2023-12-04 17:58:36 24 4
gpt4 key购买 nike

我正在读取 excel ,它似乎具有用户定义的数据格式。例如,它有一个数据格式:"yyyy"E,它只是以 yyyy 格式显示日期,后跟字母 E。

现在,这种格式不是内置可用格式的一部分。

所以,当我尝试将其设置为 CellStyleDataFormat 时,它似乎不起作用。

首先,我阅读了一本工作簿,然后根据该工作簿创建了 DataFormat

XSSFWorkbook wb = new XSSFWorkbook(excelToRead);
XSSFDataFormat df = wb.createDataFormat();

df 对象现在也具有用户定义的数据格式(通过打印检查直到 200)。现在,我尝试在同一个工作簿中创建一个新的单元格,采用如下新样式:

XSSFCell cellTemp = row.createCell(0);
XSSFCellStyle styleTemp = wb.createCellStyle();
styleTemp.setDataFormat(df.getFormat(cell.getCellStyle().getDataFormatString()));
cellTemp.setCellStyle(styleTemp);
cellTemp.setCellValue(cell.getStringCellValue());
System.out.print(formatter.formatCellValue(cellTemp)+" ");

但是,格式化程序没有给我正确的字符串值,而是给我日期的基础整数值(我想如果格式无法识别,这是默认值)。

在 XSSF 中使用用户定义格式的正确方法是什么?

更新:我似乎可以使用其他用户定义的格式,例如 yyyy0.0% 但不能使用 yyyy"E"yyyy"A"

最佳答案

我不太清楚你到底想达到什么目的。但是如果 DataFormatter 格式不正确,那么也可以使用派生自的类 CellFormatter .

例子:

import java.io.*;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.format.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.awt.Desktop;
import java.util.Date;

class CustomDateFormatTest {

public static void main(String[] args) {
try {

Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("Sheet1");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);

cell.setCellValue(new Date());

DataFormat format = wb.createDataFormat();
CellStyle cellstyle = wb.createCellStyle();
cellstyle.setDataFormat(format.getFormat("yyyy\"E\""));

cell.setCellStyle(cellstyle);

OutputStream out = new FileOutputStream("CustomDateFormatTest.xlsx");
wb.write(out);
wb.close();

System.out.println("Done");
File outputfile = new File("CustomDateFormatTest.xlsx");
Desktop.getDesktop().open(outputfile);

InputStream inp = new FileInputStream("CustomDateFormatTest.xlsx");
wb = WorkbookFactory.create(inp);

sheet = wb.getSheetAt(0);
row = sheet.getRow(0);
cell = row.getCell(0);

//This will not format properly
DataFormatter dataformatter = new DataFormatter();
System.out.println(dataformatter.formatCellValue(cell));

//This will format properly
String formatstring = cell.getCellStyle().getDataFormatString();
System.out.println(formatstring);
CellDateFormatter celldateformatter = new CellDateFormatter(formatstring);
//For using CellDateFormatter we need to know that the cell value is a Date.
System.out.println(celldateformatter.format(cell.getDateCellValue()));


} catch (InvalidFormatException ifex) {
} catch (FileNotFoundException fnfex) {
} catch (IOException ioex) {
}
}
}

关于excel - POI-XSSF : user defined data formats,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38185164/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com