SSM框架系列之使用POI技术导出Excel表

 

POI框架是Apache开源的可以导出导入Excel表的,本博客介绍在SSM(Spring+SpringMVC+Mybatis)项目里,如何使用POI框架,导出Excel表

这里我们先要去Apache官网下载jar

 

然后,就可以先编程了

先提供一个封装的httpservlet请求和添加数据的类

 


  
  1. public class PageData extends HashMap implements Map{
  2. private static final long serialVersionUID = 1L;
  3. Map map = null;
  4. HttpServletRequest request;
  5. public PageData(HttpServletRequest request){
  6. this.request = request;
  7. Map properties = request.getParameterMap();
  8. Map returnMap = new HashMap();
  9. Iterator entries = properties.entrySet().iterator();
  10. Map.Entry entry;
  11. String name = "";
  12. String value = "";
  13. while (entries.hasNext()) {
  14. entry = (Map.Entry) entries.next();
  15. name = (String) entry.getKey();
  16. Object valueObj = entry.getValue();
  17. if(null == valueObj){
  18. value = "";
  19. }else if(valueObj instanceof String[]){
  20. String[] values = (String[])valueObj;
  21. for(int i=0;i<values.length;i++){
  22. value = values[i] + ",";
  23. }
  24. value = value.substring(0, value.length()-1);
  25. }else{
  26. value = valueObj.toString();
  27. }
  28. returnMap.put(name, value);
  29. }
  30. map = returnMap;
  31. }
  32. public PageData() {
  33. map = new HashMap();
  34. }
  35. @Override
  36. public Object get(Object key) {
  37. Object obj = null;
  38. if(map.get(key) instanceof Object[]) {
  39. Object[] arr = (Object[])map.get(key);
  40. obj = request == null ? arr:(request.getParameter((String)key) == null ? arr:arr[0]);
  41. } else {
  42. obj = map.get(key);
  43. }
  44. return obj;
  45. }
  46. public String getString(Object key) {
  47. return (String)get(key);
  48. }
  49. @SuppressWarnings("unchecked")
  50. @Override
  51. public Object put(Object key, Object value) {
  52. return map.put(key, value);
  53. }
  54. @Override
  55. public Object remove(Object key) {
  56. return map.remove(key);
  57. }
  58. public void clear() {
  59. map.clear();
  60. }
  61. public boolean containsKey(Object key) {
  62. // TODO Auto-generated method stub
  63. return map.containsKey(key);
  64. }
  65. public boolean containsValue(Object value) {
  66. // TODO Auto-generated method stub
  67. return map.containsValue(value);
  68. }
  69. public Set entrySet() {
  70. // TODO Auto-generated method stub
  71. return map.entrySet();
  72. }
  73. public boolean isEmpty() {
  74. // TODO Auto-generated method stub
  75. return map.isEmpty();
  76. }
  77. public Set keySet() {
  78. // TODO Auto-generated method stub
  79. return map.keySet();
  80. }
  81. @SuppressWarnings("unchecked")
  82. public void putAll(Map t) {
  83. // TODO Auto-generated method stub
  84. map.putAll(t);
  85. }
  86. public int size() {
  87. // TODO Auto-generated method stub
  88. return map.size();
  89. }
  90. public Collection values() {
  91. // TODO Auto-generated method stub
  92. return map.values();
  93. }
  94. }

 

 

 

 

 

写个实体类:

会员类

 


  
  1. public class Member {
  2. /**
  3. * 会员账号
  4. */
  5. private String memberID;
  6. /**
  7. * 会员密码
  8. */
  9. private String password;
  10. /**
  11. * 会员级别
  12. */
  13. private String rank;
  14. /**
  15. * 会员积分
  16. */
  17. private int credit;
  18. /**
  19. * 会员手机号
  20. */
  21. private String phone;
  22. /**
  23. * 会员皮肤
  24. */
  25. private String imgPath;
  26. private List<GroupPost> postes;
  27. public List<GroupPost> getPostes() {
  28. return postes;
  29. }
  30. public void setPostes(List<GroupPost> postes) {
  31. this.postes = postes;
  32. }
  33. public String getMemberID() {
  34. return memberID;
  35. }
  36. public void setMemberID(String memberID) {
  37. this.memberID = memberID;
  38. }
  39. public String getPassword() {
  40. return password;
  41. }
  42. public void setPassword(String password) {
  43. this.password = password;
  44. }
  45. public String getRank() {
  46. return rank;
  47. }
  48. public void setRank(String rank) {
  49. this.rank = rank;
  50. }
  51. public int getCredit() {
  52. return credit;
  53. }
  54. public void setCredit(int credit) {
  55. this.credit = credit;
  56. }
  57. public String getPhone() {
  58. return phone;
  59. }
  60. public void setPhone(String phone) {
  61. this.phone = phone;
  62. }
  63. public String getImgPath() {
  64. return imgPath;
  65. }
  66. public void setImgPath(String imgPath) {
  67. this.imgPath = imgPath;
  68. }
  69. }

 

 

