1、首先导入maven依赖

  1. <!-- POI核心依赖 -->
  2. <dependency>
  3. <groupId>org.apache.poi</groupId>
  4. <artifactId>poi</artifactId>
  5. <version>3.8</version>
  6. </dependency>
  7. <!-- 为POI支持Office Open XML -->
  8. <dependency>
  9. <groupId>org.apache.poi</groupId>
  10. <artifactId>poi-ooxml</artifactId>
  11. <version>3.8</version>
  12. </dependency>

2、MicroUtil.java工具类

  1. package com.yinz.tool.j2ee;
  2.  
  3. import java.io.FileInputStream;
  4. import java.io.InputStream;
  5. import java.io.OutputStream;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8. import java.util.Map;
  9. import java.util.Set;
  10.  
  11. import javax.servlet.http.HttpServletResponse;
  12.  
  13. import org.apache.poi.hssf.usermodel.HSSFCell;
  14. import org.apache.poi.hssf.usermodel.HSSFCellStyle;
  15. import org.apache.poi.hssf.usermodel.HSSFDataFormat;
  16. import org.apache.poi.hssf.usermodel.HSSFRow;
  17. import org.apache.poi.hssf.usermodel.HSSFSheet;
  18. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  19. import org.apache.poi.ss.usermodel.Cell;
  20. import org.apache.poi.ss.usermodel.Row;
  21. import org.apache.poi.ss.usermodel.Sheet;
  22. import org.apache.poi.ss.usermodel.Workbook;
  23. import org.apache.poi.ss.util.WorkbookUtil;
  24. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  25.  
  26. import com.yinz.tool.ReflectUtil;
  27.  
  28. /**
  29. *
  30. * @description: 执行Microsoft文件 相关操作《导出/导入excel表格等》
  31. * 需要用到POI相关jar包
  32. * @author yinz
  33. * 2016-11-9
  34. */
  35. public class MicroUtil {
  36.  
  37. public static void main(String[] args) throws Exception {
  38. String excelPath = "C:\\Users\\yinz\\Desktop\\场景2\\场景2-样例数据_拜访记录.xls";
  39. Map<Integer, String> indexMapAtt = new HashMap<Integer, String>();
  40. indexMapAtt.put(0, "mbActivityInfoId");
  41. indexMapAtt.put(1, "activity");
  42. indexMapAtt.put(2, "activityName");
  43. indexMapAtt.put(3, "sendDate");
  44. indexMapAtt.put(4, "state");
  45. indexMapAtt.put(5, "isDelete");
  46. indexMapAtt.put(6, "customerId");
  47. indexMapAtt.put(7, "customerGender");
  48. indexMapAtt.put(8, "customerBirthDay");
  49. indexMapAtt.put(9, "empNo");
  50. indexMapAtt.put(10, "noteType");
  51. indexMapAtt.put(11, "contactDate");
  52. indexMapAtt.put(12, "remark");
  53. List<ContactRecord> result = readExcel(excelPath, null, 1, indexMapAtt, ContactRecord.class);
  54. System.out.println(result);
  55. }
  56.  
  57. /**
  58. * 导出excel表格到输出流<可用于web界面导出excel表格>
  59. * @param response : 输出流
  60. * @param result : 需要导出的数据java对象列表
  61. * @param name : 文件名
  62. * @param excelHead : 表格列名
  63. * @param params : 列对应的对象属性名
  64. * @param isAddIndex : 是否增加序列号
  65. */
  66. public static void exportExcel(HttpServletResponse response, List<?> result, String name, String[] excelHead, Object[] params, boolean isAddIndex) {
  67. //创建excel表格
  68. HSSFWorkbook wb = new HSSFWorkbook();
  69. //长度不能超过31个字符,并且不能包含部分特殊字符,使用如下方法,可将特殊字符替换为空格,长度超过31的进行
  70. name = WorkbookUtil.createSafeSheetName(name);
  71. HSSFSheet sheet = wb.createSheet(name);
  72. String[] head = null;
  73. //如果增加序号,第一列设为序号,重新生成head数组
  74. if (isAddIndex)
  75. {
  76. head = new String[excelHead.length + 1];
  77. head[0] = "序列号";
  78. for (int i = 0; i < excelHead.length; i++)
  79. {
  80. head[i+1] = excelHead[i];
  81. }
  82. }
  83. else
  84. {
  85. head = excelHead;
  86. }
  87. for(int i=0;i<head.length;i++){
  88. sheet.setColumnWidth(i, 6000);
  89. }
  90. //Rows are 0 based.
  91. HSSFRow row = sheet.createRow((int) 0);
  92. HSSFCellStyle style = wb.createCellStyle();
  93. HSSFCellStyle style2 = wb.createCellStyle();
  94. style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
  95. HSSFDataFormat format = wb.createDataFormat();
  96. style2.setDataFormat(format.getFormat("@"));
  97.  
  98. for(int i=0;i<head.length;i++){
  99. HSSFCell cell = row.createCell((short) i);
  100. cell.setCellValue(head[i]);
  101. cell.setCellStyle(style);
  102. cell.setCellType(HSSFCell.CELL_TYPE_STRING);
  103. sheet.setDefaultColumnStyle(i, style2);
  104. }
  105. int count = 1;
  106. if (result != null)
  107. {
  108. for (Object obj : result){
  109.  
  110. int i = 0;
  111. row = sheet.createRow(count);
  112. //先增加序号
  113. if (isAddIndex)
  114. {
  115. row.createCell((short) 0).setCellValue(count);
  116. i++;
  117. }
  118. for (Object attrName:params)
  119. {
  120. HSSFCell cell = row.createCell((short) i);
  121. cell.setCellStyle(style2);
  122. Object value = ReflectUtil.getObjAttributeValue(obj, (String)attrName);
  123. cell.setCellValue(value == null ? "" : value.toString());
  124. cell.setCellType(HSSFCell.CELL_TYPE_STRING);
  125. i++;
  126. }
  127. count++;
  128. }
  129. }
  130. try
  131. {
  132. String filename = name+".xls";//设置文件名
  133. response.reset();
  134. response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(filename, "UTF-8"));
  135. response.setContentType("application/vnd.ms-excel");
  136. OutputStream fout = response.getOutputStream();
  137. //将excel写到输出流
  138. wb.write(fout);
  139. fout.flush();
  140. fout.close();
  141. response.getOutputStream().flush();
  142. response.getOutputStream().close();
  143.  
  144. }
  145. catch (Exception e)
  146. {
  147. e.printStackTrace();
  148. }
  149. }
  150.  
  151. //读取excel表格数据
  152.  
  153. /**
  154. * 读取excel表格内容到java对象
  155. * @param inStream excel文件输入流
  156. * @param sheetPage 要读取的sheet页(0 based),若为null,则读取第1页
  157. * @param startRow 从第几行开始读取
  158. * @param indexMapAtt excel表单cell与java对象对应关系
  159. * @param clazz 要生成的java类型
  160. * @return
  161. * @throws Exception
  162. */
  163. public static <T> List<T> readExcel(InputStream inStream, Integer[] sheetPage, Integer startRow, Map<Integer, String> indexMapAtt, Class<T> clazz) throws Exception {
  164. startRow = startRow == null ? 0 : startRow;
  165. List<T> result = new ArrayList<T>();
  166. Workbook wb = new HSSFWorkbook(inStream);;
  167. Sheet sheet = null;
  168. if(sheetPage == null || sheetPage.length <= 0) {
  169. sheet = wb.getSheetAt(0);
  170. readSheet(sheet, result, startRow, indexMapAtt, clazz);
  171. } else {
  172. for(Integer sheetIndex : sheetPage) {
  173. sheet = wb.getSheetAt(sheetIndex);
  174. readSheet(sheet, result, startRow, indexMapAtt, clazz);
  175. }
  176. }
  177.  
  178. return result;
  179. }
  180.  
  181. /**
  182. *
  183. * @param excelPath excel表格路径
  184. * @param sheetPage 要读取的excel中的sheet所有 、0开始
  185. * @param startRow 开始读取的数据的行标 ,0开始
  186. * @param indexMapAtt 列索引与对象属性对应map
  187. * @param clazz 每行记录所对应的java对象
  188. * @return
  189. * @throws Exception
  190. */
  191. @SuppressWarnings("resource")
  192. public static <T> List<T> readExcel(String excelPath, Integer[] sheetPage, Integer startRow, Map<Integer, String> indexMapAtt, Class<T> clazz) throws Exception {
  193. startRow = startRow == null ? 0 : startRow;
  194. List<T> result = new ArrayList<T>();
  195. InputStream inStream = new FileInputStream(excelPath);
  196. Workbook wb = null;
  197. if(excelPath.matches("^.+\\.(?i)(xls)$")) {
  198. //excel2003
  199. wb = new HSSFWorkbook(inStream);
  200. } else if(excelPath.matches("^.+\\.(?i)(xlsx)$")) {
  201. //excel2007
  202. wb = new XSSFWorkbook(inStream);
  203. } else {
  204. return null;
  205. }
  206. Sheet sheet = null;
  207. if(sheetPage == null || sheetPage.length <= 0) {
  208. sheet = wb.getSheetAt(0);
  209. readSheet(sheet, result, startRow, indexMapAtt, clazz);
  210. } else {
  211. for(Integer sheetIndex : sheetPage) {
  212. sheet = wb.getSheetAt(sheetIndex);
  213. readSheet(sheet, result, startRow, indexMapAtt, clazz);
  214. }
  215. }
  216.  
  217. return result;
  218. }
  219.  
  220. //读取excel中的sheet数据、并为java对象集合赋值
  221. private static <T> void readSheet(Sheet sheet, List<T> result, Integer startRow, Map<Integer, String> indexMapAtt, Class<T> resultType) throws Exception {
  222. //获取总行数
  223. int totalRows = sheet.getPhysicalNumberOfRows();
  224.  
  225. T t;
  226. for(int i = startRow; i < totalRows; i++) {
  227. Row row = sheet.getRow(i);
  228. if(row == null) {
  229. continue;
  230. }
  231.  
  232. t = resultType.newInstance();
  233. Set<Integer> cellIndexSet = indexMapAtt.keySet();
  234. for(Integer index : cellIndexSet) {
  235. Cell cell = row.getCell(index);
  236. if(cell == null) {
  237. continue;
  238. }
  239. cell.setCellType(HSSFCell.CELL_TYPE_STRING);
  240. ReflectUtil.setObjAttributeValue(t, indexMapAtt.get(index), cell.getStringCellValue() == null ? "" : cell.getStringCellValue());
  241. }
  242. result.add(t);
  243. }
  244. }
  245. }

反射工具类:ReflectUtil.java

  1. package com.yinz.tool;
  2.  
  3. import java.lang.reflect.Field;
  4. import java.util.HashMap;
  5. import java.util.Map;
  6.  
  7. /**
  8. *
  9. * @description: 反射工具类
  10. * @author yinz
  11. * 2016-11-9
  12. */
  13. public class ReflectUtil {
  14.  
  15. /**
  16. * 将对象属性和值以map存储,默认包含属性值为null的属性
  17. * @param obj
  18. * @return
  19. */
  20. public static Map<String, Object> obj2map(Object obj) {
  21. return obj2map(obj, true);
  22. }
  23.  
  24. /**
  25. * 将对象属性和值以map存储
  26. * @param obj
  27. * @param isContainNullValue : 是否包含属性中为空的属性
  28. * @return
  29. */
  30. public static Map<String, Object> obj2map(Object obj, boolean isContainNullValue) {
  31. Map<String, Object> map = new HashMap<String, Object>();
  32.  
  33. Field[] fList = obj.getClass().getDeclaredFields();
  34. try {
  35. for(Field f : fList) {
  36. f.setAccessible(true);
  37. if(isContainNullValue) {
  38. map.put(f.getName(), f.get(obj));
  39. } else {
  40. if(f.get(obj) != null && f.get(obj) != "") {
  41. map.put(f.getName(), f.get(obj));
  42. }
  43. }
  44. }
  45. } catch (Exception e) {
  46. return null;
  47. }
  48. return map;
  49. }
  50.  
  51. /**
  52. * 获取对象指定属性值
  53. * @param obj
  54. * @param attName
  55. * @return
  56. */
  57. public static Object getObjAttributeValue(Object obj, String attName) {
  58. return getObjAttributeValue(obj, attName, "");
  59. }
  60.  
  61. /**
  62. * 获取对象指定属性的值
  63. * @param obj : 查询对象
  64. * @param attName : 要获取的属性名
  65. * @param defVal : 默认值
  66. * @return
  67. */
  68. public static Object getObjAttributeValue(Object obj, String attName, String defVal) {
  69. Object value = null;
  70. Field field = null;
  71. try {
  72. field = obj.getClass().getDeclaredField(attName);
  73. field.setAccessible(true);
  74. value = field.get(obj);
  75. } catch (Exception e) {
  76. return defVal;
  77. }
  78. if(value == null || value.toString().trim().length() <= 0) {
  79. value = defVal;
  80. }
  81. return value;
  82. }
  83.  
  84. /**
  85. * 为对象属性赋值
  86. * @param obj 要赋值的对象
  87. * @param attName 对象属性名
  88. * @param value 属性值
  89. */
  90. public static void setObjAttributeValue(Object obj, String attName, String value) {
  91. Field field = null;
  92. try {
  93. field = obj.getClass().getDeclaredField(attName);
  94. field.setAccessible(true);
  95. field.set(obj, value);
  96. } catch (Exception e) {
  97. }
  98. }
  99. }

