Excel date to java date

As many users already pointed out, Excel stores dates and times as a number representing the number of days since January 0, 1900, plus a fractional portion of a 24 hour day: ddddd.tttttt.
This is called serial date or serial date-time.

But the answers here represent only a part of the story — except for pointing out ready to use methods from existing libraries.

The linked documentation from Microsoft doesn’t make it any more clear.

MS DATEVALUE function states:

Excel stores dates as sequential serial numbers so that they can be used in calculations.
By default, January 1, 1900 is serial number 1, and January 1, 2008 is serial number 39448 because it is 39,447 days after January 1, 1900

Well, I’m going to check this statement:

LocalDate testDate = LocalDate.of(1900, Month.JANUARY, 1).plusDays(39447);
System.out.println(testDate);// prints 2008-01-02

39,447 days after January 1, 1900 it’s indeed… January 2, 2008!

Why is that?

The fact that dates in Excel are represented by the number of days starting from an epoch (December 30, 1899 or January 1, 1900 or 1904…) is only a part of the story.

I found an ultimate answer here: Dates And Times In Excel (some god or Whoever may bless these guys).

The developers who implemented the date routines in Excel introduced deliberately a bug for compatibility with the same known issue from Lotus 1-2-3.

They treated the year 1900 as a leap year but it’s not,
so any date exceeding January 28, 1900 it’s a day more than the actual date.

That’s why Excel thinks that January 1, 2008 is represented by the number 39448: because it is 39,448 units after January 0, 1900 (yes, Excel thinks zero) — ie 39,447 days plus January 29, 1900.

Excel can also treat the date portion of a serial date as the number of days since January 0, 1904; this mode is called 1904-mode or 1904-system and it’s used for compatibility with the Macintosh systems.

Since Excel dates don’t carry any time-zone information — it’s only a number — it’s better to use Java classes like LocalDate/LocalDateTime to represent such values without a time-zone information.

Well, in pratice — for nowadays dates — one may figure Excel epoch starting from December 30, 1900 but it’s not.

Excel demo — date format is dd/mm/yyyy

7

Dates are inserted as the number on the left

A class suitable for the required conversion:

public class SerialDate {

    //days from 1899-12-31 to Instant.EPOCH (1970-01-01T00:00:00Z)
    public static final long EPOCH = -25568L;
    private long serialDays;
    private double serialTime;
    private long epochDays;
    private long daySeconds;

    /**
     * @param date number of Excel-days since <i>January 0, 1899</i>
     */
    public SerialDate(long date) {
        serialDays = date;
        if (date > 59)//Lotus123 bug
            --date;
        epochDays = EPOCH + date;
    }
            
    /**
     * @param date number of days since <i>January 0, 1899</i> with a time fraction
     */
    public SerialDate(double date) {
        this((long)date);
        serialTime = date - serialDays;
        daySeconds = Math.round(serialTime * 24 * 60 * 60);
    }
            
    /**
     * @return days since 1970-01-01
     */
    public long toEpochDays() {
        return epochDays;
    }
            
    /**
     * @return seconds of the day for this SerialDate
     */
    public long toDaySeconds() {
        return daySeconds;
    }
            
    /**
     * @return a value suitable for an Excel date
     */
    public double getSerialDate() {
        return serialTime + serialDays;
    }
    
}

Usage example:

LocalDate dt = LocalDate.ofEpochDay(new SerialDate(41275).toEpochDays());
System.out.println(dt);//prints 2013-01-01

SerialDate sd = new SerialDate(33257.415972222225);
LocalDateTime dt = LocalDateTime.of(
        LocalDate.ofEpochDay(sd.toEpochDays()),
        LocalTime.ofSecondOfDay(sd.toDaySeconds()));
System.out.println(dt);//prints 1991-01-19T09:59

Содержание

  1. converting excel date into mm/dd/yyyy format
  2. 5 Answers 5
  3. Java Convert ‘Excel Date Serial Number’ to ‘DateTime’ [duplicate]
  4. 2 Answers 2
  5. Converting number representing a date in Excel to a Java Date object
  6. 6 Answers 6
  7. java.time
  8. Epoch reference date: 1899-12-30
  9. Do the math
  10. About java.time
  11. Convert Excel timestamp to java.sql.date
  12. 3 Answers 3
  13. POI — Problems converting between Excel & Java date & vice-versa
  14. 1 Answer 1

