poi处理Thu Jan 04 00:00:00 CST 1900日期

最近导入excel出现这个问题,日期格式都是Thu Jan 04 00:00:00 CST 1900,转换为日期都从1900年开始。从网上找到了答案,特此记录:

先贴出关键代码:

本来日期是这么取得

输出为:Thu Jan 04 00:00:00 CST 1900这种格式

存入数据库为:

现在改为

 

 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");   

 输出为:Mon Dec 31 00:00:00 CST 2018这种格式,

存入数据库为    

下面为我测试的完整代码,用mybatis测试入库的

其中有两个,一个导入一个导出,入口为info.lumanman.poi.main下的两个类ExportExcel:导出,ImportExcel:导入

pom.xml jar包依赖

<!-- mybatis包 -->
	    <dependency>
		  <groupId>org.mybatis</groupId>
		  <artifactId>mybatis</artifactId>
		  <version>3.4.6</version>
		</dependency>
		
		<!-- mysql驱动包 -->
		<dependency>
		    <groupId>mysql</groupId>
		    <artifactId>mysql-connector-java</artifactId>
		    <version>5.1.39</version>
		</dependency>
		
		<!--poi包  -->
			<dependency>
				<groupId>org.apache.poi</groupId>
				<artifactId>poi-ooxml-schemas</artifactId>
				<version>3.10-FINAL</version>
			</dependency>
	
			<dependency>
				<groupId>org.apache.poi</groupId>
				<artifactId>poi-ooxml</artifactId>
				<version>3.10-FINAL</version>
			</dependency>
	
			<dependency>
				<groupId>org.apache.poi</groupId>
				<artifactId>poi</artifactId>
				<version>3.10-FINAL</version>
			</dependency>

 目录结构

文件从上而下:

package info.lumanman.poi.dao;

import java.util.List;

import info.lumanman.poi.po.Student;

public interface StudentDao {

	int addStudent(List<Student> studentList);
	
	Student getStudentList();
}
package info.lumanman.poi.main;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import info.lumanman.poi.po.Student;
import info.lumanman.poi.util.ExportExcelUtil;
import info.lumanman.poi.util.ImportExcelUtil;


public class ExportExcel {

public static void main(String[] args) throws Exception {
		
		String resource="mybatis-config.xml";
		InputStream inputStream=Resources.getResourceAsStream(resource);
		
		//加载mybatis-config.xml配置文件,并创建SqlSessionFactory对象
		SqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
		//创建sqlSession对象
		SqlSession session=sessionFactory.openSession();
		try {
			//执行selece语句,将resultSet映射成对象并返回
			List<Student> studentList=session.selectList("info.lumanman.poi.dao.StudentDao.getStudentList");
			ExportExcelUtil.exportTwo(studentList);
			//输出Blog对象
			System.out.println(studentList);
		}finally {
			session.close();
		}
		
	}
}
package info.lumanman.poi.main;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import info.lumanman.poi.po.Student;
import info.lumanman.poi.util.ImportExcelUtil;


public class ImportExcel {

public static void main(String[] args) throws Exception {
		
		String resource="mybatis-config.xml";
		InputStream inputStream=Resources.getResourceAsStream(resource);
		
		//加载mybatis-config.xml配置文件,并创建SqlSessionFactory对象
		SqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
		//创建sqlSession对象
		SqlSession session=sessionFactory.openSession();
		try {
			//执行selece语句,将resultSet映射成对象并返回
			int result=session.insert("info.lumanman.poi.dao.StudentDao.addStudent",ImportExcelUtil.getStudentList() );
			session.commit();
			//输出Blog对象
			System.out.println(result);
		}finally {
			session.close();
		}
		
	}
}
package info.lumanman.poi.po;

import java.util.Date;

public class Student {

	private int id;
	
	private String name;
	
	private int age;
	
	private Date createDate;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public Date getCreateDate() {
		return createDate;
	}

	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}
	
	
}
package info.lumanman.poi.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import info.lumanman.poi.po.Student;

public class ExportExcelUtil {

	/** 
     * 读取Excel测试,兼容 Excel 2003/2007/2010 
     * @throws Exception  
     */  
    public static  void addStudentList(List<Student> studentList) throws Exception {  
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
        try {  
            // 同时支持Excel 2003、2007  
            File excelFile = new File("C:\\Users\\WM\\Desktop\\student-export.xlsx"); // 创建文件对象  
            if(!excelFile.exists()){
            	excelFile.createNewFile();
            }
            FileInputStream in = new FileInputStream(excelFile); // 文件流  
            ImportExcelUtil.checkExcelVaild(excelFile);  
           //Workbook workbook = ImportExcelUtil.getWorkbok(in,excelFile);  
            Workbook workbook = WorkbookFactory.create(in); // 这种方式 Excel2003/2007/2010都是可以处理的  
            Sheet sheet = workbook.createSheet("工作簿1");   // 遍历第三个Sheet  
            
            sheet.getRow(0).getCell(0).setCellValue("姓名");
        	sheet.getRow(0).getCell(1).setCellValue("年龄");
        	sheet.getRow(0).getCell(2).setCellValue("创建时间");
            
            for(int i=1;i<studentList.size();i++){//出去目录:遍历行
            	sheet.getRow(i).getCell(0).setCellValue(studentList.get(i-1).getName());
            	sheet.getRow(i).getCell(0).setCellValue(studentList.get(i-1).getAge());
            	sheet.getRow(i).getCell(0).setCellValue(studentList.get(i-1).getCreateDate());
            	
            	
            }
        } catch (Exception e) {  
            e.printStackTrace();  
            
        }
    }
    
    public static void exportTwo(List<Student> studentList) throws Exception{
    	// create a new file
    	FileOutputStream out = new FileOutputStream("C:\\Users\\WM\\Desktop\\student-export.xlsx");
    	// create a new workbook
    	Workbook wb = new HSSFWorkbook();
    	// create a new sheet
    	Sheet sheet = wb.createSheet();
    	// declare a row object reference
    	Row row = null;
    	// declare a cell object reference
    	
    	wb.setSheetName(0, "学生基本信息" );
    	Cell cell=null;
    	//设置表头
    	row = sheet.createRow(0);
    	sheet.setColumnWidth(0, 10000);
    	sheet.setColumnWidth(1, 3000);
    	sheet.setColumnWidth(2, 4000);
    	
    	CellStyle cellStyle = wb.createCellStyle();
    	cellStyle.setAlignment(CellStyle.ALIGN_CENTER); // 居中 
    	
    	
    	cell = row.createCell(0);
    	cell.setCellStyle(cellStyle);
    	cell.setCellValue("姓名");
    	
    	cell = row.createCell(1);
    	cell.setCellStyle(cellStyle);
    	cell.setCellValue("年龄");
		
    	cell = row.createCell(2);
    	cell.setCellStyle(cellStyle);
    	cell.setCellValue("创建时间");
		
    	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		
    	for (int rownum =1; rownum < studentList.size(); rownum++){
    		
    		row = sheet.createRow(rownum);//从第二行开始创建
    		
    		cell = row.createCell(0);
    		cell.setCellValue(studentList.get(rownum-1).getName());
    		
    		cell = row.createCell(1);
    		cell.setCellValue(studentList.get(rownum-1).getAge());
    		
    		cell = row.createCell(2);
    		cell.setCellValue(sdf.format(studentList.get(rownum-1).getCreateDate()));
    	    	
    	    	
    	    	
    	}
    	wb.write(out);
    	out.close();
    }
}
package info.lumanman.poi.util;

/**
 * 
 */
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import info.lumanman.poi.po.Student;
 
/**
 *
 * Description: Excel操作
 * 
 * CreateTime: 2017年12月11日  下午3:08:09
 *
 * Change History:
 *
 *        Date             CR Number              Name              Description of change
 *
 */
public class ImportExcelUtil {
 
	private static final String EXCEL_XLS = "xls";  
    private static final String EXCEL_XLSX = "xlsx";  
  
    /** 
     * 判断Excel的版本,获取Workbook 
     * @param in 
     * @param filename 
     * @return 
     * @throws IOException 
     */  
    public static Workbook getWorkbok(InputStream in,File file) throws IOException{  
        Workbook wb = null;  
        if(file.getName().endsWith(EXCEL_XLS)){  //Excel 2003  
            wb = new HSSFWorkbook(in);  
        }else if(file.getName().endsWith(EXCEL_XLSX)){  // Excel 2007/2010  
            wb = new XSSFWorkbook(in);  
        }  
        return wb;  
    }  
  
