Skip to content

Commit

Permalink
add excelDemo
Browse files Browse the repository at this point in the history
  • Loading branch information
quding committed Feb 23, 2017
1 parent 22c8c69 commit 229f5fe
Show file tree
Hide file tree
Showing 7 changed files with 375 additions and 0 deletions.
44 changes: 44 additions & 0 deletions excel-Demo/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>cn.mrdear.poi</groupId>
<artifactId>poi</artifactId>
<version>1.0-SNAPSHOT</version>

<dependencies>
<!--poi start-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
</dependencies>


<build>
<plugins>
<!--编译版本-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
171 changes: 171 additions & 0 deletions excel-Demo/src/main/java/cn/mrdear/excel/core/Excel.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
package cn.mrdear.excel.core;

import cn.mrdear.excel.util.BeanUtils;
import com.sun.tools.javac.comp.Todo;
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 java.io.*;
import java.util.*;

/**
* 工具类入口
* @author Niu Li
* @since 2017/2/23
*/
public class Excel {

//该表格的工作本
private Workbook workbook;

/**
* 控制表头,其中键为对应DTO的字段,值为表头显示内容
*/
private LinkedHashMap<String,String> headers;
/**
* 具体表内容,只接受DTO
*/
private List<?> contents;

/**
* 入口函数
* @param headers 表单头部
* @param content 表单内容DTO
* @return this表单对象
*/
public static Excel from(LinkedHashMap<String,String> headers,List<?> content){
return new Excel(headers,content);
}

/**
* 在此workbook中增加另一个sheet
* @param headers 新sheet的表头
* @param content 新sheet的内容
* @return this
*/
public Excel andForm(LinkedHashMap<String,String> headers,List<?> content){
this.headers = headers;
this.contents = content;
return this;
}


/**
* 端点方法,生成最终的表单
* @return this
*/
public Excel build(String sheetName){
//创建字表
Sheet sheet = sheetName == null ? workbook.createSheet() : workbook.createSheet(sheetName);
//创建表头
int rowNum = 0;
Row headerRow = sheet.createRow(rowNum++);
List<String> headers = new ArrayList<>(this.headers.keySet());//表头
List<String> values = new ArrayList<>(this.headers.values());//对应值
for (int i = 0; i < headers.size(); i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(values.get(i)==null?headers.get(i):values.get(i));
}
//构造表单内容
try {
for (Object content : contents) {
Map<String,Object> contentMap = BeanUtils.bean2Map(content);
Row current = sheet.createRow(rowNum++);
for (int i = 0; i < headers.size(); i++) {
Cell cell = current.createCell(i);
Object obj = contentMap.get(headers.get(i));
if (obj == null) {
obj = "";
}
if (obj instanceof String) {
cell.setCellValue((String) obj);
} else if (obj instanceof Integer) {
cell.setCellValue((Integer) obj);
} else if (obj instanceof Long) {
cell.setCellValue((Long) obj);
} else if (obj instanceof Double) {
cell.setCellValue((Double) obj);
} else if (obj instanceof Date) {
cell.setCellValue((Date) obj);
} else if (obj instanceof Boolean) {
cell.setCellValue((Boolean) obj);
} else {
throw new IllegalArgumentException("unsupported cell type");
}
}
}
} catch (IllegalAccessException e) {
// todo 替换为自己项目的日志
e.printStackTrace();
}
//设置样式

return this;
}
/**
* 私有化构造函数
*/
private Excel(LinkedHashMap<String, String> headers, List<?> contents) {
this.headers = headers;
this.contents = contents;
}

/**
* 调用该方法后,此workbook则写入关闭
* @param dirIncludedFileName 最终生成文件名称
*/
public void write(String dirIncludedFileName){
try {
File file = new File(dirIncludedFileName);
FileOutputStream os = new FileOutputStream(file);
workbook.write(os);
os.close();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (workbook != null) workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

// todo 测试在写入后关闭对其的影响
/**
* 结果写到一个输出流中
* @param os 目标流
*/
public void write(OutputStream os) {
try {
workbook.write(os);
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}


/**
* 链式调用设置生成文档格式
* @param type 指定格式
* @return this
*/
public Excel excelType(ExcelType type){
workbook = type == ExcelType.XLS?new HSSFWorkbook():new XSSFWorkbook();
return this;
}

/**
* 定义excel格式
*/
public static enum ExcelType{
XLS,
XLSX
}

}
41 changes: 41 additions & 0 deletions excel-Demo/src/main/java/cn/mrdear/excel/util/BeanUtils.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package cn.mrdear.excel.util;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
* 对bean一些转换方法
* @author Niu Li
* @since 2017/2/23
*/
public class BeanUtils {

/**
* 转换bean为map
* @param source 要转换的bean
* @param <T> bean类型
* @return 转换结果
*/
public static <T> Map<String,Object> bean2Map(T source) throws IllegalAccessException {
Map<String,Object> result = new HashMap<>();

Class<?> sourceClass = source.getClass();
//拿到所有的字段,不包括继承的字段
Field[] sourceFiled = sourceClass.getDeclaredFields();
for (Field field : sourceFiled) {
field.setAccessible(true);//设置可访问,不然拿不到private
//配置了注解的话则使用注解名称,作为header字段
FiledName filedName = field.getAnnotation(FiledName.class);
if (filedName == null){
result.put(field.getName(),field.get(source));
}else {
if (filedName.Ignore()) continue;
result.put(filedName.value(),field.get(source));
}
}
return result;
}

}

24 changes: 24 additions & 0 deletions excel-Demo/src/main/java/cn/mrdear/excel/util/FiledName.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package cn.mrdear.excel.util;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
* 自定义字段名
* @author Niu Li
* @since 2017/2/23
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
public @interface FiledName {
/**
* 字段名
*/
String value() default "";
/**
* 是否忽略
*/
boolean Ignore() default false;
}
16 changes: 16 additions & 0 deletions excel-Demo/src/test/java/cn/mrdear/excel/BeanUtilTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package cn.mrdear.excel;

import cn.mrdear.excel.util.BeanUtils;

/**
* @author Niu Li
* @since 2017/2/23
*/
public class BeanUtilTest {
public static void main(String[] args) throws IllegalAccessException {
Demo demo = new Demo();
demo.setUserName("111");
demo.setPassWord("222");
System.out.println(BeanUtils.bean2Map(demo));
}
}
37 changes: 37 additions & 0 deletions excel-Demo/src/test/java/cn/mrdear/excel/Demo.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package cn.mrdear.excel;

import cn.mrdear.excel.util.FiledName;

/**
* @author Niu Li
* @since 2017/2/23
*/
class Demo {

public Demo(String username, String password) {
this.userName = username;
this.passWord = password;
}
public Demo() {
}
//fildName字段需要和header对应
@FiledName(value = "username")
private String userName;
private String passWord;

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getPassWord() {
return passWord;
}

public void setPassWord(String passWord) {
this.passWord = passWord;
}
}
42 changes: 42 additions & 0 deletions excel-Demo/src/test/java/cn/mrdear/excel/ExcelTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package cn.mrdear.excel;

import cn.mrdear.excel.core.Excel;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
* @author Niu Li
* @since 2017/2/23
*/
public class ExcelTest {
LinkedHashMap<String,String> headers;

@Before
public void init() {
headers = new LinkedHashMap<>();
headers.put("username","用户名");
headers.put("passWord", "密码");
}

@Test
public void testMake() {
List<Demo> content = new ArrayList<>();
Demo demo1 = new Demo("1","1");
Demo demo2 = new Demo("2","2");
Demo demo3 = new Demo("3","3");
Demo demo4 = new Demo("4","4");
content.add(demo1);
content.add(demo2);
content.add(demo3);
content.add(demo4);

Excel.from(headers,content)
.excelType(Excel.ExcelType.XLS)
.build("niuli")
.write("/tmp/niuli.xls");
}
}

0 comments on commit 229f5fe

Please sign in to comment.