converting excel date into mm/dd/yyyy format

I am reading from an excel sheet using poi jar where in there is a date column.If i print out the value of the data cloumn :

It gives me value like 3124.0

So i tried with this code to convert to the mm/dd/yyyy format:

But for reading a date 06/30/2001 i got this value as output:

5 Answers 5

Your Date Format String is wrong. Should be like following

Read the Java doc for SimpleDateFormat

First check your date format

and also check the POI API For more info to deal with dates in excel,there are better ways to handle the dates.

check HSSFDateUtil.isCellDateFormatted() , getExcelDate ,getJavaDate

getJavaDate

public static java.util.Date getJavaDate(double date)

Given an Excel date with using 1900 date windowing, and converts it to a java.util.Date.

NOTE: If the default TimeZone in Java uses Daylight Saving Time then the conversion back to an Excel date may not give the same value, that is the comparison excelDate == getExcelDate(getJavaDate(excelDate,false)) is not always true. For example if default timezone is Europe/Copenhagen, on 2004-03-28 the minute after 01:59 CET is 03:00 CEST, if the excel date represents a time between 02:00 and 03:00 then it is converted to past 03:00 summer time Parameters:

date — The Excel date. Returns: Java representation of the date, or null if date is not a valid Excel date

Источник

Java Convert ‘Excel Date Serial Number’ to ‘DateTime’ [duplicate]

How convert ‘excel date serial number'(i.e. 33257.415972222225) to DateTime(i.e. 19/01/1991 09:59:00) using Java?

2 Answers 2

You can also have a look at the Source code of Apache POI, method DateUtils#getLocalDateTime(double date, boolean use1904windowing, boolean roundSeconds) . This utility class offers more handy methods for working with Excel dates.

Excel stores dates and times as a number representing the number of days since January 0, 1900, plus a fractional portion of a 24 hour day: ddddd.tttttt .
This is called serial date or serial date-time.

The linked documentation from Microsoft seems to be quite clear.

Excel stores dates as sequential serial numbers so that they can be used in calculations. By default, January 1, 1900 is serial number 1, and January 1, 2008 is serial number 39448 because it is 39,447 days after January 1, 1900

Well, I’m going to check this statement:

39,447 days after January 1, 1900 it’s indeed. January 2, 2008!

Why is that?

The fact that dates in Excel are represented by the number of days starting from an epoch (December 30, 1899 or January 1, 1900 or 1904. ) is only a part of the story.

I found an ultimate answer here: Dates And Times In Excel (some god or Whoever may bless these guys).

The developers who implemented the date routines in Excel introduced deliberately a bug for compatibility with the same known issue from Lotus 1-2-3.

They treated the year 1900 as a leap year but it’s not, so any date exceeding February 28, 1900 it’s a day more than the actual date.

That’s why Excel thinks that January 1, 2008 is represented by the number 39448: because it is 39,448 units after January 0, 1900 (yes, Excel thinks zero) — ie 39,447 days plus February 29, 1900.

Excel can also treat the date portion of a serial date as the number of days since January 0, 1904; this mode is called 1904-mode or 1904-system and it’s used for compatibility with the Macintosh systems.

Since Excel dates don’t carry any time-zone information — it’s only a number — it’s better to use Java classes like LocalDate / LocalDateTime to represent such values without a time-zone information.

Well, in pratice — for nowadays dates — one may figure Excel epoch starting from December 30, 1900 but it’s not.

Excel demo — date format is dd/mm/yyyy hh:MM:ss


Dates are inserted as the number on the left

A class suitable for the required conversion:

Источник

Converting number representing a date in Excel to a Java Date object

I have a date column in Excel, but when I’m reading it in my Java application I’m getting the value as number.

I’m getting it as

How to convert the number to a date in my Java application?

6 Answers 6

Here is a minimal working example how to convert an Excel date to a Java date:

You also need to import the following packages:

Use modern java.time classes.

java.time

The modern solution uses the java.time classes that supplanted the terrible legacy date-time classes bundled with the earliest versions of Java.

Epoch reference date: 1899-12-30

According to this documentation, that value from Microsoft Excel is the number of days since the epoch reference of 1900-01-01 in UTC. Internally, the actual reference date is December 30, 1899 as documented on this Wikipedia page.

Beware, some versions (old versions for macOS?) of Excel use a different epoch in 1904.

Establish the epoch reference somewhere in your code.

Do the math

Parse your input string as a BigDecimal for accuracy (versus floating-point types that trade away accuracy for faster execution).

Add the number of whole days to the epoch reference date.

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat .

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

Note Excel stores dates as the number of days (plus fractional days) since 1900 (and in some cases it can be from 1904). See http://support.microsoft.com/kb/180162.

As many users already pointed out, Excel stores dates and times as a number representing the number of days since January 0, 1900, plus a fractional portion of a 24 hour day: ddddd.tttttt .
This is called serial date or serial date-time.

But the answers here represent only a part of the story — except for pointing out ready to use methods from existing libraries.

The linked documentation from Microsoft doesn’t make it any more clear.

Excel stores dates as sequential serial numbers so that they can be used in calculations. By default, January 1, 1900 is serial number 1, and January 1, 2008 is serial number 39448 because it is 39,447 days after January 1, 1900

Well, I’m going to check this statement:

39,447 days after January 1, 1900 it’s indeed. January 2, 2008!

Why is that?

The fact that dates in Excel are represented by the number of days starting from an epoch (December 30, 1899 or January 1, 1900 or 1904. ) is only a part of the story.

I found an ultimate answer here: Dates And Times In Excel (some god or Whoever may bless these guys).

The developers who implemented the date routines in Excel introduced deliberately a bug for compatibility with the same known issue from Lotus 1-2-3.

They treated the year 1900 as a leap year but it’s not, so any date exceeding January 28, 1900 it’s a day more than the actual date.

That’s why Excel thinks that January 1, 2008 is represented by the number 39448: because it is 39,448 units after January 0, 1900 (yes, Excel thinks zero) — ie 39,447 days plus January 29, 1900.

Excel can also treat the date portion of a serial date as the number of days since January 0, 1904; this mode is called 1904-mode or 1904-system and it’s used for compatibility with the Macintosh systems.

Since Excel dates don’t carry any time-zone information — it’s only a number — it’s better to use Java classes like LocalDate / LocalDateTime to represent such values without a time-zone information.

Well, in pratice — for nowadays dates — one may figure Excel epoch starting from December 30, 1900 but it’s not.

Excel demo — date format is dd/mm/yyyy


Dates are inserted as the number on the left

A class suitable for the required conversion:

Источник

Convert Excel timestamp to java.sql.date

I am extracting a timestamp out of Excel (2010):

It is displayed as «10.06.2015 14:24». The «internal representation» of excel is «42165.6». Last one is outputted from Excel.

So, for now, I want to parse this timestamp into a Java program like this:

How can I do this in line 2?!

Many thanks for your help.

3 Answers 3

Excel stores dates as the number of days since January 1900. This makes it awkward to convert into a Java date (milliseconds since 1 Jan 1970). If you cannot export it in a readable format, you’ll need to create a Java Calendar, set it to 1 Jan 1900, and add the number of days.

NOTE A java.sql.Date can be created from a java.util.Date as follows:

The fastest way to get from the excel notation to a java.sql.Date is:

Excel stores a date since 01-01-1900, java.sql.date since 01-01-1970. There are exactly 25569 days difference between both dates. The constructor of java.sql.Date wants the milliseconds (!) since 01-01-1970, so with «* 86400» we get the seconds and then with (* 1000) the milliseconds.

Putting 42165.6 in excel and formatting to a date gives the correct date 6/10/15 14:24 .

For me the answers by mrbela and NickJ both gave incorrect answers to the question of 42165.6, 06/10/2015 09:23 and 06/12/2015 03:25 . This seems to be true of most of the examples I’ve tried.

The solution that worked for me was to use Apache POI, which is a java API for Microsoft Documents. This question is very similar and had the pointers that led me to poi.

Источник

POI — Problems converting between Excel & Java date & vice-versa

I’m trying to save a time in a cell in an Excel workbook using Apache POI (4.0.1).

I’m converting the time to a java.util.Date and then attempting to use the org.apache.poi.ss.usermodel.DateUtil.getExcelDate method to then save that in the cell.

What I’m finding is that as the time is in the same year as the epoch (1899), there is a hardcoded check in getExcelDate that prohibits conversion of dates with years before 1900, preventing me from doing what I was after.

Output (note, as per the documentation — a «Converted Excel Date» of «-1» indicates an error).

Here you can see I’m asking for the Java Date representing the Excel date «0.5». I’m then taking the Java date provided, but POI says that there is no Excel date corresponding to that — even though I’ve generated it from that.

Am I missing something.

1 Answer 1

Excel date values in 1900 date system start with value 0 = day 0 in January 1900. There are no Excel date values before that.

If you have following cells in Excel :

where the values in column B are the same values as in column A but formatted as dates using number format MM/DD/YYYY hh:mm:ss , you see that.

So there is no Excel date December 31 1899. That’s why DateUtil.getExcelDate(date) fails when date is the Java date Sun Dec 31 00:00:00 GMT 1899 or Sun Dec 31 12:00:00 GMT 1899 .

But DateUtil.getJavaDate(excelDate) returns December 31 1899 when excelDate is a double value from 0.0 to 0.999. . That is because there is no Java date January 0 1900 possible. But there are Excel date values possible from 0.0 to 0.999. .

In other words, the Excel date values from 0.0 to 0.999. are in reality time values before the first possible whole day in Excel , which is date January 01 1900. They not really are in a day but are in day 0 instead.

Since date values from 0.0 to 0.999. and converted Java dates of December 31 1899 are special cases, one could handling them as such.

Источник

Introduction

In this example I will show you how to create date and put it in an excel file using Apache POI in Java language. I will show you how to build the project using both maven and gradle build tools. I will also show you how to create date using Java 8 or prior to Java 8 on java.util.Date and java.util.Calendar.

The Apache POI is to create and maintain Java APIs for manipulating various file formats based upon the Office Open XML standards (OOXML) and Microsoft’s OLE 2 Compound Document format (OLE2). You can read and write MS Excel files using Java. In addition, you can read and write MS Word and MS PowerPoint files using Java. Apache POI is the Java Excel solution (for Excel 97-2008).

Prerequisites

Java 8+, Apache POI – 4.1.1/5.2.2, Gradle 5.6, Maven – 3.6.1 – 3.8.5

Project Setup

Create a standalone maven project or gradle based project in your favorite IDE or tool. The name or artifact id of the project is apache-poi-excel-date.

If you are creating maven based project then you can use the below pom.xml file:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.roytuts</groupId>
	<artifactId>apache-poi-excel-date</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>11</maven.compiler.source>
		<maven.compiler.target>11</maven.compiler.target>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>5.2.2</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.1</version>
			</plugin>
		</plugins>
	</build>
</project>

If you are creating gradle based project then you can use below build.gradle script for creating date in excel file:

plugins {
    id 'java-library'
}

sourceCompatibility = 12
targetCompatibility = 12

repositories {
    jcenter()
}

dependencies {
    implementation 'org.apache.poi:poi-ooxml:4.1.1'
    //required only for jdk 9 or above
    implementation('com.fasterxml.jackson.core:jackson-databind:2.10.1')
}

Create Date in Excel File

Now I will create date in excel file using Apache POI in Java technology. I will put four different kind of date values in excel file – default date, java.util.Date, java.util.Calendar and Java 8’s LocalDate & LocalDateTime.

public class ExcelDate {

	public static void main(String[] args) {
		final String fileName = "excel-date.xlsx";// "excel-date.xls";
		createExcel(fileName);
	}

	public static void createExcel(final String fileName) {
		// get the file extension
		String ext = ".xlsx";
		if (fileName != null) {
			int len = fileName.trim().lastIndexOf(".");
			ext = fileName.trim().substring(len);
		}

		Workbook workbook = null;

		// based on file extension create Workbook object
		if (".xls".equalsIgnoreCase(ext)) {
			workbook = new HSSFWorkbook();
		} else if (".xlsx".equalsIgnoreCase(ext)) {
			workbook = new XSSFWorkbook();
		}

		// create Sheet object
		// sheet name must not exceed 31 characters
		// the name must not contain 0x0000, 0x0003, colon(:), backslash(),
		// asterisk(*), question mark(?), forward slash(/), opening square
		// bracket([), closing square bracket(])
		Sheet sheet = workbook.createSheet("my_sheet");

		// Create first row. Rows are 0 based.
		Row row = sheet.createRow((short) 0);

		// Create a cell
		// put a value in cell.
		// default Date
		row.createCell(0).setCellValue(new Date());

		// style Date
		CreationHelper createHelper = workbook.getCreationHelper();
		CellStyle cellStyle = workbook.createCellStyle();
		cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("MM/dd/yyyy hh:mm:ss"));

