从JAVA导出数据到Excel

来源:互联网 发布:汉字简化 知乎 编辑:程序博客网 时间:2024/05/16 09:10

实体类

package com.hello.pojo;import java.util.Date;/*** 包名+类名: com.hello.pojo.User*/public class User {private String code;private String name;private Date birth;public User(){}public User(String code,String name,Date birth){this.code = code;this.name = name;this.birth = birth;}public String getCode() {return code;}public void setCode(String code) {this.code = code;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Date getBirth() {return birth;}public void setBirth(Date birth) {this.birth = birth;}}


代码

package com.excel;import java.io.FileOutputStream;import java.io.IOException;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.List;import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.ss.usermodel.CellStyle;import org.apache.poi.ss.usermodel.HorizontalAlignment;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.util.CellRangeAddress;import org.apache.poi.xssf.usermodel.XSSFWorkbook;import com.hello.pojo.User;/*** 包名+类名: com.excel.Test*/public class Test {public static List getUser() throws ParseException{List<User> li = new ArrayList<>();SimpleDateFormat df =new SimpleDateFormat("yyyy-mm-dd");User u1 = new User("1","中国制造", df.parse("2000-5-20"));User u2 = new User("2", "中国智造", df.parse("2020-03-05"));User u3 = new User("3", "中国AI", df.parse("2030-06-15"));li.add(u1);li.add(u2);li.add(u3);return li;}//逻辑:1、创建工作簿-->2、创建工作表-->3、创建行-->4、创建表格/cell-->5、写入数据-->6、设置储存路径public static void main(String[] args) throws ParseException {//1、创建工作簿Workbook wb = new XSSFWorkbook();//1.1、设置表格的格式----居中CellStyle cs = wb.createCellStyle();cs.setAlignment(HorizontalAlignment.CENTER);//2.1、创建工作表Sheet sheet = wb.createSheet("学生表格");//2.2、合并单元格sheet.addMergedRegion(new CellRangeAddress(4, 8, 5, 9));//3.1、创建行----表头行Row row = sheet.createRow(0);//4、创建格Cell cell = row.createCell(0);cell.setCellValue("学号");cell.setCellStyle(cs);cell = row.createCell(1);cell.setCellValue("姓名");cell.setCellStyle(cs);cell = row.createCell(2);cell.setCellValue("时间");cell.setCellStyle(cs);//5、写入实体数据List<User> list = Test.getUser();for (int i = 0; i < list.size(); i++) {//3.2、创建行----内容行row = sheet.createRow(i+1);User us = (User)list.get(i);//第几行第几格  第一行第一格为“code”row.createCell(0).setCellValue(us.getCode());row.createCell(1).setCellValue(us.getName());row.createCell(2).setCellValue(new SimpleDateFormat("yyyy-mm-dd").format(us.getBirth()));}//6、将文件储存到指定位置try {FileOutputStream fout = new FileOutputStream("g:\\uuu.xlsx");wb.write(fout);fout.close();} catch (IOException e) {e.printStackTrace();}}}

运行结果: