POI - 如何将单元格值设置为日期并应用默认Excel日期格式?

问题描述 投票:88回答:6

我已经使用Apache POI一段时间以编程方式读取现有的Excel 2003文件。现在我有了一个新的要求,即在内存中创建整个.xls文件(仍使用Apache POI),然后将它们写入文件末尾。阻碍我的唯一问题是处理带日期的细胞。

请考虑以下代码:

Date myDate = new Date();
HSSFCell myCell;
// code that assigns a cell from an HSSFSheet to 'myCell' would go here...
myCell.setCellValue(myDate);

当我将包含此单元格的工作簿写入文件并使用Excel打开时,单元格显示为数字。是的,我确实认识到Excel将其“日期”存储为自1900年1月1日以来的天数,这就是单元格中的数字所代表的数字。

问题:我可以在POI中使用哪些API调用来告诉它我需要将默认日期格式应用于我的日期单元格?

理想情况下,如果用户在Excel中手动打开电子表格并键入Excel识别为日期的单元格值,我希望电子表格单元格显示的Excel默认日期格式与Excel分配的格式相同。

java date apache-poi
6个回答
147
投票

http://poi.apache.org/spreadsheet/quick-guide.html#CreateDateCells

CellStyle cellStyle = wb.createCellStyle();
CreationHelper createHelper = wb.getCreationHelper();
cellStyle.setDataFormat(
    createHelper.createDataFormat().getFormat("m/d/yy h:mm"));
cell = row.createCell(1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);

21
投票

要设置为默认Excel类型日期(默认为操作系统级别区域设置/ - >例如,如果您在Excel的单元格格式选择器中选择它时,xlsx在德国或英国人打开时会显示不同/并且标有星号)您应该:

    CellStyle cellStyle = xssfWorkbook.createCellStyle();
    cellStyle.setDataFormat((short)14);
    cell.setCellStyle(cellStyle);

我用xlsx做到了它并且工作正常。


11
投票

此示例适用于.xlsx文件类型。此示例来自用于创建.xslx电子表格的.jsp页面。

import org.apache.poi.xssf.usermodel.*; //import needed

XSSFWorkbook  wb = new XSSFWorkbook ();  // Create workbook
XSSFSheet sheet = wb.createSheet();      // Create spreadsheet in workbook
XSSFRow row = sheet.createRow(rowIndex); // Create the row in the spreadsheet


//1. Create the date cell style
XSSFCreationHelper createHelper = wb.getCreationHelper();
XSSFCellStyle cellStyle         = wb.createCellStyle();
cellStyle.setDataFormat(
createHelper.createDataFormat().getFormat("MMMM dd, yyyy")); 

//2. Apply the Date cell style to a cell

//This example sets the first cell in the row using the date cell style
cell = row.createCell(0);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);

1
投票

我在这里写我的答案,因为它可能对其他读者有帮助,他们的要求可能与提问者的要求略有不同。

我准备一个.xlsx模板;所有将填充日期的单元格已经格式化为日期单元格(使用Excel)。

我使用Apache POI打开.xlsx模板,然后将日期写入单元格,它可以工作。

在下面的示例中,单元格A1已经在Excel中格式化为格式为[$-409]mmm yyyy,Java代码仅用于填充单元格。

FileInputStream inputStream = new FileInputStream(new File("Path to .xlsx template"));
Workbook wb = new XSSFWorkbook(inputStream);
Date date1=new Date();
Sheet xlsMainTable = (Sheet) wb.getSheetAt(0);
Row myRow= CellUtil.getRow(0, xlsMainTable);
CellUtil.getCell(myRow, 0).setCellValue(date1);

打开Excel时,日期格式正确。


0
投票

此代码示例可用于更改日期格式。在这里,我想从yyyy-MM-dd改为dd-MM-yyyy。这里pos是列的位置。

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

class Test{ 
public static void main( String[] args )
{
String input="D:\\somefolder\\somefile.xlsx";
String output="D:\\somefolder\\someoutfile.xlsx"
FileInputStream file = new FileInputStream(new File(input));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> iterator = sheet.iterator();
Cell cell = null;
Row row=null;
row=iterator.next();
int pos=5; // 5th column is date.
while(iterator.hasNext())
{
    row=iterator.next();

    cell=row.getCell(pos-1);
    //CellStyle cellStyle = wb.createCellStyle();
    XSSFCellStyle cellStyle = (XSSFCellStyle)cell.getCellStyle();
    CreationHelper createHelper = wb.getCreationHelper();
    cellStyle.setDataFormat(
        createHelper.createDataFormat().getFormat("dd-MM-yyyy"));
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Date d=null;
    try {
        d= sdf.parse(cell.getStringCellValue());
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        d=null;
        e.printStackTrace();
        continue;
    }
    cell.setCellValue(d);
    cell.setCellStyle(cellStyle);
   }

file.close();
FileOutputStream outFile =new FileOutputStream(new File(output));
workbook.write(outFile);
workbook.close();
outFile.close();
}}

0
投票

要知道Excel使用的格式字符串而不必猜测它:创建一个excel文件,在单元格A1中写入日期并根据需要对其进行格式化。然后运行以下行:

FileInputStream fileIn = new FileInputStream("test.xlsx");
Workbook workbook = WorkbookFactory.create(fileIn);
CellStyle cellStyle = workbook.getSheetAt(0).getRow(0).getCell(0).getCellStyle();
String styleString = cellStyle.getDataFormatString();
System.out.println(styleString);

然后复制粘贴生成的字符串,删除反斜杠(例如d/m/yy\ h\.mm;@变为d/m/yy h.mm;@)并在http://poi.apache.org/spreadsheet/quick-guide.html#CreateDateCells代码中使用它:

CellStyle cellStyle = wb.createCellStyle();
CreationHelper createHelper = wb.getCreationHelper();
cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("d/m/yy h.mm;@"));
cell = row.createCell(1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);
© www.soinside.com 2019 - 2024. All rights reserved.