实体类:ContactRecord.java

  1. package com.tianwen.nlp.pojo;
  2.  
  3. public class ContactRecord {
  4. private Integer id;
  5.  
  6. private String mbActivityInfoId;
  7.  
  8. private String activityType;
  9.  
  10. private String activityName;
  11.  
  12. private String sendDate;
  13.  
  14. private String state;
  15.  
  16. private String isDelete;
  17.  
  18. private String customerId;
  19.  
  20. private String customerGender;
  21.  
  22. private String customerBirthday;
  23.  
  24. private String empNo;
  25.  
  26. private String noteType;
  27.  
  28. private String contactDate;
  29.  
  30. private String remark;
  31.  
  32. public Integer getId() {
  33. return id;
  34. }
  35.  
  36. public void setId(Integer id) {
  37. this.id = id;
  38. }
  39.  
  40. public String getMbActivityInfoId() {
  41. return mbActivityInfoId;
  42. }
  43.  
  44. public void setMbActivityInfoId(String mbActivityInfoId) {
  45. this.mbActivityInfoId = mbActivityInfoId == null ? null : mbActivityInfoId.trim();
  46. }
  47.  
  48. public String getActivityType() {
  49. return activityType;
  50. }
  51.  
  52. public void setActivityType(String activityType) {
  53. this.activityType = activityType == null ? null : activityType.trim();
  54. }
  55.  
  56. public String getActivityName() {
  57. return activityName;
  58. }
  59.  
  60. public void setActivityName(String activityName) {
  61. this.activityName = activityName == null ? null : activityName.trim();
  62. }
  63.  
  64. public String getSendDate() {
  65. return sendDate;
  66. }
  67.  
  68. public void setSendDate(String sendDate) {
  69. this.sendDate = sendDate == null ? null : sendDate.trim();
  70. }
  71.  
  72. public String getState() {
  73. return state;
  74. }
  75.  
  76. public void setState(String state) {
  77. this.state = state == null ? null : state.trim();
  78. }
  79.  
  80. public String getIsDelete() {
  81. return isDelete;
  82. }
  83.  
  84. public void setIsDelete(String isDelete) {
  85. this.isDelete = isDelete == null ? null : isDelete.trim();
  86. }
  87.  
  88. public String getCustomerId() {
  89. return customerId;
  90. }
  91.  
  92. public void setCustomerId(String customerId) {
  93. this.customerId = customerId == null ? null : customerId.trim();
  94. }
  95.  
  96. public String getCustomerGender() {
  97. return customerGender;
  98. }
  99.  
  100. public void setCustomerGender(String customerGender) {
  101. this.customerGender = customerGender == null ? null : customerGender.trim();
  102. }
  103.  
  104. public String getCustomerBirthday() {
  105. return customerBirthday;
  106. }
  107.  
  108. public void setCustomerBirthday(String customerBirthday) {
  109. this.customerBirthday = customerBirthday == null ? null : customerBirthday.trim();
  110. }
  111.  
  112. public String getEmpNo() {
  113. return empNo;
  114. }
  115.  
  116. public void setEmpNo(String empNo) {
  117. this.empNo = empNo == null ? null : empNo.trim();
  118. }
  119.  
  120. public String getNoteType() {
  121. return noteType;
  122. }
  123.  
  124. public void setNoteType(String noteType) {
  125. this.noteType = noteType == null ? null : noteType.trim();
  126. }
  127.  
  128. public String getContactDate() {
  129. return contactDate;
  130. }
  131.  
  132. public void setContactDate(String contactDate) {
  133. this.contactDate = contactDate == null ? null : contactDate.trim();
  134. }
  135.  
  136. public String getRemark() {
  137. return remark;
  138. }
  139.  
  140. public void setRemark(String remark) {
  141. this.remark = remark == null ? null : remark.trim();
  142. }
  143. }

