最近项目中有一个功能是根据客户的excel模板导出excel,经过同事JAY的提醒,可以用jxls包来实现。
1.包的准备,由于这次的项目只是普通的javaweb项目,所以去网上下载了2个jar包,如图:
如果是maven项目那就pom文件中加入
<dependency>
<groupId>org.jxls</groupId>
<artifactId>jxls</artifactId>
<version>2.4.7</version>
</dependency>
<dependency>
<groupId>org.jxls</groupId>
<artifactId>jxls-poi</artifactId>
<version>1.0.16</version>
</dependency>
2.下面是实现的java代码
2.1通过map塞入context生成数据
public View test(){
//获得模板文件生成一个输入流 各种获取文件仅供参考模板的定义在下面
// InputStream inputStream = ResourceUtils.getResource("classpath:framemax- config/templates/"+ fileName +".xlsx").getInputStream();
// InputStream inputStream = JxlsExporter.class.getResourceAsStream(template);
Resource resource = new ClassPathResource("template/a.xlsx");
InputStream inputStream = resource.getInputStream();
//定义一个字节类型的输出流,因为等下要把文件转成字节输出
ByteArrayOutputStream os = new ByteArrayOutputStream ();
Context context = new Context();
List<Map<String, Object>> lists = new ArrayList<Map<String, Object>>();
//通过一个map把数据输入excel
Map<String, Object> map1 = new HashMap<String, Object>();
map1.put("id", 1);
map1.put("name", "roger");
map1.put("age",24);
lists.add(map1);
Map<String, Object> map2 = new HashMap<String, Object>();
map2.put("id", 2);
map2.put("name", "jay");
map2.put("age", 23);
lists.add(map2);
//注意这个lists等一下应该对应excel模板中的lists
context.putVar("lists",lists);
JxlsHelper.getInstance().processTemplate(inputStream, os, context);
byte[] byteArray = os.toByteArray();
os.close();
inputStream.close();
View view = FileDownload.download("test.xlsx",byteArray);
return view;
}
2.2通过List塞入context生成数据
public View test(){
//获得模板文件生成一个输入流 各种获取文件仅供参考模板的定义在下面
// InputStream inputStream = ResourceUtils.getResource("classpath:framemax-config/templates/"+ fileName +".xlsx").getInputStream();
// InputStream inputStream = JxlsExporter.class.getResourceAsStream(template);
Resource resource = new ClassPathResource("template/a.xlsx");
InputStream inputStream = resource.getInputStream();
//定义一个字节类型的输出流,因为等下要把文件转成字节输出
ByteArrayOutputStream os = new ByteArrayOutputStream ();
Context context = new Context();
//通过一个List把数据输入excel
List<User> userList = new ArrayList<User>();
User user1= new User(1,"roger",24);
userList.add(user1);
User user2= new User(1,"jay",23);
userList.add(user2);
//注意这个lists等一下应该对应excel模板中的lists
context.putVar("lists",userList );
JxlsHelper.getInstance().processTemplate(inputStream, os, context);
byte[] byteArray = os.toByteArray();
os.close();
inputStream.close();
View view = FileDownload.download("test.xlsx",byteArray);
return view;
}
3.下面是我自己定义的模板
在A2中批注中插入
jx:area(lastCell="C2")
jx:each(items="lists" var="bean" lastCell="C2")
下面是输出的模板(返回的View可以在浏览器直接解析为文件)
有问题欢迎留言!!