		Cell cell = row.createCell(1);
		cell.setCellValue(new Date());
		cell.setCellStyle(cellStyle);

		// set date as java.util.Calendar
		CellStyle cellStyle2 = workbook.createCellStyle();
		cellStyle2.setDataFormat(createHelper.createDataFormat().getFormat("MMM/dd/yyyy hh:mm:ss"));
		cell = row.createCell(2);
		cell.setCellValue(Calendar.getInstance());
		cell.setCellStyle(cellStyle2);

		// set date as Java 8
		CellStyle cellStyle3 = workbook.createCellStyle();
		cellStyle3.setDataFormat(createHelper.createDataFormat().getFormat("MMM/dd/yyyy hh:mm:ss"));
		cell = row.createCell(3);
		cell.setCellValue(LocalDateTime.now());
		cell.setCellStyle(cellStyle3);

		CellStyle cellStyle4 = workbook.createCellStyle();
		cellStyle4.setDataFormat(createHelper.createDataFormat().getFormat("MMM/dd/yyyy"));
		cell = row.createCell(4);
		cell.setCellValue(LocalDate.now());
		cell.setCellStyle(cellStyle4);

		FileOutputStream fileOut = null;
		try {
			fileOut = new FileOutputStream(fileName);
			workbook.write(fileOut);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fileOut.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}

Testing Date Creation in Excel Sheet

Run the above class, you will get excel-date.xlsx or excel-date.xls file created under the project root directory. Open the file you will get the output in sheet “my_sheet”.

create date in excel file using apache poi in java

Source Code

Download

Formatting Dates Using Apache POI — Introduction

In this tutorial, let us examine how to use built in formatters available in Apache POI, to format your date cells in Excel to the pattern you want, in Java, with an example program. Formatting a cell to a specific date value, requires a style (HSSFCellStyle) to be attached to it. In the style, you can use the method setDataFormat method and specify the formatter you want to use. Let us see a step by step guide in POI to attach built in date formatters to XLS documents in this example.

createCellStyle — Specify Date Format

The first step is to create your workbook and add a worksheet. We have done this many times now. After this, you should use workbook.createCellStyle() method and define styles in your workbook. Later, we will attach a date pattern to these styles. Java code snippet for this step is provided below:

                
                HSSFWorkbook my_workbook = new HSSFWorkbook();
                HSSFSheet my_sheet = my_workbook.createSheet("Cell Date");              
                
                HSSFCellStyle my_style_0 = my_workbook.createCellStyle();
                HSSFCellStyle my_style_1 = my_workbook.createCellStyle();

setDataFormat — Attach Date formats to Style

In this step, we use HSSFDataFormat class to retrieve some built in date formats that is available in POI. This is done using getBuiltinFormat method. The value retrieved is then passed to setDataFormat method, which attaches a date format to the styles created in step — 1. We use two styles in this example. Refer below for a code sample:

                                        
                my_style_0.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));
                my_style_1.setDataFormat(HSSFDataFormat.getBuiltinFormat("d-mmm-yy"));
                

Attach Cells with Date Formats

We will now create some data in the worksheet and attach the styles to it. We use «Row» and «Cell» objects to define data. As this is a date based cell, we use java.util.Calendar and java.util.GregorianCalendar to define a date and attach it to the cell. This step is the key as it defines the cell value and attaches the format we created earlier to the cell. A code snippet to do this is provided below:

                
                Calendar calendar = new GregorianCalendar();
                calendar.set(1982,Calendar.NOVEMBER,25);
                          
                Row row = my_sheet.createRow(0);                
                Cell cell = row.createCell(0);
                cell.setCellValue(calendar);            
                cell.setCellStyle(my_style_0); 
                row = my_sheet.createRow(1);            
                cell = row.createCell(1);
                cell.setCellValue(calendar);            
                cell.setCellStyle(my_style_1); 