此处用与上传的excel文件:http://files.cnblogs.com/files/yinz/场景2-样例数据_拜访记录.rar

apache POI 操作excel<导入导出>的更多相关文章

  1. 【原创】POI操作Excel导入导出工具类ExcelUtil

    关于本类线程安全性的解释: 多数工具方法不涉及共享变量问题,至于添加合并单元格方法addMergeArea,使用ThreadLocal变量存储合并数据,ThreadLocal内部借用Thread.Th ...

  2. SpringBoot集成文件 - 集成POI之Excel导入导出

    Apache POI 是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程序对Microsoft Office格式档案读和写的功能.本文主要介绍通过Spr ...

  3. 利用Apache POI操作Excel

    最近在做接口,有个功能是利用Excel导入汽车发动机所需零件信息到线上系统中.简单回顾一下之前学过的用java操作Excel. 1.maven配置Apache POI pom.xml中配置POIjar ...

  4. Java之POI的excel导入导出

    一.Apache POI是一种流行的API,它允许程序员使用Java程序创建,修改和显示MS Office文件.这由Apache软件基金会开发使用Java分布式设计或修改Microsoft Offic ...

  5. Java使用Apache POI进行Excel导入和导出

    Manve依赖 <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml --> <dependency> ...

  6. POI操作Excel导入和导出

    Apache的POI组件是Java操作Microsoft Office办公套件的强大API,当中对Word,Excel和PowperPoint都有支持,当然使用较多的还是Excel.由于Word和Po ...

  7. 基于POI的Excel导入导出(JAVA实现)

    今天做了个excel的导入导出功能,在这记录下. 首先现在相关poi的相关jar包,资源链接:http://download.csdn.net/detail/opening_world/9663247 ...

  8. POI实现Excel导入导出

    我们知道要创建一张excel你得知道excel由什么组成,比如说sheet也就是一个工作表格,例如一行,一个单元格,单元格格式,单元格内容格式…这些都对应着poi里面的一个类. 一个excel表格: ...

  9. Spring Boot学习笔记----POI(Excel导入导出)

    业务:动态生成模板导出Excel,用户修改完再导入Excel. Spring boot + bootstrap + poi 1.添加Dependence <dependency> < ...

