1 maven坐标
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.10-FINAL</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.10-FINAL</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.6</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
2 创建注解
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD })
public @interface ExcelField {
public abstract String name();
public abstract String column() default "";
public abstract String prompt() default "";
public abstract String[] combo() default {};
public abstract boolean isExport() default true;
public abstract boolean isMark() default false;
public abstract boolean isSum() default false;
public abstract int index();
}
3 创建实体类,在属性中添加刚才创建的注解
public class Apply {
private Long id;
private String accessToken;
private String itemCode;
private String taskHandleItem;
private String applyNo;
private String itemName;
private String targetType;
@ExcelField(name = "办理对象名称",index = 11)
private String targetName;
@ExcelField(name = "办理对象编号",index = 13)
private String targetNo;
@ExcelField(name = "申请人姓名",index = 11)
private String username;
private String licenseType;
@ExcelField(name = "申请人证件编号",index = 13)
private String licenseNo;
@ExcelField(name = "申请人手机号",index = 10)
private String mobile;
@ExcelField(name = "受理部门(办理点)编号",index = 7)
private String departCode;
@ExcelField(name = "受理部门(办理点)名称",index = 8)
private String departName;
private String source;
private String content;
@ExcelField(name = "保存时间",index = 5)
private String opTime;
private String districtCode;
private Info info;
private String ProjectType;
private String isStatistics;
@ExcelField(name = "对应订单号",index = 3)
private String orderNo;
@ExcelField(name = "订购端来源",index = 6)
private String platform;
@ExcelField(name = "票类型",index = 8)
private String scheduleName;
@ExcelField(name = "reservedate",index = 9)
private String reservedate;
@ExcelField(name = "票面价格",index = 15)
private String showPrice;
@ExcelField(name = "groupName",index = 1)
private String groupName;
@ExcelField(name = "voucherNo",index = 2)
private String voucherNo;
...
4 读取excel文件
@Test
public void testReadExcel() throws InstantiationException, IllegalAccessException {
List<Apply> applyList = importExcelUtil.readFromExcel(Constant.filePath, Apply.class);
System.out.println(applyList);
}
5 写入excel
@RequestMapping("export")
public void export(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {
List<Apply> applyList = applyService.findAll();
ExportExcelUtil excelUtil = new ExportExcelUtil();
ClassPathResource classPathResource = new ClassPathResource("static/excleTemplate/test.xlsx");
File excelTplFile = classPathResource.getFile();
Workbook workbook = excelUtil.getWorkbook(excelTplFile);
Sheet sheet = excelUtil.getSheet(workbook,"sheet1");
for (int i = 0; i < applyList.size(); i++) {
Apply apply = applyList.get(i);
Row row = excelUtil.createRow(sheet);
Cell cell0 = excelUtil.createCell(row,0);
cell0.setCellValue(apply.getApplyNo());
Cell cell1 = excelUtil.createCell(row,1);
cell1.setCellValue(apply.getContent());
Cell cell2 = excelUtil.createCell(row,2);
cell2.setCellValue(apply.getDepartCode());
Cell cell3 = excelUtil.createCell(row,3);
cell3.setCellValue(apply.getDepartName());
}
String fileName="dept_list.xlsx";
response.setContentType("application/ms-excel");
response.setHeader("Content-disposition", "attachment;filename="+fileName);
ServletOutputStream ouputStream = response.getOutputStream();
workbook.write(ouputStream);
ouputStream.flush();
ouputStream.close();
}
6 相关工具类
import org.apache.poi.ss.usermodel.*;
import java.io.File;
import java.io.FileInputStream;
public class ExportExcelUtil {
private CellStyle cs;
public File getExcelTplFile(String path, String filePath) throws Exception {
String classDir = null;
String fileBaseDir = null;
File file = null;
file = new File(path+filePath);
if (!file.exists()) {
throw new Exception("模板文件不存在!");
}
return file;
}
public Workbook getWorkbook(File file) throws Exception {
FileInputStream fis = new FileInputStream(file);
Workbook wb = new ImportExcelUtil().getWorkbook(fis, file.getName());
return wb;
}
public Sheet getSheet(Workbook wb, String sheetName) throws Exception {
cs = setSimpleCellStyle(wb);
Sheet sheet = wb.getSheet(sheetName);
return sheet;
}
public Row createRow(Sheet sheet) throws Exception {
int lastRow = sheet.getLastRowNum() + 1;
Row row = sheet.createRow(lastRow);
return row;
}
public Cell createCell(Row row, int CellNum) throws Exception {
Cell cell = row.createCell(CellNum);
cell.setCellStyle(cs);
return cell;
}
public CellStyle setSimpleCellStyle(Workbook wb) {
CellStyle cs = wb.createCellStyle();
cs.setBorderBottom(CellStyle.BORDER_THIN);
cs.setBorderLeft(CellStyle.BORDER_THIN);
cs.setBorderTop(CellStyle.BORDER_THIN);
cs.setBorderRight(CellStyle.BORDER_THIN);
cs.setAlignment(CellStyle.ALIGN_CENTER);
return cs;
}
}
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
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.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;
@Component
public class ImportExcelUtil {
private final static String excel2003L =".xls";
private final static String excel2007U =".xlsx";
public List<List<Object>> getListByExcel(InputStream in,String fileName) throws Exception{
List<List<Object>> list = null;
Workbook work = this.getWorkbook(in,fileName);
if(null == work){
throw new Exception("创建Excel工作薄为空!");
}
Sheet sheet = null;
Row row = null;
Cell cell = null;
list = new ArrayList<List<Object>>();
for (int i = 0; i < work.getNumberOfSheets(); i++) {
sheet = work.getSheetAt(i);
if(sheet==null){continue;}
for (int j = sheet.getFirstRowNum(); j < sheet.getLastRowNum()+1; j++) {
row = sheet.getRow(j);
if(row==null||row.getFirstCellNum()==j){continue;}
List<Object> li = new ArrayList<Object>();
boolean ok = true;
for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
cell = row.getCell(y);
if (cell == null){
ok = false;
break;
}
li.add(this.getCellValue(cell));
}
if (ok){
list.add(li);
}
}
}
return list;
}
public Workbook getWorkbook(InputStream inStr,String fileName) throws Exception{
Workbook wb = null;
String fileType = fileName.substring(fileName.lastIndexOf("."));
if(excel2003L.equals(fileType)){
wb = new HSSFWorkbook(inStr);
}else if(excel2007U.equals(fileType)){
wb = new XSSFWorkbook(inStr);
}else{
throw new Exception("解析的文件格式有误!");
}
return wb;
}
public Object getCellValue(Cell cell){
Object value = null;
DecimalFormat df = new DecimalFormat("0");
SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");
DecimalFormat df2 = new DecimalFormat("0.00");
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
value = cell.getRichStringCellValue().getString();
break;
case Cell.CELL_TYPE_NUMERIC:
if("General".equals(cell.getCellStyle().getDataFormatString())){
value = df.format(cell.getNumericCellValue());
}else if("m/d/yy".equals(cell.getCellStyle().getDataFormatString())){
value = sdf.format(cell.getDateCellValue());
}else{
value = df2.format(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BOOLEAN:
value = cell.getBooleanCellValue();
break;
case Cell.CELL_TYPE_BLANK:
value = "";
break;
default:
break;
}
return value;
}
public <T> List<T> readFromExcel(String filePath,Class<T> tClass) throws IllegalAccessException,
InstantiationException {
String fileName = filePath.substring(filePath.lastIndexOf("\\"));
File file = new File(filePath);
log.info("文件地址:"+filePath);
InputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
log.info("");
}
List<List<Object>> listByExcel = null;
try {
listByExcel = this.getListByExcel(inputStream, fileName);
} catch (Exception e) {
e.printStackTrace();
}
List<T> applyList = new ArrayList<>();
for (List<Object> objects : listByExcel) {
Field[] fields = ReflectUtil.getFields(Apply.class);
T t = tClass.newInstance();
for (Field field : fields) {
if (AnnotationUtil.hasAnnotation(field, ExcelField.class)) {
Object index = AnnotationUtil.getAnnotationValue(field, ExcelField.class, "index");
ReflectUtil.setFieldValue(t, field, objects.get(Convert.toInt(index)));
}
}
applyList.add(t);
}
log.info("------------------------------end-------------------------------");
return applyList;
}
}