Finally, we write the workbook to a file to see the formats we applied.

Date Format to Excel Cells — Apache POI — Complete Java Program Example

The full Java code that explains how to use built in formatters to format date cell data in a XLS workbook is provided below:

import java.io.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.*;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
public class FormatCellData {  
        public static void main(String[] args) throws Exception{
                
                HSSFWorkbook my_workbook = new HSSFWorkbook();
                HSSFSheet my_sheet = my_workbook.createSheet("Cell Date");              
                
                HSSFCellStyle my_style_0 = my_workbook.createCellStyle();
                HSSFCellStyle my_style_1 = my_workbook.createCellStyle();
                                        
                my_style_0.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));
                my_style_1.setDataFormat(HSSFDataFormat.getBuiltinFormat("d-mmm-yy"));
                
                Calendar calendar = new GregorianCalendar();
                calendar.set(1982,Calendar.NOVEMBER,25);
                          
                Row row = my_sheet.createRow(0);                
                Cell cell = row.createCell(0);
                cell.setCellValue(calendar);            
                cell.setCellStyle(my_style_0); 
                row = my_sheet.createRow(1);            
                cell = row.createCell(1);
                cell.setCellValue(calendar);            
                cell.setCellStyle(my_style_1); 
                
                FileOutputStream out = new FileOutputStream(new File("C:\cell_date_format.xls"));
                my_workbook.write(out);
                out.close();
        }
}

A screenshot of the cell data produced in the output is provided below: (output cell highlighted in yellow, with the format provided against it)

Excel POI - Format Cell Date Example - Java Program - Output
Excel POI — Format Cell Date Example — Java Program — Output

That completes a quick tutorial to use built in date formatters in POI to format your date data in Excel. In the next article, we will see how to write a custom formatter, instead of using built in formatters.

vitya_brodov

При попытке спарсить excel-файл и записать в объект, кидает exception о том что

Cannot get a numeric value from a text cell

в поле даты.

Вопрос: как правильно спарсить дату?

excel:
615b10a790fab703427611.png

код:

@Data
public class BaseModel {
    private Date dateTime;
    private int paymentId;
    private String paymentPurpose;
    private int sum;

}
@PostMapping("/import")
    public void mapReapExcelDatatoDB(@RequestParam("file") MultipartFile reapExcelDataFile) throws IOException {
        List<BaseModel> models = new ArrayList<>();
        XSSFWorkbook workbook = new XSSFWorkbook(reapExcelDataFile.getInputStream());
        XSSFSheet worksheet = workbook.getSheetAt(0);
        DataFormatter formatter = new DataFormatter();


        for(int i=1; i<worksheet.getPhysicalNumberOfRows() ;i++) {
            BaseModel baseModel = new BaseModel();

            XSSFRow row = worksheet.getRow(i);

            baseModel.setDateTime(row.getCell(0).getDateCellValue());
            baseModel.setPaymentId((int) row.getCell(1).getNumericCellValue());
            baseModel.setPaymentPurpose(row.getCell(2).getStringCellValue());
            baseModel.setSum((int) row.getCell(3).getNumericCellValue());
            models.add(baseModel);
        }
    }


  • Вопрос задан

    более года назад

  • 161 просмотр

Пригласить эксперта

Есть вот такой кусок из обработки разных типов полей excel

switch (sh.getRow(r).getCell(cell).getCellType()) {
			case HSSFCell.CELL_TYPE_NUMERIC:
				if (HSSFDateUtil.isCellDateFormatted(sh.getRow(r).getCell(cell))) {
					Date aDate = sh.getRow(r).getCell(cell).getDateCellValue();
					SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
					res = sdf.format(aDate);
				} else {
					sh.getRow(r).getCell(cell).setCellType(Cell.CELL_TYPE_STRING);
					res = sh.getRow(r).getCell(cell).getStringCellValue();
				}
				break;


  • Показать ещё
    Загружается…

14 апр. 2023, в 01:55

1000 руб./в час

13 апр. 2023, в 23:50

3000 руб./за проект

13 апр. 2023, в 23:18

1000 руб./за проект

Минуточку внимания

Like this post? Please share to your friends:
  • Excel date this month
  • Excel date plus days
  • Excel date month extract
  • Excel date from days to years
  • Excel date from calendar