tiempo que puedo ingles formato fecha evitar español desde dar cómo celdas cambie cambiar automaticamente aaaa java date apache-poi

java - que - PDI: ¿Cómo configuro el valor de celda en Fecha y aplico el formato de fecha de Excel predeterminado?



formato fecha excel formula (6)

Este ejemplo de código se puede usar para cambiar el formato de fecha. Aquí quiero cambiar de aaaa-MM-dd a dd-MM-aaaa. Aquí pos es la posición de la columna.

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(); }}

He estado usando Apache POI durante algún tiempo para leer archivos existentes de Excel 2003 mediante programación. Ahora tengo un nuevo requisito para crear archivos .xls enteros en la memoria (aún usando Apache POI) y luego escribirlos en un archivo al final. El único problema que se interpone en mi camino es el manejo de celdas con fechas.

Considera el siguiente código:

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

Cuando escribo el libro que contiene esta celda en un archivo y lo abro con Excel, la celda se muestra como un número. Sí, me doy cuenta de que Excel almacena sus ''fechas'' como el número de días desde el 1 de enero de 1900 y eso es lo que representa el número en la celda.

PREGUNTA: ¿Qué llamadas de API puedo usar en PDI para decirle que quiero un formato de fecha predeterminado aplicado a mi celda de fecha?

Idealmente, quiero que la celda de la hoja de cálculo se muestre con el mismo formato de fecha predeterminado que Excel le hubiera asignado si un usuario hubiera abierto manualmente la hoja de cálculo en Excel y hubiera ingresado un valor de celda que Excel reconoció como una fecha.


Este ejemplo es para trabajar con tipos de archivos .xlsx. Este ejemplo proviene de una página .jsp utilizada para crear una hoja de cálculo .xslx.

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);


Estoy escribiendo mi respuesta aquí porque puede ser útil para otros lectores, que podrían tener un requisito ligeramente diferente que el que pregunta aquí.

Preparo una plantilla .xlsx; todas las celdas que se rellenarán con fechas ya están formateadas como celdas de fecha (usando Excel).

Abro la plantilla .xlsx usando Apache POI y luego solo escribo la fecha en la celda, y funciona.

En el siguiente ejemplo, la celda A1 ya está formateada desde Excel con el formato [$-409]mmm yyyy , y el código de Java se usa solo para rellenar la celda.

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);

Cuando se abre el Excel, la fecha se formatea correctamente.


Para establecer el tipo predeterminado de Excel Fecha (predeterminado en la configuración regional de nivel de sistema operativo / -> ie xlsx se verá diferente cuando lo abra una persona alemana o británica / y marcado con un asterisco si lo elige en el selector de formato de celda de Excel):

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

Lo hice con xlsx y funcionó bien.


Para saber la cadena de formato utilizada por Excel sin tener que adivinarla: cree un archivo de Excel, escriba una fecha en la celda A1 y formatéelo como desee. Luego ejecuta las siguientes líneas:

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);

Luego copie y pegue la cadena resultante, elimine las barras invertidas (por ejemplo, d/m/yy/ h/.mm;@ convierte en d/m/yy h.mm;@ ) y utilícela en http://poi.apache.org/spreadsheet/quick-guide.html#CreateDateCells código de 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);


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);