    /** 
     * 判断文件是否是excel 
     * @throws Exception  
     */  
    public static void checkExcelVaild(File file) throws Exception{  
        if(!file.exists()){  
            throw new Exception("文件不存在");  
        }  
        if(!(file.isFile() && (file.getName().endsWith(EXCEL_XLS) || file.getName().endsWith(EXCEL_XLSX)))){  
            throw new Exception("文件不是Excel");  
        }  
    }  
    
    /** 
     * 读取Excel测试,兼容 Excel 2003/2007/2010 
     * @throws Exception  
     */  
    public static List<Student> getStudentList() throws Exception {  
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
        try {  
            // 同时支持Excel 2003、2007  
            File excelFile = new File("C:\\Users\\WM\\Desktop\\student.xlsx"); // 创建文件对象  
            FileInputStream in = new FileInputStream(excelFile); // 文件流  
            checkExcelVaild(excelFile);  
            Workbook workbook = getWorkbok(in,excelFile);  
            //Workbook workbook = WorkbookFactory.create(is); // 这种方式 Excel2003/2007/2010都是可以处理的  
            Sheet sheet = workbook.getSheetAt(0);   // 遍历第三个Sheet  
            //获取总行数
//          System.out.println(sheet.getLastRowNum());
            List<Student> studentList=new ArrayList<Student>();
            for(int i=1;i<sheet.getLastRowNum();i++){//出去目录:遍历行
            	Student student=new Student();
//            	student.setName((String)getValue(sheet.getRow(i).getCell(0)));
//            	
//            	String ageExcel=String.valueOf((Double)getValue(sheet.getRow(i).getCell(1)));
//            	student.setAge(Integer.parseInt(ageExcel.substring(0,ageExcel.indexOf("."))));
//            	student.setCreateDate(fmt.parse((String)getValue(sheet.getRow(i).getCell(1))));
            	sheet.getRow(i).getCell(0).setCellType(Cell.CELL_TYPE_STRING);
            	student.setName(sheet.getRow(i).getCell(0).getStringCellValue());
            	
            	sheet.getRow(i).getCell(1).setCellType(Cell.CELL_TYPE_STRING);
            	student.setAge(Integer.parseInt(sheet.getRow(i).getCell(1).getStringCellValue()));
            	
            	sheet.getRow(i).getCell(2).setCellType(Cell.CELL_TYPE_STRING);
            	student.setCreateDate(sdf.parse(sheet.getRow(i).getCell(2).getStringCellValue()));
            	studentList.add(student);
            }
            return studentList;
        } catch (Exception e) {  
            e.printStackTrace();  
            
        }
        return null;
    }
    
    
    
}

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="info.lumanman.poi.dao.StudentDao" >
 
  <!-- 定义sql语句 -->
  <select id="getStudentList" resultType="info.lumanman.poi.po.Student">
  		select name,age,create_date createDate from student
  </select>
  
  <insert id="addStudent"   parameterType="list" >
  insert into student(name,age,create_date)values
  		<foreach collection="list"  item="student" separator="," >
  		(#{student.name},#{student.age},#{student.createDate})
  		</foreach>
  </insert>
  
  
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings><!-- 全局配置信息 -->
        <setting name="cacheEnabled" value="true" />
        <!-- 打印查询语句 -->
        <setting name="logImpl" value="STDOUT_LOGGING" />
    </settings>
	<environments default="development">
		<environment id="development">
			<!--配置事务管理器的类型  -->
			<transactionManager type="JDBC">
			</transactionManager>
			
			<!-- 配置数据源的类型,以及数据库连接的相关信息 -->
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver"/>
				<property name="url" value="jdbc:mysql://localhost:3306/test"/>
				<property name="username" value="root"/>
				<property name="password" value="123456"/>
			</dataSource>
		</environment>
	</environments>
	
	<!--配置映射配置文件的位置  -->
	<mappers>
		<mapper resource="mapper/StudentMapper.xml"/>
	</mappers>
</configuration>

 数据库脚本

DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL DEFAULT '',
  `age` int(11) NOT NULL DEFAULT '0',
  `create_date` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=488 DEFAULT CHARSET=utf8mb4;

 参考地址:https://blog.csdn.net/wwd0501/article/details/78780646

                   http://poi.apache.org/components/spreadsheet/quick-guide.html这是官方的文档

猜你喜欢

转载自blog.csdn.net/fly_grass_fish/article/details/83822326
00