DAO.java


  
  1. package com.appweb.core.dao;
  2. public interface DAO {
  3. /**
  4. * 保存对象
  5. * @param str
  6. * @param obj
  7. * @return
  8. * @throws Exception
  9. */
  10. public Object save(String str, Object obj) throws Exception;
  11. /**
  12. * 修改对象
  13. * @param str
  14. * @param obj
  15. * @return
  16. * @throws Exception
  17. */
  18. public Object update(String str, Object obj) throws Exception;
  19. /**
  20. * 删除对象
  21. * @param str
  22. * @param obj
  23. * @return
  24. * @throws Exception
  25. */
  26. public Object delete(String str, Object obj) throws Exception;
  27. /**
  28. * 查找对象
  29. * @param str
  30. * @param obj
  31. * @return
  32. * @throws Exception
  33. */
  34. public Object findForObject(String str, Object obj) throws Exception;
  35. /**
  36. * 查找对象
  37. * @param str
  38. * @param obj
  39. * @return
  40. * @throws Exception
  41. */
  42. public Object findForList(String str, Object obj) throws Exception;
  43. /**
  44. * 查找对象封装成Map
  45. * @param s
  46. * @param obj
  47. * @return
  48. * @throws Exception
  49. */
  50. public Object findForMap(String sql, Object obj, String key , String value) throws Exception;
  51. }

 


DAOSupport类:

 

 


  
  1. package com.appweb.core.dao;
  2. import java.util.List;
  3. import javax.annotation.Resource;
  4. import org.apache.ibatis.session.ExecutorType;
  5. import org.apache.ibatis.session.SqlSession;
  6. import org.apache.ibatis.session.SqlSessionFactory;
  7. import org.mybatis.spring.SqlSessionTemplate;
  8. import org.springframework.stereotype.Repository;
  9. @Repository("daoSupport")
  10. public class DaoSupport implements DAO {
  11. @Resource(name = "sqlSessionTemplate")
  12. private SqlSessionTemplate sqlSessionTemplate;
  13. /**
  14. * 保存对象
  15. * @param str
  16. * @param obj
  17. * @return
  18. * @throws Exception
  19. */
  20. public Object save(String str, Object obj) throws Exception {
  21. return sqlSessionTemplate.insert(str, obj);
  22. }
  23. /**
  24. * 批量更新
  25. * @param str
  26. * @param obj
  27. * @return
  28. * @throws Exception
  29. */
  30. public Object batchSave(String str, List objs )throws Exception{
  31. return sqlSessionTemplate.insert(str, objs);
  32. }
  33. /**
  34. * 修改对象
  35. * @param str
  36. * @param obj
  37. * @return
  38. * @throws Exception
  39. */
  40. public Object update(String str, Object obj) throws Exception {
  41. return sqlSessionTemplate.update(str, obj);
  42. }
  43. /**
  44. * 批量更新
  45. * @param str
  46. * @param obj
  47. * @return
  48. * @throws Exception
  49. */
  50. public void batchUpdate(String str, List objs )throws Exception{
  51. SqlSessionFactory sqlSessionFactory = sqlSessionTemplate.getSqlSessionFactory();
  52. //批量执行器
  53. SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH,false);
  54. try{
  55. if(objs!=null){
  56. for(int i=0,size=objs.size();i<size;i++){
  57. sqlSession.update(str, objs.get(i));
  58. }
  59. sqlSession.flushStatements();
  60. sqlSession.commit();
  61. sqlSession.clearCache();
  62. }
  63. }finally{
  64. sqlSession.close();
  65. }
  66. }
  67. /**
  68. * 批量更新
  69. * @param str
  70. * @param obj
  71. * @return
  72. * @throws Exception
  73. */
  74. public Object batchDelete(String str, List objs )throws Exception{
  75. return sqlSessionTemplate.delete(str, objs);
  76. }
  77. /**
  78. * 删除对象
  79. * @param str
  80. * @param obj
  81. * @return
  82. * @throws Exception
  83. */
  84. public Object delete(String str, Object obj) throws Exception {
  85. return sqlSessionTemplate.delete(str, obj);
  86. }
  87. /**
  88. * 查找对象
  89. * @param str
  90. * @param obj
  91. * @return
  92. * @throws Exception
  93. */
  94. public Object findForObject(String str, Object obj) throws Exception {
  95. return sqlSessionTemplate.selectOne(str, obj);
  96. }
  97. /**
  98. * 查找对象
  99. * @param str
  100. * @param obj
  101. * @return
  102. * @throws Exception
  103. */
  104. public Object findForList(String str, Object obj) throws Exception {
  105. return sqlSessionTemplate.selectList(str, obj);
  106. }
  107. public Object findForMap(String str, Object obj, String key, String value) throws Exception {
  108. return sqlSessionTemplate.selectMap(str, obj, key);
  109. }
  110. }

 

 

 

 

 

 

写个Service类:

 


  
  1. /**
  2. * 会员信息列表
  3. * @param pd
  4. * @return
  5. * @throws Exception
  6. */
  7. public List<PageData> listM(PageData pd)throws Exception{
  8. return (List<PageData>)dao.findForList("MemberMapper.memberList", pd);
  9. }

 

 

 

 

 

ObjectExcelView.java:

 


  
  1. package com.appweb.core.view;
  2. import java.util.Date;
  3. import java.util.List;
  4. import java.util.Map;
  5. import javax.servlet.http.HttpServletRequest;
  6. import javax.servlet.http.HttpServletResponse;
  7. import org.apache.poi.hssf.usermodel.HSSFCell;
  8. import org.apache.poi.hssf.usermodel.HSSFCellStyle;
  9. import org.apache.poi.hssf.usermodel.HSSFFont;
  10. import org.apache.poi.hssf.usermodel.HSSFSheet;
  11. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  12. import org.springframework.web.servlet.view.document.AbstractExcelView;
  13. import com.appweb.core.entity.PageData;
  14. import com.appweb.core.utils.Tools;
  15. /**
  16. * 导入到EXCEL
  17. * 类名称:ObjectExcelView.java
  18. * 类描述:
  19. */
  20. public class ObjectExcelView extends AbstractExcelView{
  21. @Override
  22. protected void buildExcelDocument(Map<String, Object> model,
  23. HSSFWorkbook workbook, HttpServletRequest request,
  24. HttpServletResponse response) throws Exception {
  25. // TODO Auto-generated method stub
  26. Date date = new Date();
  27. String filename = Tools.date2Str(date, "yyyyMMddHHmmss");
  28. HSSFSheet sheet;
  29. HSSFCell cell;
  30. response.setContentType("application/octet-stream");
  31. response.setHeader("Content-Disposition", "attachment;filename="+filename+".xls");
  32. sheet = workbook.createSheet("sheet1");
  33. List<String> titles = (List<String>) model.get("titles");
  34. int len = titles.size();
  35. HSSFCellStyle headerStyle = workbook.createCellStyle(); //标题样式
  36. headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  37. headerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  38. HSSFFont headerFont = workbook.createFont(); //标题字体
  39. headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
  40. headerFont.setFontHeightInPoints((short)11);
  41. headerStyle.setFont(headerFont);
  42. short width = 20,height=25*20;
  43. sheet.setDefaultColumnWidth(width);
  44. for(int i=0; i<len; i++){ //设置标题
  45. String title = titles.get(i);
  46. cell = getCell(sheet, 0, i);
  47. cell.setCellStyle(headerStyle);
  48. setText(cell,title);
  49. }
  50. sheet.getRow(0).setHeight(height);
  51. HSSFCellStyle contentStyle = workbook.createCellStyle(); //内容样式
  52. contentStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  53. List<PageData> varList = (List<PageData>) model.get("varList");
  54. int varCount = varList.size();
  55. for(int i=0; i<varCount; i++){
  56. PageData vpd = varList.get(i);
  57. for(int j=0;j<len;j++){
  58. String varstr = vpd.getString("var"+(j+1)) != null ? vpd.getString("var"+(j+1)) : "";
  59. cell = getCell(sheet, i+1, j);
  60. cell.setCellStyle(contentStyle);
  61. setText(cell,varstr);
  62. }
  63. }
  64. }
  65. }


控制类导出Excel表:

 

 


  
  1. /**
  2. * 导出Excel
  3. * @return
  4. * @throws Exception
  5. */
  6. @RequestMapping("/exportExcel")
  7. public ModelAndView exportExcel()throws Exception{
  8. ModelAndView mv = this.getModelAndView();
  9. PageData pd = new PageData();
  10. pd = this.getPageData();
  11. //检索条件
  12. Map<String,Object> dataMap = new HashMap<String,Object>();
  13. List<String> titles = new ArrayList<String>();
  14. titles.add("用户名");
  15. titles.add("密码");
  16. titles.add("级别");
  17. titles.add("积分");
  18. titles.add("手机号");
  19. dataMap.put("titles", titles);
  20. List<PageData> memberList = memberService.listM(pd);
  21. List<PageData> varList = new ArrayList<PageData>();
  22. for(int i=0;i<memberList.size();i++){
  23. PageData vpd = new PageData();
  24. vpd.put("var1", memberList.get(i).getString("memberID"));
  25. vpd.put("var2", memberList.get(i).getString("password"));
  26. vpd.put("var3", memberList.get(i).getString("rank"));
  27. vpd.put("var4", memberList.get(i).get("credit").toString());
  28. vpd.put("var5", memberList.get(i).getString("phone"));
  29. varList.add(vpd);
  30. }
  31. dataMap.put("varList", varList);
  32. ObjectExcelView erv = new ObjectExcelView();
  33. mv = new ModelAndView(erv,dataMap);
  34. return mv;
  35. }

 

 

 

 

 

 

文章来源: smilenicky.blog.csdn.net,作者:smileNicky,版权归原作者所有,如需转载,请联系作者。

原文链接:smilenicky.blog.csdn.net/article/details/52526551

(完)