1、首先导入maven依赖

        <!-- POI核心依赖 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.8</version>
</dependency>
<!-- 为POI支持Office Open XML -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.8</version>
</dependency>

2、MicroUtil.java工具类

package com.yinz.tool.j2ee;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set; import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.WorkbookUtil;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import com.yinz.tool.ReflectUtil; /**
*
* @description: 执行Microsoft文件 相关操作《导出/导入excel表格等》
* 需要用到POI相关jar包
* @author yinz
* 2016-11-9
*/
public class MicroUtil { public static void main(String[] args) throws Exception {
String excelPath = "C:\\Users\\yinz\\Desktop\\场景2\\场景2-样例数据_拜访记录.xls";
Map<Integer, String> indexMapAtt = new HashMap<Integer, String>();
indexMapAtt.put(0, "mbActivityInfoId");
indexMapAtt.put(1, "activity");
indexMapAtt.put(2, "activityName");
indexMapAtt.put(3, "sendDate");
indexMapAtt.put(4, "state");
indexMapAtt.put(5, "isDelete");
indexMapAtt.put(6, "customerId");
indexMapAtt.put(7, "customerGender");
indexMapAtt.put(8, "customerBirthDay");
indexMapAtt.put(9, "empNo");
indexMapAtt.put(10, "noteType");
indexMapAtt.put(11, "contactDate");
indexMapAtt.put(12, "remark");
List<ContactRecord> result = readExcel(excelPath, null, 1, indexMapAtt, ContactRecord.class);
System.out.println(result);
} /**
* 导出excel表格到输出流<可用于web界面导出excel表格>
* @param response : 输出流
* @param result : 需要导出的数据java对象列表
* @param name : 文件名
* @param excelHead : 表格列名
* @param params : 列对应的对象属性名
* @param isAddIndex : 是否增加序列号
*/
public static void exportExcel(HttpServletResponse response, List<?> result, String name, String[] excelHead, Object[] params, boolean isAddIndex) {
//创建excel表格
HSSFWorkbook wb = new HSSFWorkbook();
//长度不能超过31个字符,并且不能包含部分特殊字符,使用如下方法,可将特殊字符替换为空格,长度超过31的进行
name = WorkbookUtil.createSafeSheetName(name);
HSSFSheet sheet = wb.createSheet(name);
String[] head = null;
//如果增加序号,第一列设为序号,重新生成head数组
if (isAddIndex)
{
head = new String[excelHead.length + 1];
head[0] = "序列号";
for (int i = 0; i < excelHead.length; i++)
{
head[i+1] = excelHead[i];
}
}
else
{
head = excelHead;
}
for(int i=0;i<head.length;i++){
sheet.setColumnWidth(i, 6000);
}
//Rows are 0 based.
HSSFRow row = sheet.createRow((int) 0);
HSSFCellStyle style = wb.createCellStyle();
HSSFCellStyle style2 = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
HSSFDataFormat format = wb.createDataFormat();
style2.setDataFormat(format.getFormat("@")); for(int i=0;i<head.length;i++){
HSSFCell cell = row.createCell((short) i);
cell.setCellValue(head[i]);
cell.setCellStyle(style);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
sheet.setDefaultColumnStyle(i, style2);
}
int count = 1;
if (result != null)
{
for (Object obj : result){ int i = 0;
row = sheet.createRow(count);
//先增加序号
if (isAddIndex)
{
row.createCell((short) 0).setCellValue(count);
i++;
}
for (Object attrName:params)
{
HSSFCell cell = row.createCell((short) i);
cell.setCellStyle(style2);
Object value = ReflectUtil.getObjAttributeValue(obj, (String)attrName);
cell.setCellValue(value == null ? "" : value.toString());
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
i++;
}
count++;
}
}
try
{
String filename = name+".xls";//设置文件名
response.reset();
response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(filename, "UTF-8"));
response.setContentType("application/vnd.ms-excel");
OutputStream fout = response.getOutputStream();
//将excel写到输出流
wb.write(fout);
fout.flush();
fout.close();
response.getOutputStream().flush();
response.getOutputStream().close(); }
catch (Exception e)
{
e.printStackTrace();
}
} //读取excel表格数据 /**
* 读取excel表格内容到java对象
* @param inStream excel文件输入流
* @param sheetPage 要读取的sheet页(0 based),若为null,则读取第1页
* @param startRow 从第几行开始读取
* @param indexMapAtt excel表单cell与java对象对应关系
* @param clazz 要生成的java类型
* @return
* @throws Exception
*/
public static <T> List<T> readExcel(InputStream inStream, Integer[] sheetPage, Integer startRow, Map<Integer, String> indexMapAtt, Class<T> clazz) throws Exception {
startRow = startRow == null ? 0 : startRow;
List<T> result = new ArrayList<T>();
Workbook wb = new HSSFWorkbook(inStream);;
Sheet sheet = null;
if(sheetPage == null || sheetPage.length <= 0) {
sheet = wb.getSheetAt(0);
readSheet(sheet, result, startRow, indexMapAtt, clazz);
} else {
for(Integer sheetIndex : sheetPage) {
sheet = wb.getSheetAt(sheetIndex);
readSheet(sheet, result, startRow, indexMapAtt, clazz);
}
} return result;
} /**
*
* @param excelPath excel表格路径
* @param sheetPage 要读取的excel中的sheet所有 、0开始
* @param startRow 开始读取的数据的行标 ,0开始
* @param indexMapAtt 列索引与对象属性对应map
* @param clazz 每行记录所对应的java对象
* @return
* @throws Exception
*/
@SuppressWarnings("resource")
public static <T> List<T> readExcel(String excelPath, Integer[] sheetPage, Integer startRow, Map<Integer, String> indexMapAtt, Class<T> clazz) throws Exception {
startRow = startRow == null ? 0 : startRow;
List<T> result = new ArrayList<T>();
InputStream inStream = new FileInputStream(excelPath);
Workbook wb = null;
if(excelPath.matches("^.+\\.(?i)(xls)$")) {
//excel2003
wb = new HSSFWorkbook(inStream);
} else if(excelPath.matches("^.+\\.(?i)(xlsx)$")) {
//excel2007
wb = new XSSFWorkbook(inStream);
} else {
return null;
}
Sheet sheet = null;
if(sheetPage == null || sheetPage.length <= 0) {
sheet = wb.getSheetAt(0);
readSheet(sheet, result, startRow, indexMapAtt, clazz);
} else {
for(Integer sheetIndex : sheetPage) {
sheet = wb.getSheetAt(sheetIndex);
readSheet(sheet, result, startRow, indexMapAtt, clazz);
}
} return result;
} //读取excel中的sheet数据、并为java对象集合赋值
private static <T> void readSheet(Sheet sheet, List<T> result, Integer startRow, Map<Integer, String> indexMapAtt, Class<T> resultType) throws Exception {
//获取总行数
int totalRows = sheet.getPhysicalNumberOfRows(); T t;
for(int i = startRow; i < totalRows; i++) {
Row row = sheet.getRow(i);
if(row == null) {
continue;
} t = resultType.newInstance();
Set<Integer> cellIndexSet = indexMapAtt.keySet();
for(Integer index : cellIndexSet) {
Cell cell = row.getCell(index);
if(cell == null) {
continue;
}
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
ReflectUtil.setObjAttributeValue(t, indexMapAtt.get(index), cell.getStringCellValue() == null ? "" : cell.getStringCellValue());
}
result.add(t);
}
}
}

