Springboot 는 POI 를 사용 하여 Excel 파일 예제 내 보 내기

26213 단어 springboot
앞 에 서 는 POI 를 사용 하여 Word 파일 을 내 보 내 고 Excel 파일 을 읽 는 것 을 다 루 었 습 니 다.이 두 가지 예 는 상대 적 으로 간단 합 니 다.다음은 POI 를 사용 하여 Excel 파일 을 내 보 내 는 것 이 훨씬 복잡 하고 내용 도 길 어 집 니 다.
헤더 정보 만 들 기
표 두 정 보 는 표 두 구조 와 정렬 을 자동 으로 생 성 하 는 데 사용 된다.

public class ExcelHeader implements Comparable<ExcelHeader>{
 /**
  * excel     
  */
 private String title;
 /**
  *         
  */
 private int order;
 /**
  *        
  */
 private String methodName;


 public String getTitle() {
  return title;
 }
 public void setTitle(String title) {
  this.title = title;
 }
 public int getOrder() {
  return order;
 }
 public void setOrder(int order) {
  this.order = order;
 }
 public String getMethodName() {
  return methodName;
 }
 public void setMethodName(String methodName) {
  this.methodName = methodName;
 }

 public int compareTo(ExcelHeader o) {
  return order>o.order?1:(order<o.order?-1:0);
 }
 public ExcelHeader(String title, int order, String methodName) {
  super();
  this.title = title;
  this.order = order;
  this.methodName = methodName;
 }
}

헤더 정보의 Annotation

/**
 *       get      annotation,   annotation            
 * Created by     on 2016/10/29 0:14.
 */
@Retention(RetentionPolicy.RUNTIME)
public @interface ExcelResources {
 /**
  *        
  * @return
  */
 String title();
 /**
  *  excel   
  * @return
  */
 int order() default 9999;
}
데이터 실체 만 들 기

public class WebDto {

 //    
 private String name;

 //  
 private String url;

 //   
 private String username;

 //  
 private String password;

 //     
 private Integer readCount;

 public WebDto(String name, String url, String username, String password, Integer readCount) {
  this.name = name;
  this.url = url;
  this.username = username;
  this.password = password;
  this.readCount = readCount;
 }

 public WebDto() {}

 @Override
 public String toString() {
  return "WebDto{" +
    "name='" + name + '\'' +
    ", url='" + url + '\'' +
    ", username='" + username + '\'' +
    ", password='" + password + '\'' +
    ", readCount=" + readCount +
    '}';
 }

 @ExcelResources(title="    ",order=1)
 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 @ExcelResources(title="  ",order=2)
 public String getUrl() {
  return url;
 }

 public void setUrl(String url) {
  this.url = url;
 }

 @ExcelResources(title="   ",order=3)
 public String getUsername() {
  return username;
 }

 public void setUsername(String username) {
  this.username = username;
 }

 @ExcelResources(title="  ",order=4)
 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }

 @ExcelResources(title="     ",order=5)
 public Integer getReadCount() {
  return readCount;
 }

 public void setReadCount(Integer readCount) {
  this.readCount = readCount;
 }
}

메모:여기 서@ExcelResources 를 사용 하여 헤더 정보 와 번 호 를 자동 으로 식별 합 니 다.
템 플 릿 파일 가 져 오 는 도구 클래스

public class TemplateFileUtil {

 public static FileInputStream getTemplates(String tempName) throws FileNotFoundException {
  return new FileInputStream(ResourceUtils.getFile("classpath:excel-templates/"+tempName));
 }
}
메모:여기 서 보 듯 이 모든 엑셀 템 플 릿 파일 은 resources/엑셀-templates/디 렉 터 리 에 놓 여 있 습 니 다.
템 플 릿 도구 클래스
이 를 통 해 표 스타일 등 을 자동 으로 복사 할 수 있 습 니 다.

/**
 *             
 *        ,   excel        sernums
 *        ,      Map,  map           , excel   #   
 *                      datas
 *           ,       styles    ,            
 *     defaultStyls    ,      ,    defaultStyles  datas       
 * Created by     [email protected] on 2016/10/28 23:38.
 */
public class ExcelTemplate {

 /**
  *      
  */
 public final static String DATA_LINE = "datas";
 /**
  *       
  */
 public final static String DEFAULT_STYLE = "defaultStyles";
 /**
  *      
  */
 public final static String STYLE = "styles";
 /**
  *         
  */
 public final static String SER_NUM = "sernums";
 private static ExcelTemplate et = new ExcelTemplate();
 private Workbook wb;
 private Sheet sheet;
 /**
  *         
  */
 private int initColIndex;
 /**
  *         
  */
 private int initRowIndex;
 /**
  *     
  */
 private int curColIndex;
 /**
  *     
  */
 private int curRowIndex;
 /**
  *      
  */
 private Row curRow;
 /**
  *        
  */
 private int lastRowIndex;
 /**
  *     
  */
 private CellStyle defaultStyle;
 /**
  *     
  */
 private float rowHeight;
 /**
  *            
  */
 private Map<Integer,CellStyle> styles;
 /**
  *     
  */
 private int serColIndex;
 private ExcelTemplate(){

 }
 public static ExcelTemplate getInstance() {
  return et;
 }

