itsource

셀 값을 날짜로 설정하고 기본 Excel 날짜 형식을 적용하려면 어떻게 해야 합니까?

mycopycode 2022. 9. 12. 11:47
반응형

셀 값을 날짜로 설정하고 기본 Excel 날짜 형식을 적용하려면 어떻게 해야 합니까?

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이 할당한 기본 날짜 형식으로 스프레드시트 셀을 표시하는 것이 이상적입니다.

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

기본 Excel type Date(Excel 유형 날짜)로 설정하려면 다음과 같이 하십시오(기본값은 OS 수준 로케일 /-> 즉, xlsx는 독일인 또는 영국인이 열었을 때 다르게 표시되며/ Excel의 셀 형식 선택기로 선택한 경우 별표 플래그가 표시됩니다).

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

xlsx로 했는데 잘 작동했어요.

이 예에서는 .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);

질문자와 조금 다른 요구를 가진 독자들에게 도움이 될 수 있기 때문에 여기에 답변을 씁니다.

.xlsx 템플릿을 준비했습니다.날짜가 입력되는 모든 셀은 이미 날짜 셀(Excel 사용)로 포맷되어 있습니다.

Apache POI를 사용하여 .xlsx 템플릿을 열고 셀에 날짜를 쓰면 작동합니다.

에서는 셀 에서 "A1"이라는되어 있습니다.[$-409]mmm yyyyJava java java java java java java java java java java java java 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을 열면 날짜 형식이 올바르게 지정됩니다.

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

@BlondeCode answer와 더불어 사용할 수 있는 모든 형식의 목록을 다음에 나타냅니다.creationHelper.createDataFormat().getFormat((short) index)

0 = "일반"
1 = "0"
2 = "0.00"
3 = "#,##0"
4 = "#,##0.00"
5 = ""$"#,##0_);("$"#,##0)"
6 = ""$"#,##0_);빨강"
7 = ""$"#,##0.00_);("$"#,##0.00)"
8 = ""$"#,##0.00_);빨강"
9 = "0%"
10 = "0.00%"
11 = "0.00E+00"
12 = "# ?/?"
13 = "# ??/??"
14 = "m/d/yy"
15 = "d-contract-yy"
16 = "d-contract"
17 = "yy"
18 = "h:mm AM/PM"
19 = "h:mm:ss AM/PM"
20 = "h:mm"
21 = "h:mm:ss"
22 = "m/d/yy h:mm"
23-36 = 예약 완료
37 = "#,##0_);(#,##0)"
38 = "#,##0_);빨강"
39 = "#,##0.00_);(#,##0.00)"
40 = "#,##0.00_);빨강"
41 = (* # , # 0 ) ; ( * ( # , # 0 ) ; ( * - ) ; ( @
) 42 = ( " $ " * " # , # 0 _ ) ; ( " $ " * , # 0 ) ; ( @
)43 = ( * , # 0 . 00 ) ; ( # 00 ) ) ; ( ?

45 = "mm:ss"
46 = [h]:mm:ss
47 = "mm:ss.0"
48 = "#0.0E+0"
49 = "@"

그리고 색인 164부터, 당신의 맞춤 패턴이 있습니다.

이 코드 샘플을 사용하여 날짜 형식을 변경할 수 있습니다.여기서 yyy-MM-dd에서 dd-MM-yyy로 변경합니다.여기서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();
}}

언급URL : https://stackoverflow.com/questions/5794659/how-do-i-set-cell-value-to-date-and-apply-default-excel-date-format

반응형