反射工具类:ReflectUtil.java

package com.yinz.tool;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map; /**
*
* @description: 反射工具类
* @author yinz
* 2016-11-9
*/
public class ReflectUtil { /**
* 将对象属性和值以map存储,默认包含属性值为null的属性
* @param obj
* @return
*/
public static Map<String, Object> obj2map(Object obj) {
return obj2map(obj, true);
} /**
* 将对象属性和值以map存储
* @param obj
* @param isContainNullValue : 是否包含属性中为空的属性
* @return
*/
public static Map<String, Object> obj2map(Object obj, boolean isContainNullValue) {
Map<String, Object> map = new HashMap<String, Object>(); Field[] fList = obj.getClass().getDeclaredFields();
try {
for(Field f : fList) {
f.setAccessible(true);
if(isContainNullValue) {
map.put(f.getName(), f.get(obj));
} else {
if(f.get(obj) != null && f.get(obj) != "") {
map.put(f.getName(), f.get(obj));
}
}
}
} catch (Exception e) {
return null;
}
return map;
} /**
* 获取对象指定属性值
* @param obj
* @param attName
* @return
*/
public static Object getObjAttributeValue(Object obj, String attName) {
return getObjAttributeValue(obj, attName, "");
} /**
* 获取对象指定属性的值
* @param obj : 查询对象
* @param attName : 要获取的属性名
* @param defVal : 默认值
* @return
*/
public static Object getObjAttributeValue(Object obj, String attName, String defVal) {
Object value = null;
Field field = null;
try {
field = obj.getClass().getDeclaredField(attName);
field.setAccessible(true);
value = field.get(obj);
} catch (Exception e) {
return defVal;
}
if(value == null || value.toString().trim().length() <= 0) {
value = defVal;
}
return value;
} /**
* 为对象属性赋值
* @param obj 要赋值的对象
* @param attName 对象属性名
* @param value 属性值
*/
public static void setObjAttributeValue(Object obj, String attName, String value) {
Field field = null;
try {
field = obj.getClass().getDeclaredField(attName);
field.setAccessible(true);
field.set(obj, value);
} catch (Exception e) {
}
}
}

实体类:ContactRecord.java

package com.tianwen.nlp.pojo;

public class ContactRecord {
private Integer id; private String mbActivityInfoId; private String activityType; private String activityName; private String sendDate; private String state; private String isDelete; private String customerId; private String customerGender; private String customerBirthday; private String empNo; private String noteType; private String contactDate; private String remark; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getMbActivityInfoId() {
return mbActivityInfoId;
} public void setMbActivityInfoId(String mbActivityInfoId) {
this.mbActivityInfoId = mbActivityInfoId == null ? null : mbActivityInfoId.trim();
} public String getActivityType() {
return activityType;
} public void setActivityType(String activityType) {
this.activityType = activityType == null ? null : activityType.trim();
} public String getActivityName() {
return activityName;
} public void setActivityName(String activityName) {
this.activityName = activityName == null ? null : activityName.trim();
} public String getSendDate() {
return sendDate;
} public void setSendDate(String sendDate) {
this.sendDate = sendDate == null ? null : sendDate.trim();
} public String getState() {
return state;
} public void setState(String state) {
this.state = state == null ? null : state.trim();
} public String getIsDelete() {
return isDelete;
} public void setIsDelete(String isDelete) {
this.isDelete = isDelete == null ? null : isDelete.trim();
} public String getCustomerId() {
return customerId;
} public void setCustomerId(String customerId) {
this.customerId = customerId == null ? null : customerId.trim();
} public String getCustomerGender() {
return customerGender;
} public void setCustomerGender(String customerGender) {
this.customerGender = customerGender == null ? null : customerGender.trim();
} public String getCustomerBirthday() {
return customerBirthday;
} public void setCustomerBirthday(String customerBirthday) {
this.customerBirthday = customerBirthday == null ? null : customerBirthday.trim();
} public String getEmpNo() {
return empNo;
} public void setEmpNo(String empNo) {
this.empNo = empNo == null ? null : empNo.trim();
} public String getNoteType() {
return noteType;
} public void setNoteType(String noteType) {
this.noteType = noteType == null ? null : noteType.trim();
} public String getContactDate() {
return contactDate;
} public void setContactDate(String contactDate) {
this.contactDate = contactDate == null ? null : contactDate.trim();
} public String getRemark() {
return remark;
} public void setRemark(String remark) {
this.remark = remark == null ? null : remark.trim();
}
}

此处用与上传的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. Problem H: 阶乘和

    #include<stdio.h> int main() { ; ; ; int n; scanf("%d",&n); ;i<=n;i++) { ret= ...

  2. HTML5 Boilerplate笔记(3)

    HTML5 Boilerplate项目网址:https://github.com/h5bp/html5-boilerplate

  3. activemq 5.13.2 jdbc 数据库持久化 异常 找不到驱动程序

    原文:https://my.oschina.net/u/2284972/blog/662033 摘要: activemq jdbc 数据库持久化 异常 找不到驱动程序 Caused by: java. ...

  4. 【java】LocalDate和Date等新旧日期类的转化

    // 01. java.util.Date --> java.time.LocalDateTime public void UDateToLocalDateTime() { java.util. ...

  5. [Ubuntu Setup] Ubuntu 14.10 LTS 中文输入法的安装

    from : http://www.cnblogs.com/zhj5chengfeng/archive/2013/06/23/3150620.html http://xboot.org/thread- ...

  6. druid.io 海量实时OLAP数据仓库 (翻译+总结) (1)

    介绍 我是NDPmedia公司的大数据OLAP的资深高级工程师, 专注于OLAP领域, 现将一个成熟的可靠的高性能的海量实时OLAP数据仓库介绍给大家: druid.io NDPmedia在2014年 ...

  7. [Functional Programming Monad] Map And Evaluate State With A Stateful Monad

    We explore our first stateful transaction, by devising a means to echo our state value into the resu ...

  8. Java Volatile keyword

    Volatile修饰的成员变量在每次被线程訪问时,都强迫从主内存中重读该成员变量的值.并且,当成员变量发生变化时,强迫线程将变化值回写到主内存.这样在不论什么时刻,两个不同的线程总是看到某个成员变量的 ...

  9. LogManager

    public class LogManager { // Fields public static bool Debugstate; // Methods public static void Log ...

  10. ios app在itunesConnect里面的几种状态

    原地址:http://blog.csdn.net/dean19900504/article/details/8164734 Waiting for Upload (Yellow) Appears wh ...