 /**
  *  classpath            
  * @param path
  * @return
  */
 public ExcelTemplate readTemplateByClasspath(String path) {
  try {
   wb = new HSSFWorkbook(TemplateFileUtil.getTemplates(path));
   initTemplate();
  } catch (IOException e) {
   e.printStackTrace();
   throw new RuntimeException("       !   ");
  }
  return this;
 }
 /**
  *            
  * @param filepath
  */
 public void writeToFile(String filepath) {
  FileOutputStream fos = null;
  try {
   fos = new FileOutputStream(filepath);
   wb.write(fos);
  } catch (FileNotFoundException e) {
   e.printStackTrace();
   throw new RuntimeException("        ");
  } catch (IOException e) {
   e.printStackTrace();
   throw new RuntimeException("      :"+e.getMessage());
  } finally {
   try {
    if(fos!=null) fos.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
 /**
  *            
  * @param os
  */
 public void wirteToStream(OutputStream os) {
  try {
   wb.write(os);
  } catch (IOException e) {
   e.printStackTrace();
   throw new RuntimeException("     :"+e.getMessage());
  }
 }
 /**
  *           
  * @param path
  * @return
  */
 public ExcelTemplate readTemplateByPath(String path) {
  try {
   wb = new HSSFWorkbook(TemplateFileUtil.getTemplates(path));
   initTemplate();
  } catch (IOException e) {
   e.printStackTrace();
   throw new RuntimeException("       !   ");
  }
  return this;
 }

 /**
  *        ,  String  
  * @param value
  */
 public void createCell(String value) {
  Cell c = curRow.createCell(curColIndex);
  setCellStyle(c);
  c.setCellValue(value);
  curColIndex++;
 }
 public void createCell(int value) {
  Cell c = curRow.createCell(curColIndex);
  setCellStyle(c);
  c.setCellValue((int)value);
  curColIndex++;
 }
 public void createCell(Date value) {
  Cell c = curRow.createCell(curColIndex);
  setCellStyle(c);
  c.setCellValue(value);
  curColIndex++;
 }
 public void createCell(double value) {
  Cell c = curRow.createCell(curColIndex);
  setCellStyle(c);
  c.setCellValue(value);
  curColIndex++;
 }
 public void createCell(boolean value) {
  Cell c = curRow.createCell(curColIndex);
  setCellStyle(c);
  c.setCellValue(value);
  curColIndex++;
 }

 public void createCell(Calendar value) {
  Cell c = curRow.createCell(curColIndex);
  setCellStyle(c);
  c.setCellValue(value);
  curColIndex++;
 }
 public void createCell(BigInteger value) {
  Cell c = curRow.createCell(curColIndex);
  setCellStyle(c);
  c.setCellValue(value==null?0:value.intValue());
  curColIndex++;
 }
 /**
  *          
  * @param c
  */
 private void setCellStyle(Cell c) {
  if(styles.containsKey(curColIndex)) {
   c.setCellStyle(styles.get(curColIndex));
  } else {
   c.setCellStyle(defaultStyle);
  }
 }
 /**
  *     ,           ,         
  */
 public void createNewRow() {
  if(lastRowIndex>curRowIndex&&curRowIndex!=initRowIndex) {
   sheet.shiftRows(curRowIndex, lastRowIndex, 1,true,true);
   lastRowIndex++;
  }
  curRow = sheet.createRow(curRowIndex);
  curRow.setHeightInPoints(rowHeight);
  curRowIndex++;
  curColIndex = initColIndex;
 }

 /**
  *     ,                  
  */
 public void insertSer() {
  int index = 1;
  Row row = null;
  Cell c = null;
  for(int i=initRowIndex;i<curRowIndex;i++) {
   row = sheet.getRow(i);
   c = row.createCell(serColIndex);
   setCellStyle(c);
   c.setCellValue(index++);
  }
 }
 /**
  *   map       ,  Map      #    
  * @param datas
  */
 public void replaceFinalData(Map<String,String> datas) {
  if(datas==null) return;
  for(Row row:sheet) {
   for(Cell c:row) {
//    if(c.getCellType()!=Cell.CELL_TYPE_STRING) continue;
    String str = c.getStringCellValue().trim();
    if(str.startsWith("#")) {
     if(datas.containsKey(str.substring(1))) {
      c.setCellValue(datas.get(str.substring(1)));
     }
    }
   }
  }
 }
 /**
  *   Properties   ,      #   
  * @param prop
  */
 public void replaceFinalData(Properties prop) {
  if(prop==null) return;
  for(Row row:sheet) {
   for(Cell c:row) {
//    if(c.getCellType()!=Cell.CELL_TYPE_STRING) continue;
    String str = c.getStringCellValue().trim();
    if(str.startsWith("#")) {
     if(prop.containsKey(str.substring(1))) {
      c.setCellValue(prop.getProperty(str.substring(1)));
     }
    }
   }
  }
 }

 private void initTemplate() {
  sheet = wb.getSheetAt(0);
  initConfigData();
  lastRowIndex = sheet.getLastRowNum();
  curRow = sheet.createRow(curRowIndex);
 }
 /**
  *        
  */
 private void initConfigData() {
  boolean findData = false;
  boolean findSer = false;
  for(Row row:sheet) {
   if(findData) break;
   for(Cell c:row) {
//    if(c.getCellType()!=Cell.CELL_TYPE_STRING) continue;
    String str = c.getStringCellValue().trim();
    if(str.equals(SER_NUM)) {
     serColIndex = c.getColumnIndex();
     findSer = true;
    }
    if(str.equals(DATA_LINE)) {
     initColIndex = c.getColumnIndex();
     initRowIndex = row.getRowNum();
     curColIndex = initColIndex;
     curRowIndex = initRowIndex;
     findData = true;
     defaultStyle = c.getCellStyle();
     rowHeight = row.getHeightInPoints();
     initStyles();
     break;
    }
   }
  }
  if(!findSer) {
   initSer();
  }
 }
 /**
  *        
  */
 private void initSer() {
  for(Row row:sheet) {
   for(Cell c:row) {
//    if(c.getCellType()!=Cell.CELL_TYPE_STRING) continue;
    String str = c.getStringCellValue().trim();
    if(str.equals(SER_NUM)) {
     serColIndex = c.getColumnIndex();
    }
   }
  }
 }
 /**
  *        
  */
 private void initStyles() {
  styles = new HashMap<Integer, CellStyle>();
  for(Row row:sheet) {
   for(Cell c:row) {
//    if(c.getCellType()!=Cell.CELL_TYPE_STRING) continue;
    String str = c.getStringCellValue().trim();
    if(str.equals(DEFAULT_STYLE)) {
     defaultStyle = c.getCellStyle();
    }
    if(str.equals(STYLE)) {
     styles.put(c.getColumnIndex(), c.getCellStyle());
    }
   }
  }
 }
}

작업 도구 클래스

/**
 *              Excel  ,     Excel        List   
 *      BeanUtils        
 *        ,           ExcelReources        
 * Created by     [email protected] on 2016/10/29 0:15.
 */
public class ExcelUtil {
 private static ExcelUtil eu = new ExcelUtil();
 private ExcelUtil(){}

 public static ExcelUtil getInstance() {
  return eu;
 }
 /**
  *        Excel
  * @param template
  * @param objs
  * @param clz
  * @param isClasspath
  * @return
  */
 private ExcelTemplate handlerObj2Excel (String template, List objs, Class clz, boolean isClasspath) {
  ExcelTemplate et = ExcelTemplate.getInstance();
  try {
   if(isClasspath) {
    et.readTemplateByClasspath(template);
   } else {
    et.readTemplateByPath(template);
   }
   List<ExcelHeader> headers = getHeaderList(clz);
   Collections.sort(headers);
   //    
   et.createNewRow();
   for(ExcelHeader eh:headers) {
    et.createCell(eh.getTitle());
   }
   //   
   for(Object obj:objs) {
    et.createNewRow();
    for(ExcelHeader eh:headers) {
     //    Method m = clz.getDeclaredMethod(mn);
     //    Object rel = m.invoke(obj);
     et.createCell(BeanUtils.getProperty(obj,getMethodName(eh)));
    }
   }
  } catch (IllegalAccessException e) {
   e.printStackTrace();
  } catch (InvocationTargetException e) {
   e.printStackTrace();
  } catch (NoSuchMethodException e) {
   e.printStackTrace();
  }
  return et;
 }
 /**
  *              
  * @param eh
  * @return
  */
 private String getMethodName(ExcelHeader eh) {
  String mn = eh.getMethodName().substring(3);
  mn = mn.substring(0,1).toLowerCase()+mn.substring(1);
  return mn;
 }
 /**
  *       Excel    ,           ,    
  * @param datas            
  * @param template     
  * @param os    
  * @param objs     
  * @param clz      
  * @param isClasspath      classPath   
  */
 public void exportObj2ExcelByTemplate(Map<String,String> datas, String template, OutputStream os, List objs, Class clz, boolean isClasspath) {
  try {
   ExcelTemplate et = handlerObj2Excel(template, objs, clz, isClasspath);
   et.replaceFinalData(datas);
   et.wirteToStream(os);
   os.flush();
   os.close();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
 /**
  *       Excel    ,           ,           
  * @param datas            
  * @param template     
  * @param outPath     
  * @param objs     
  * @param clz      
  * @param isClasspath      classPath   
  */
 public void exportObj2ExcelByTemplate(Map<String,String> datas,String template,String outPath,List objs,Class clz,boolean isClasspath) {
  ExcelTemplate et = handlerObj2Excel(template, objs, clz, isClasspath);
  et.replaceFinalData(datas);
  et.writeToFile(outPath);
 }

 /**
  *       Excel    ,           ,    ,  Properties      
  * @param prop   Properties       
  * @param template     
  * @param os    
  * @param objs     
  * @param clz      
  * @param isClasspath      classPath   
  */
 public void exportObj2ExcelByTemplate(Properties prop, String template, OutputStream os, List objs, Class clz, boolean isClasspath) {
  ExcelTemplate et = handlerObj2Excel(template, objs, clz, isClasspath);
  et.replaceFinalData(prop);
  et.wirteToStream(os);
 }
 /**
  *       Excel    ,           ,           ,  Properties      
  * @param prop   Properties       
  * @param template     
  * @param outPath     
  * @param objs     
  * @param clz      
  * @param isClasspath      classPath   
  */
 public void exportObj2ExcelByTemplate(Properties prop,String template,String outPath,List objs,Class clz,boolean isClasspath) {
  ExcelTemplate et = handlerObj2Excel(template, objs, clz, isClasspath);
  et.replaceFinalData(prop);
  et.writeToFile(outPath);
 }

 private Workbook handleObj2Excel(List objs, Class clz) {
  Workbook wb = new HSSFWorkbook();
  try {
   Sheet sheet = wb.createSheet();
   Row r = sheet.createRow(0);
   List<ExcelHeader> headers = getHeaderList(clz);
   Collections.sort(headers);
   //   
   for(int i=0;i<headers.size();i++) {
    r.createCell(i).setCellValue(headers.get(i).getTitle());
   }
   //   
   Object obj = null;
   for(int i=0;i<objs.size();i++) {
    r = sheet.createRow(i+1);
    obj = objs.get(i);
    for(int j=0;j<headers.size();j++) {
     r.createCell(j).setCellValue(BeanUtils.getProperty(obj, getMethodName(headers.get(j))));
    }
   }
  } catch (IllegalAccessException e) {
   e.printStackTrace();
  } catch (InvocationTargetException e) {
   e.printStackTrace();
  } catch (NoSuchMethodException e) {
   e.printStackTrace();
  }
  return wb;
 }
 /**
  *      Excel,       ,      Excel    ,       
  * @param outPath     
  * @param objs     
  * @param clz     
  */
 public void exportObj2Excel(String outPath,List objs,Class clz) {
  Workbook wb = handleObj2Excel(objs, clz);
  FileOutputStream fos = null;
  try {
   fos = new FileOutputStream(outPath);
   wb.write(fos);
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    if(fos!=null) fos.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
 /**
  *      Excel,       ,      Excel    ,   
  * @param os    
  * @param objs     
  * @param clz     
  */
 public void exportObj2Excel(OutputStream os,List objs,Class clz) {
  try {
   Workbook wb = handleObj2Excel(objs, clz);
   wb.write(os);
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
 /**
  *          Excel       
  * @param path      path
  * @param clz     
  * @param readLine    ,        
  * @param tailLine       ,      ,      
  * @return
  */
 public List<Object> readExcel2ObjsByClasspath(String path,Class clz,int readLine,int tailLine) {
  Workbook wb = null;
  try {
   wb = new HSSFWorkbook(TemplateFileUtil.getTemplates(path));
   return handlerExcel2Objs(wb, clz, readLine,tailLine);
  } catch (IOException e) {
   e.printStackTrace();
  }
  return null;
 }
 /**
  *           Excel       
  * @param path       path
  * @param clz     
  * @param readLine    ,        
  * @param tailLine       ,      ,      
  * @return
  */
 public List<Object> readExcel2ObjsByPath(String path,Class clz,int readLine,int tailLine) {
  Workbook wb = null;
  try {
   wb = new HSSFWorkbook(TemplateFileUtil.getTemplates(path));
   return handlerExcel2Objs(wb, clz, readLine,tailLine);
  } catch (IOException e) {
   e.printStackTrace();
  }
  return null;
 }
 /**
  *          Excel       ,    0,    
  * @param path   
  * @param clz   
  * @return     
  */
 public List<Object> readExcel2ObjsByClasspath(String path,Class clz) {
  return this.readExcel2ObjsByClasspath(path, clz, 0,0);
 }
 /**
  *           Excel       ,    0,    
  * @param path   
  * @param clz   
  * @return     
  */
 public List<Object> readExcel2ObjsByPath(String path,Class clz) {
  return this.readExcel2ObjsByPath(path, clz,0,0);
 }

 private String getCellValue(Cell c) {
  String o = null;
  switch (c.getCellType()) {
   case Cell.CELL_TYPE_BLANK:
    o = ""; break;
   case Cell.CELL_TYPE_BOOLEAN:
    o = String.valueOf(c.getBooleanCellValue()); break;
   case Cell.CELL_TYPE_FORMULA:
    o = String.valueOf(c.getCellFormula()); break;
   case Cell.CELL_TYPE_NUMERIC:
    o = String.valueOf(c.getNumericCellValue()); break;
   case Cell.CELL_TYPE_STRING:
    o = c.getStringCellValue(); break;
   default:
    o = null;
    break;
  }
  return o;
 }

 private List<Object> handlerExcel2Objs(Workbook wb,Class clz,int readLine,int tailLine) {
  Sheet sheet = wb.getSheetAt(0);
  List<Object> objs = null;
  try {
   Row row = sheet.getRow(readLine);
   objs = new ArrayList<Object>();
   Map<Integer,String> maps = getHeaderMap(row, clz);
   if(maps==null||maps.size()<=0) throw new RuntimeException("    Excel      ,           ");
   for(int i=readLine+1;i<=sheet.getLastRowNum()-tailLine;i++) {
    row = sheet.getRow(i);
    Object obj = clz.newInstance();
    for(Cell c:row) {
     int ci = c.getColumnIndex();
     String mn = maps.get(ci).substring(3);
     mn = mn.substring(0,1).toLowerCase()+mn.substring(1);
     BeanUtils.copyProperty(obj,mn, this.getCellValue(c));
    }
    objs.add(obj);
   }
  } catch (InstantiationException e) {
   e.printStackTrace();
  } catch (IllegalAccessException e) {
   e.printStackTrace();
  } catch (InvocationTargetException e) {
   e.printStackTrace();
  }
  return objs;
 }

 private List<ExcelHeader> getHeaderList(Class clz) {
  List<ExcelHeader> headers = new ArrayList<ExcelHeader>();
  Method[] ms = clz.getDeclaredMethods();
  for(Method m:ms) {
   String mn = m.getName();
   if(mn.startsWith("get")) {
    if(m.isAnnotationPresent(ExcelResources.class)) {
     ExcelResources er = m.getAnnotation(ExcelResources.class);
     headers.add(new ExcelHeader(er.title(),er.order(),mn));
    }
   }
  }
  return headers;
 }

 private Map<Integer,String> getHeaderMap(Row titleRow,Class clz) {
  List<ExcelHeader> headers = getHeaderList(clz);
  Map<Integer,String> maps = new HashMap<Integer, String>();
  for(Cell c:titleRow) {
   String title = c.getStringCellValue();
   for(ExcelHeader eh:headers) {
    if(eh.getTitle().equals(title.trim())) {
     maps.put(c.getColumnIndex(), eh.getMethodName().replace("get","set"));
     break;
    }
   }
  }
  return maps;
 }
}

Excel 템 플 릿 파일
템 플 릿 파일 을 만 듭 니 다.다음 그림:
POI导出Excel的模板文件
POI 에서 Excel 템 플 릿 파일 내 보 내기
테스트 클래스

@SpringBootTest
@RunWith(SpringRunner.class)
public class ExportExcelTest {

 @Test
 public void test() throws Exception {
  List<WebDto> list = new ArrayList<WebDto>();
  list.add(new WebDto("   ", "http://www.zslin.com", "admin", "111111", 555));
  list.add(new WebDto("    ", "http://basic.zslin.com", "admin", "111111", 111));
  list.add(new WebDto("   ", "http://school.zslin.com", "admin", "222222", 333));

  Map<String, String> map = new HashMap<String, String>();
  map.put("title", "     ");
  map.put("total", list.size()+"  ");
  map.put("date", getDate());

  ExcelUtil.getInstance().exportObj2ExcelByTemplate(map, "web-info-template.xls", new FileOutputStream("D:/temp/out.xls"),
    list, WebDto.class, true);
 }

 private String getDate() {
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd ");
  return sdf.format(new Date());
 }
}

테스트 방법 을 실행 한 후 D:/temp/out.xls 파일 을 보면 다음 그림 과 같은 내용 을 볼 수 있 습 니 다.
POI Excel 결과 도 내 보 내기
POI导出Excel结果图
다운로드 주소:Springboot_jb51.rar
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기