springmvc poi 导出word 复选框 怎么用
Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。
这里的方法支持导出excel至项目所在服务器,或导出至客户端浏览器供用户下载,下面我把两个实例都放出来。
1下载所需POI的jar包,并导入项目。
2添加一个User类,用于存放用户实体,类中内容如下:
1 package commvcpo;
2
3 public class User {
4 private int id;
5 private String name;
6 private String password;
7 private int age;
8
9 public User() {
10
11 }
12
13 public User(int id, String name, String password, int age) {
14 thisid = id;
15 thisname = name;
16 thispassword = password;
17 thisage = age;
18 }
19 public int getId() {
20 return id;
21 }
22 public void setId(int id) {
23 thisid = id;
24 }
25 public String getName() {
26 return name;
27 }
28 public void setName(String name) {
29 thisname = name;
30 }
31 public String getPassword() {
32 return password;
33 }
34 public void setPassword(String password) {
35 thispassword = password;
36 }
37 public int getAge() {
38 return age;
39 }
40 public void setAge(int age) {
41 thisage = age;
42 }
43 }
3添加一个UserController类,类中内容如下:
1 package commvccontroller;
2
3 import javatextSimpleDateFormat;
4 import javautilDate;
5
6 import javaxservletServletOutputStream;
7 import javaxservlethttpHttpServletResponse;
8
9 import orgspringframeworkstereotypeController;
10 import orgspringframeworkbeansfactoryannotationAutowired;
11 import orgspringframeworkwebbindannotationRequestMapping;
12 import orgspringframeworkwebbindannotationResponseBody;
13
14 import commvcpoUser;
15 import commvcserviceUserService;
16
17 @Controller
18 public class UserController {
19
20 @Autowired
21 private UserService userService;
22
23 @RequestMapping("/exportdo")
24 public @ResponseBody String export(HttpServletResponse response){
25 responsesetContentType("application/binary;charset=UTF-8");
26 try{
27 ServletOutputStream out=responsegetOutputStream();
28 String fileName=new String(("UserInfo "+ new SimpleDateFormat("yyyy-MM-dd")format(new Date()))getBytes(),"UTF-8");
29 responsesetHeader("Content-disposition", "attachment; filename=" + fileName + "xls");
30 String[] titles = { "用户编号", "用户姓名", "用户密码", "用户年龄" };
31 userServiceexport(titles, out);
32 return "success";
33 } catch(Exception e){
34 eprintStackTrace();
35 return "导出信息失败";
36 }
37 }
38 }
4添加一个接口类UserService和实现类UserServiceImpl,类中内容如下:
1 package commvcservice;
2
3 import javaxservletServletOutputStream;
4 import commvcpoUser;
5
6 public interface UserService {
7 public void export(String[] titles, ServletOutputStream out);
8 }
1 package commvcserviceimpl;
2
3 import javatextSimpleDateFormat;
4 import javautilList;
5
6 import javaxservletServletOutputStream;
7
8 import commvcdaoUserDAO;
9 import commvcpoUser;
10 import commvcserviceUserService;
11
12 import orgapachepoihssfusermodelHSSFCell;
13 import orgapachepoihssfusermodelHSSFCellStyle;
14 import orgapachepoihssfusermodelHSSFRow;
15 import orgapachepoihssfusermodelHSSFSheet;
16 import orgapachepoihssfusermodelHSSFWorkbook;
17 import orgspringframeworkbeansfactoryannotationAutowired;
18 import orgspringframeworkstereotypeService;
19
20 @Service
21 public class UserServiceImpl implements UserService {
22
23 @Autowired
24 private UserDAO userDAO;
25
26 @Override
27 public void export(String[] titles, ServletOutputStream out) {
28 try{
29 // 第一步,创建一个workbook,对应一个Excel文件
30 HSSFWorkbook workbook = new HSSFWorkbook();
31 // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
32 HSSFSheet hssfSheet = workbookcreateSheet("sheet1");
33 // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
34 HSSFRow hssfRow = hssfSheetcreateRow(0);
35 // 第四步,创建单元格,并设置值表头 设置表头居中
36 HSSFCellStyle hssfCellStyle = workbookcreateCellStyle();
37 //居中样式
38 hssfCellStylesetAlignment(HSSFCellStyleALIGN_CENTER);
39
40 HSSFCell hssfCell = null;
41 for (int i = 0; i < titleslength; i++) {
42 hssfCell = hssfRowcreateCell(i);//列索引从0开始
43 hssfCellsetCellValue(titles[i]);//列名1
44 hssfCellsetCellStyle(hssfCellStyle);//列居中显示
45 }
46
47 // 第五步,写入实体数据
48 List users = userDAOquery();
49
50 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
51 if(users != null && !usersisEmpty()){
52 for (int i = 0; i < userssize(); i++) {
53 hssfRow = hssfSheetcreateRow(i+1);
54 User user = usersget(i);
55
56 // 第六步,创建单元格,并设置值
57 int userid = 0;
58 if(usergetId() != 0){
59 userid = usergetId();
60 }
61 hssfRowcreateCell(0)setCellValue(userid);
62 String username = "";
63 if(usergetName() != null){
64 username = usergetName();
65 }
66 hssfRowcreateCell(1)setCellValue(username);
67 String password = "";
68 if(usergetPassword() != null){
69 password = usergetPassword();
70 }
71 hssfRowcreateCell(2)setCellValue(password);
72 int age = 0;
73 if(usergetAge() != 0){
74 age = usergetAge();
75 }
76 hssfRowcreateCell(3)setCellValue(age);
77 }
78 }
79
80 // 第七步,将文件输出到客户端浏览器
81 try {
82 workbookwrite(out);
83 outflush();
84 outclose();
85
86 } catch (Exception e) {
87 eprintStackTrace();
88 }
89 }catch(Exception e){
90 eprintStackTrace();
91 throw new Exception("导出信息失败!");
92 }
93 }
94 }
5添加一个接口类UserDAO和实现类UserDAOImpl,类中内容如下:
1 package commvcdao;
2
3 import javautilList;
4 import commvcpoUser;
5
6 public interface UserDAO {
7 List query();
8 }
1 package commvcdaoimpl;
2
3 import javautilList;
4 import javasqlResultSet;
5 import javasqlSQLException;
6
7 import commvcdaoUserDAO;
8 import commvcpoUser;
9
10 import orgspringframeworkstereotypeRepository;
11 import orgspringframeworkbeansfactoryannotationAutowired;
12 import orgspringframeworkjdbccoreJdbcTemplate;
13 import orgspringframeworkjdbccoreRowMapper;
14
15 @Repository
16 public class UserDAOImpl implements UserDAO {
17
18 @Autowired
19 private JdbcTemplate jdbcTemplate;
20
21 public List query() {
22 return thisjdbcTemplatequery("select from student",
23 new RowMapper() {
24 public User mapRow(ResultSet rs, int arg1)
25 throws SQLException {
26 return new User(rsgetInt("sId"),
27 rsgetString("sName"), rsgetString("sPwd"), rs
28 getInt("sAge"));
29 }
30 });
31 }
32 }
这样就完成了excel导出至客户端浏览器,当然有时候也会用到导出excel至服务器上。只需要对本文步骤4中的第七步文件输出方式进行修改,如下:
1 // 第七步,将文件存到指定位置
2 try {
3 FileOutputStream fileOutputStream = new FileOutputStream("C:/userxls");//指定路径与名字和格式
4 workbookwrite(fileOutputStream);//讲数据写出去
5 fileOutputStreamclose();//关闭输出流
6 } catch (Exception e) {
7 eprintStackTrace();
8 }
然后去除controller类中的out参数设置就ok了。也可以看出其实两种方式只是最终保存方式不同,其他步骤是共通的。
public static void main(String[] args) throws IOException {
File file = new File("d:/testxls");
InputStream is = new FileInputStream(file);
Workbook wb = new HSSFWorkbook(is);
{
Systemoutprintln("读取成功");
return;
}
}
刚才写了个测试程序试了一下,也是2003格式的,里边只有一个下拉框
测试结果:无论点不点或者修改下拉框值,一切正常,workbook对象都能创建成功。
你看看是不是你导入的excel里存在 宏之类的 东西。
a标签点击请求后,在服务端根据excel对应的数据 利用poi生成一个workbook对象,
然后
OutputStream os = null;
responsesetContentType("application/vndopenxmlformats-officedocumentspreadsheetmlworksheet");
responsesetHeader("Content-Disposition","attachment;filename=" + URLEncoderencode("供应商信息"+new Date()toString(), "UTF-8") + "xslx"); //以下载形式,如果是直接在线打开
// responsesetHeader("Content-Disposition","inline;filename="
//中文文件名请适当转码,后缀名根据创建workbook时的版本决定(2003-HSSFWorkbook-xls;2007-XSSFWorkbook-xlsx)
os = responsegetOutputStream();
workbookwrite(os);
responseflushBuffer();
(io流的关闭和io异常扑捉自行处理,poi生成excel的过程参照poi文档,无非就是sheet,row,cell的操作)
0条评论