【发布时间】:2020-07-08 07:10:23
【问题描述】:
目前我正在努力将 DataFormat 设置为特定行。
这就是我的 Excel 工作表的样子。我有这 4 列。 第 1 列应采用 DataFormat Number 第 2 列和第 3 列应采用 DataFormat Date 第4栏没问题
public static void createTableRow(Sheet sheet, List<String> EDIROWKeys, int col, CellStyle style , int lastRowNum){
if(sheet == null){
return;
}
int lastRow = lastRowNum;
int newRow = lastRow + 1;
Workbook wb = sheet.getWorkbook();
SimpleDateFormat format = new SimpleDateFormat();
CreationHelper helper = wb.getCreationHelper();
org.apache.poi.ss.usermodel.DataFormat date = wb.createDataFormat();
XSSFRow row = (XSSFRow) sheet.createRow(newRow);
if(row == null){
return;
}
int startCol = col;
for(String string : EDIROWKeys){
XSSFCell cell = row.createCell(startCol);
FOe.getFOPSessionContext().getDbContext().out().println(string);
if(style != null){
cell.setCellStyle(style);
}else {
XSSFWorkbook wbx = (XSSFWorkbook) sheet.getWorkbook();
XSSFDataFormat dataformat = wbx.createDataFormat();
XSSFCellStyle cs = wbx.createCellStyle();
if(startCol == 1){
cs.setDataFormat(dataformat.getFormat("#"));
}
cell.setCellStyle(cs);
}
cell.setCellValue(string);
startCol++;
}
return;
}
这是我用来创建行和列的方法 https://poi.apache.org/apidocs/dev/org/apache/poi/ss/usermodel/BuiltinFormats.html 这是我从中获取数据格式的资源。 我还尝试将那些带有 HssfDataformat 的 DataFormat 应用到我的单元格 - 也没有成功。
我感谢任何有用的输入 :)
通过使用 setCellValue(Double);...解决...
if(string.matches("\\d+")){
cell.setCellValue(Double.valueOf(string));
startCol++;
continue;
}
【问题讨论】:
-
Cell.setCellValue(java.lang.String value)之后的单元格包含一个文本值。文本值不会使用数字格式。您需要使用Cell.setCellValue(double value)或Cell.setCellValue(java.util.Date value)或其他设置数值的 set-cell-value-method 设置单元格值。 -
谢谢老兄,这解决了问题。现在为数字和日期值添加了一些条件:)!
标签: java excel apache-poi dataformat