当前位置:   article > 正文

spring boot导出数据到Excel表格_"@excel(name = \"customer_phone\")"

"@excel(name = \"customer_phone\")"

所需依赖:

  1. <!-- Excel导入 -->
  2. <dependency>
  3. <groupId>org.apache.poi</groupId>
  4. <artifactId>poi</artifactId>
  5. <version>3.6</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.apache.poi</groupId>
  9. <artifactId>poi-ooxml</artifactId>
  10. <version>3.6</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>org.jetbrains</groupId>
  14. <artifactId>annotations</artifactId>
  15. <version>RELEASE</version>
  16. <scope>compile</scope>
  17. </dependency>

实体类:CustomerInfo

  1. package com.nz.entity;
  2. import java.util.Date;
  3. /**
  4. * @Author xxs
  5. * @Date 2020/4/16 17:29
  6. */
  7. public class CustomerInfo {
  8. private Integer id;
  9. private String customerName;
  10. private String customerPhone;
  11. private String text;
  12. private String type;
  13. private Date addTime;
  14. public Integer getId() {
  15. return id;
  16. }
  17. public void setId(Integer id) {
  18. this.id = id;
  19. }
  20. public String getCustomerName() {
  21. return customerName;
  22. }
  23. public void setCustomerName(String customerName) {
  24. this.customerName = customerName;
  25. }
  26. public String getCustomerPhone() {
  27. return customerPhone;
  28. }
  29. public void setCustomerPhone(String customerPhone) {
  30. this.customerPhone = customerPhone;
  31. }
  32. public String getText() {
  33. return text;
  34. }
  35. public void setText(String text) {
  36. this.text = text;
  37. }
  38. public String getType() {
  39. return type;
  40. }
  41. public void setType(String type) {
  42. this.type = type;
  43. }
  44. public Date getAddTime() {
  45. return addTime;
  46. }
  47. public void setAddTime(Date addTime) {
  48. this.addTime = addTime;
  49. }
  50. }
导出表格所要显示的信息实体:downloadProfitStatementExcel
  1. package com.nz.entity;
  2. import java.text.SimpleDateFormat;
  3. import java.util.Date;
  4. /**
  5. * @Author xxs
  6. * @Date 2020/4/17 14:58
  7. */
  8. public class downloadProfitStatementExcel {
  9. private String customerName;
  10. private String customerPhone;
  11. private String text;
  12. private String addTime;
  13. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  14. public downloadProfitStatementExcel(String customerName, String customerPhone,
  15. String text,String addTime) {
  16. super();
  17. this.customerName = customerName;
  18. this.customerPhone = customerPhone;
  19. this.text = text;
  20. this.addTime = addTime;
  21. }
  22. public static downloadProfitStatementExcel getInit() {
  23. return new downloadProfitStatementExcel("用户名", "手机号", "信息","提交时间");
  24. }
  25. public downloadProfitStatementExcel() {
  26. super();
  27. }
  28. public String getCustomerName() {
  29. return customerName;
  30. }
  31. public void setCustomerName(String customerName) {
  32. this.customerName = customerName;
  33. }
  34. public String getCustomerPhone() {
  35. return customerPhone;
  36. }
  37. public void setCustomerPhone(String customerPhone) {
  38. this.customerPhone = customerPhone;
  39. }
  40. public String getText() {
  41. return text;
  42. }
  43. public void setText(String text) {
  44. this.text = text;
  45. }
  46. public String getAddTime() {
  47. return addTime;
  48. }
  49. public void setAddTime(Date addTime) {
  50. this.addTime = sdf.format(addTime);
  51. }
  52. }
CustomerInfoService接口:
  1. package com.nz.service;
  2. import com.nz.entity.CustomerInfo;
  3. import java.util.List;
  4. /**
  5. * @Author xxs
  6. * @Date 2020/4/17 10:36
  7. */
  8. public interface CustomerInfoService {
  9. public List<CustomerInfo> selectAll();
  10. public List<CustomerInfo> selectAllByType(String type);
  11. int insert(CustomerInfo customerInfo);
  12. }
CustomerInfoServiceImpl实现类:
  1. package com.nz.service.Impl;
  2. import com.nz.dao.CustomerInfoDao;
  3. import com.nz.entity.CustomerInfo;
  4. import com.nz.service.CustomerInfoService;
  5. import org.springframework.stereotype.Service;
  6. import javax.annotation.Resource;
  7. import java.util.List;
  8. /**
  9. * @Author xxs
  10. * @Date 2020/4/17 10:39
  11. */
  12. @Service
  13. public class CustomerInfoServiceImpl implements CustomerInfoService {
  14. @Resource
  15. private CustomerInfoDao customerInfoDao;
  16. @Override
  17. public List<CustomerInfo> selectAll() {
  18. return customerInfoDao.selectAll();
  19. }
  20. @Override
  21. public List<CustomerInfo> selectAllByType(String type) {
  22. return customerInfoDao.selectAllByType(type);
  23. }
  24. @Override
  25. public int insert(CustomerInfo customerInfo) {
  26. return customerInfoDao.insert(customerInfo);
  27. }
  28. }
CustomerInfoDao接口:
  1. package com.nz.dao;
  2. import com.nz.entity.CustomerInfo;
  3. import org.apache.ibatis.annotations.*;
  4. import java.util.List;
  5. /**
  6. * @Author xxs
  7. * @Date 2020/4/17 10:40
  8. */
  9. public interface CustomerInfoDao {
  10. @Select("select * from customer_info")
  11. @Results(id="resultMap", value={
  12. @Result(column="id", property="id", id=true),
  13. @Result(column="customer_name", property="customerName"),
  14. @Result(column="customer_phone", property="customerPhone"),
  15. @Result(column="text", property="text"),
  16. @Result(column="type", property="type"),
  17. @Result(column="addtime", property="addTime")
  18. })
  19. public List<CustomerInfo> selectAll();
  20. @Select("select * from customer_info where type =#{type}")
  21. @ResultMap(value={"resultMap"})
  22. public List<CustomerInfo> selectAllByType(String type);
  23. @Insert("insert INTO customer_info (customer_name,customer_phone,text,type,addtime) values(#{customerName},#{customerPhone},#{text},#{type},#{addTime})")
  24. int insert(CustomerInfo customerInfo);
  25. }

controller层导出方法:

  1. package com.nz.controller;
  2. import com.nz.entity.CustomerInfo;
  3. import com.nz.entity.downloadProfitStatementExcel;
  4. import com.nz.response.ResponseMess;
  5. import com.nz.service.CustomerInfoService;
  6. import com.nz.util.ExcelUtil;
  7. import org.springframework.beans.BeanUtils;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.ResponseBody;
  10. import org.springframework.web.bind.annotation.RestController;
  11. import javax.annotation.Resource;
  12. import javax.servlet.http.HttpServletResponse;
  13. import java.io.IOException;
  14. import java.util.ArrayList;
  15. import java.util.Date;
  16. import java.util.List;
  17. /**
  18. * @Author xxs
  19. * @Date 2020/4/17 12:36
  20. */
  21. @RestController
  22. @ResponseBody
  23. @RequestMapping("/customerInfo")
  24. public class CustomerInfoController {
  25. @Resource
  26. private CustomerInfoService customerInfoService;
  27. /**
  28. * 导出信息表excel
  29. * @param type 0-,1-
  30. * @param response
  31. * @returns
  32. */
  33. @RequestMapping("/downloadCustomerInfo")
  34. @ResponseBody
  35. public ResponseMess downloadQueryProfitStatementEXCEL(String type, HttpServletResponse response) {
  36. if(type.equals("")||type==null) {
  37. return new ResponseMess("请求参数异常");
  38. }
  39. List<CustomerInfo> qs = customerInfoService.selectAllByType(type);
  40. List<downloadProfitStatementExcel> list = new ArrayList<>(qs.size()+1);
  41. list.add(downloadProfitStatementExcel.getInit());
  42. for(CustomerInfo q:qs) {
  43. downloadProfitStatementExcel d = new downloadProfitStatementExcel();
  44. try {
  45. BeanUtils.copyProperties(q, d);
  46. } catch (Exception e) {
  47. e.printStackTrace();
  48. }
  49. list.add(d);
  50. }
  51. ExcelUtil e = new ExcelUtil();
  52. //设置文件输出类型
  53. response.setHeader("Content-disposition", "attachment; filename="
  54. + new Date().getTime() + ".xls");
  55. String s = "";
  56. if(type.equals("0")){
  57. s = "1类型提交资料";
  58. }else{
  59. s = "2类型提交资料";
  60. }
  61. String[] strs = new String[] {s};
  62. try {
  63. e.exportDataToExcel(list, strs, s, response.getOutputStream());
  64. } catch (IOException e1) {
  65. e1.printStackTrace();
  66. return new ResponseMess("失败");
  67. }
  68. return new ResponseMess(1,"成功");
  69. }
  70. }

ExcelUtil 表格工具类:

  1. package com.nz.util;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.io.OutputStream;
  5. import java.lang.reflect.Field;
  6. import java.lang.reflect.Method;
  7. import java.util.ArrayList;
  8. import java.util.List;
  9. import javax.servlet.http.HttpServletRequest;
  10. import org.apache.poi.hssf.usermodel.HSSFCell;
  11. import org.apache.poi.hssf.usermodel.HSSFCellStyle;
  12. import org.apache.poi.hssf.usermodel.HSSFFont;
  13. import org.apache.poi.hssf.usermodel.HSSFRichTextString;
  14. import org.apache.poi.hssf.usermodel.HSSFRow;
  15. import org.apache.poi.hssf.usermodel.HSSFSheet;
  16. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  17. import org.apache.poi.hssf.util.HSSFColor;
  18. import org.apache.poi.ss.usermodel.Cell;
  19. import org.apache.poi.ss.usermodel.Row;
  20. import org.apache.poi.ss.usermodel.Sheet;
  21. import org.apache.poi.ss.usermodel.Workbook;
  22. import org.apache.poi.ss.util.CellRangeAddress;
  23. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  24. /**
  25. * @ClassName: ExcelUtil
  26. * @Description: Excel导入导出工具类
  27. */
  28. public class ExcelUtil {
  29. /**
  30. * @Title: createWorkbook
  31. * @Description: 判断excel文件后缀名,生成不同的workbook
  32. * @param @param is
  33. * @param @param excelFileName
  34. * @param @return
  35. * @param @throws IOException
  36. * @return Workbook
  37. * @throws
  38. */
  39. public Workbook createWorkbook(InputStream is,String excelFileName) throws IOException{
  40. if (excelFileName.endsWith(".xls")) {
  41. return new HSSFWorkbook(is);
  42. }else if (excelFileName.endsWith(".xlsx")) {
  43. return new XSSFWorkbook(is);
  44. }
  45. return null;
  46. }
  47. /**
  48. * @Title: getSheet
  49. * @Description: 根据sheet索引号获取对应的sheet
  50. * @param @param workbook
  51. * @param @param sheetIndex
  52. * @param @return
  53. * @return Sheet
  54. * @throws
  55. */
  56. public Sheet getSheet(Workbook workbook,int sheetIndex){
  57. return workbook.getSheetAt(0);
  58. }
  59. /**
  60. * @Title: isHasValues
  61. * @Description: 判断一个对象所有属性是否有值,如果一个属性有值(分空),则返回true
  62. * @param @param object
  63. * @param @return
  64. * @return boolean
  65. * @throws
  66. */
  67. public boolean isHasValues(Object object){
  68. Field[] fields = object.getClass().getDeclaredFields();
  69. boolean flag = false;
  70. for (int i = 0; i < fields.length; i++) {
  71. String fieldName = fields[i].getName();
  72. String methodName = "get"+fieldName.substring(0, 1).toUpperCase()+fieldName.substring(1);
  73. Method getMethod;
  74. try {
  75. getMethod = object.getClass().getMethod(methodName);
  76. Object obj = getMethod.invoke(object);
  77. if (null != obj || !"".equals(obj)) {
  78. flag = true;
  79. break;
  80. }
  81. } catch (Exception e) {
  82. }
  83. }
  84. return flag;
  85. }
  86. public <T> void exportDataToExcel(List<T> list,String[] headers,String title,OutputStream os){
  87. HSSFWorkbook workbook = new HSSFWorkbook();
  88. //生成一个表格
  89. HSSFSheet sheet = workbook.createSheet(title);
  90. //设置表格默认列宽15个字节
  91. sheet.setDefaultColumnWidth(15);
  92. //生成一个样式
  93. HSSFCellStyle style = this.getCellStyle(workbook);
  94. //生成一个字体
  95. HSSFFont font = this.getFont(workbook);
  96. //把字体应用到当前样式
  97. style.setFont(font);
  98. //生成表格标题
  99. HSSFRow row = sheet.createRow(0);
  100. row.setHeight((short)300);
  101. HSSFCell cell = null;
  102. for (int i = 0; i < headers.length; i++) {
  103. cell = row.createCell(i);
  104. cell.setCellStyle(style);
  105. HSSFRichTextString text = new HSSFRichTextString(headers[i]);
  106. cell.setCellValue(text);
  107. }
  108. // 合并日期占两行(4个参数,分别为起始行,结束行,起始列,结束列)
  109. CellRangeAddress region = new CellRangeAddress(0, 0, 0, 4);
  110. sheet.addMergedRegion(region);
  111. //将数据放入sheet中
  112. for (int i = 0; i < list.size(); i++) {
  113. HSSFRow r2 = sheet.createRow(i+1);
  114. T t = list.get(i);
  115. //利用反射,根据JavaBean属性的先后顺序,动态调用get方法得到属性的值
  116. Field[] fields = t.getClass().getDeclaredFields();
  117. try {
  118. for (int j = 0; j < fields.length; j++) {
  119. HSSFCell c2 = r2.createCell(j);
  120. Field field = fields[j];
  121. String fieldName = field.getName();
  122. String methodName = "get"+fieldName.substring(0, 1).toUpperCase()+fieldName.substring(1);
  123. Method getMethod = t.getClass().getMethod(methodName,new Class[]{});
  124. Object value = getMethod.invoke(t, new Object[]{});
  125. if(null == value)
  126. value ="";
  127. c2.setCellValue(value.toString());
  128. }
  129. } catch (Exception e) {
  130. }
  131. }
  132. try {
  133. workbook.write(os);
  134. } catch (Exception e) {
  135. }finally{
  136. try {
  137. os.flush();
  138. os.close();
  139. } catch (IOException e) {
  140. }
  141. }
  142. }
  143. /**
  144. * @Title: getCellStyle
  145. * @Description: 获取单元格格式
  146. * @param @param workbook
  147. * @param @return
  148. * @return HSSFCellStyle
  149. * @throws
  150. */
  151. public HSSFCellStyle getCellStyle(HSSFWorkbook workbook){
  152. HSSFCellStyle style = workbook.createCellStyle();
  153. style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
  154. style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
  155. style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  156. style.setBorderTop(HSSFCellStyle.BORDER_THIN);
  157. style.setLeftBorderColor(HSSFCellStyle.BORDER_THIN);
  158. style.setRightBorderColor(HSSFCellStyle.BORDER_THIN);
  159. style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  160. return style;
  161. }
  162. /**
  163. * @Title: getFont
  164. * @Description: 生成字体样式
  165. * @param @param workbook
  166. * @param @return
  167. * @return HSSFFont
  168. * @throws
  169. */
  170. public HSSFFont getFont(HSSFWorkbook workbook){
  171. HSSFFont font = workbook.createFont();
  172. font.setColor(HSSFColor.WHITE.index);
  173. font.setFontHeightInPoints((short)12);
  174. font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
  175. return font;
  176. }
  177. public boolean isIE(HttpServletRequest request){
  178. return request.getHeader("USER-AGENT").toLowerCase().indexOf("msie")>0?true:false;
  179. }
  180. }

看一下数据库我们需要导出的数据:

那么我们调导出方法测试一下:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/536776
推荐阅读
相关标签
  

闽ICP备14008679号