首先需要pom文件
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15-beta2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15-beta2</version>
</dependency>
<dependency>
<groupId>net.sf.jxls</groupId>
<artifactId>jxls-core</artifactId>
<version>1.0-RC-1</version>
</dependency>
实体类
public class User implements Serializable{
private static final long serialVersionUID = -7588727575833992276L;
private String username;
private String password;
private Date birthday;
//~~
}
模板文件
-
如果想要日期格式的内容正常显示需要修改下图位置的单元格格式
代码部分
@RequestMapping("/downData.do")
public void downData(HttpServletResponse response) throws IOException, InvalidFormatException {
User user1 = new User("zhangsan", "123", new Date());
User user2 = new User("lisi", "9999", new Date());
User user3 = new User("wagnwu", "44444", new Date());
List<User> userList = new ArrayList<>();
userList.add(user1);
userList.add(user2);
userList.add(user3);
String fileName = "学生信息";
fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
response.reset();
response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
response.setContentType("application/x-download");
Resource resource = new ClassPathResource("template/a.xlsx");
InputStream is = resource.getInputStream();
Workbook workbook = getWorkBook(userList);
workbook.write(response.getOutputStream());
}
private Workbook getWorkBook(List<User> userList) throws IOException, InvalidFormatException {
Map<String, List<User>> beans = new HashMap<>();
beans.put("userList", userList);
XLSTransformer transformer = new XLSTransformer();
Resource resource = new ClassPathResource("template/a.xlsx");
InputStream is = resource.getInputStream();
return transformer.transformXLS(is, beans);
}