随机推荐

  1. FCL研究-集合- System.Collections 接口和对象集合

    [目录] 发现自己已经有很长一段时间写代码没什么进步了,随便读读FCL的源码,看看之前一直用的方法是如何实现的,也顺便提高下自己.FCL很是庞大,很难下口,于是用最笨的办法,先看常见的命名空间,逐个展 ...

  2. CentOS 6.9系统时间和硬件时间设置(转)

    总结一下hwclock,这个容易晕: 1)/etc/sysconfig/clock 文件,只对 hwclock 命令有效,且只在系统启动和关闭的时候才有用(修改了其中的 UTC=true 到 UTC= ...

  3. 如何垂直居中元素(浮动元素&居中一个<img>)?

    1.如何居中一个浮动元素? 方法一:已知元素的高度   <!DOCTYPE html> <html lang="en"> <head> < ...

  4. HTTP协议下保证登录密码不被获取最健壮方式

    原文:http://www.cnblogs.com/intsmaze/p/6009648.html HTTP协议下保证登录密码不被获取最健壮方式   说到在http协议下用户登录如何保证密码安全这个问 ...

  5. HTTPS.SYS怎样使用HTTPS

    HTTPS.SYS怎样使用HTTPS 参考了MORMOT的官方文档:http://blog.synopse.info/post/2013/09/04/HTTPS-communication-in-mO ...

  6. touch: cannot touch ‘/var/jenkins_home/copy_reference_file.log’: Permission denied Can not write to /var/jenkins_home/copy_reference_file.log. Wrong volume permissions?

    问题:在从 https://c.163.com/hub#/m/repository/?repoId=3093 下载镜像 docker pull hub.c.163.com/library/jenkin ...

  7. python--如何操作表

    >>> import MySQLdb >>> conn=MySQLdb.connect(user='admin',passwd='',host='192.168.3 ...

  8. Java平时需要注意的事项

    1.String 相等 稍微有点经验的程序员都会用equals比较而不是用 ==,但用equals就真的安全了吗,看下面的代码 user.getName().equals("xiaoming ...

  9. OS中处理机调度模型和调度算法

    OS中处理机调度模型和调度算法 调度层次 1.1. 高级调度(长程调度,作业调度) 功能:依据某种算法.把在外存队列上处于后备队列的那些作业调入内存.以作业为操做对象. 作业:比程序更为广泛的概念,不 ...

  10. No goals have been specified for this build 解决方案

    运行maven报错:[ERROR] No goals have been specified for this build. You must specify a valid lifecycle ph ...