简体   繁体   English

使用Java保存到数据库时更改Excel日期数据的日期格式

[英]Change date format of excel date data while saving into database with Java

I have my codes written to save my user's data in an excel file into MySQL database. 我编写了代码,以将用户数据以excel文件格式保存到MySQL数据库中。 While I run it, everything works fine except the date is wrong. 当我运行它时,除日期错误外,其他一切都正常。 In the excel file, the date format is dd.MM.yyyy, whereas the date format in MySQL is yyyy-MM-dd. 在excel文件中,日期格式为dd.MM.yyyy,而MySQL中的日期格式为yyyy-MM-dd。 What should I do in my code to convert the date format while saving it into database? 在将日期格式保存到数据库中的同时,我该如何在代码中进行转换?

These are the codes: 这些是代码:

import java.io.FileInputStream;
import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelToDb {
    public static void main( String [] args ) {
        String fileName="testing.xlsx";
        Vector dataHolder=read(fileName);
        saveToDatabase(dataHolder);
    }
    public static Vector read(String fileName)    {
        Vector cellVectorHolder = new Vector();
        try{
            FileInputStream myInput = new FileInputStream(fileName);
            //POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
            XSSFWorkbook myWorkBook = new XSSFWorkbook(myInput);
            XSSFSheet mySheet = myWorkBook.getSheetAt(0);
            Iterator rowIter = mySheet.rowIterator();
            while(rowIter.hasNext()){
                XSSFRow myRow = (XSSFRow) rowIter.next();
                Iterator cellIter = myRow.cellIterator();
                //Vector cellStoreVector=new Vector();
                List list = new ArrayList();
                while(cellIter.hasNext()){
                    XSSFCell myCell = (XSSFCell) cellIter.next();
                    list.add(myCell);
                }
                cellVectorHolder.addElement(list);
            }
        }catch (Exception e){e.printStackTrace(); }
        return cellVectorHolder;
    }
    private static void saveToDatabase(Vector dataHolder) {
        String activityId="";
        String activityName="";
        String activityAllocation="";
        String activityDate="";
        String activityPersonInCharge="";
        System.out.println(dataHolder);

        for(Iterator iterator = dataHolder.iterator();iterator.hasNext();) {
            List list = (List) iterator.next();
            activityId= list.get(0).toString();
            activityName= list.get(5).toString();
            activityAllocation= list.get(8).toString();
            activityDate= list.get(10).toString();
            activityPersonInCharge= list.get(11).toString();


            try {
                Class.forName("com.mysql.jdbc.Driver").newInstance();
                Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/TEST", "root", "password");
                System.out.println("connection made...");
                PreparedStatement stmt=con.prepareStatement("INSERT INTO TEST_DEMO(ACT_ID,ACT_NAME,ACT_ALLOCATION,ACT_DATE,ACT_PERSON_ON_CHARGE) VALUES(?,?,?,?,?)");
                stmt.setString(1, activityId);
                stmt.setString(2, activityName);
                stmt.setString(3, activityAllocation);
                stmt.setString(4, activityDate);
                stmt.setString(5, activityPersonInCharge);
                stmt.executeUpdate();

                System.out.println("Data is inserted");
                stmt.close();
                con.close();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }



        }
    }

Please provide some clues for the date formatter part. 请提供有关日期格式化程序部分的一些线索。

Thanks in advance. 提前致谢。

You just try this:
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date dt = sdf.parse("your date field");
sdf.applyPattern("yyyy-MM-dd");
res = sdf.format(dt);

Don't shoot the messenger. 不要开枪。 :-) :-)

As far as I remember dates can be in different formats in MS Excel and there is no way you can determine through Apache POI which format was used. 据我所记得,日期在MS Excel中可以采用不同的格式,因此无法通过Apache POI确定使用哪种格式。 I should enjoy if someone can tell me I'm wrong here. 如果有人可以告诉我我错了,我应该感到高兴。

For storing a date in MySQL you will want to store it in a column of datatype date . 为了在MySQL中存储日期,您将需要将其存储在datatype date列中。 Such a column doesn't have a format. 这样的列没有格式。 You will want to format the date from the column only when you present it to a user (or serialize it to JSON or for some other reason need a string representation). 仅当您向用户展示日期(或将其序列化为JSON或出于其他原因需要字符串表示形式)时,才需要格式化该列中的日期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM