使用POI导出excel进阶篇

进阶篇就是涉及到合并单元格了。就是某一列相同的单元格需要合并为一个,并分为多个sheet。

效果如图:

 

直接上代码,需要提供的数据自己搞,传到工具类里面就好。

JcExcelVoSuper.java

 

 

 

package com.jimmy.demo.poi;

import java.util.HashMap;
import java.util.List;
public class JcExcelVoSuper {
private String courseName;
private String jiaocaiName;
private String title;
private HashMap<Integer,String> map=new HashMap<Integer,String>();

private List<JcExcelVo> voList;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}

public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public String getJiaocaiName() {
return jiaocaiName;
}
public void setJiaocaiName(String jiaocaiName) {
this.jiaocaiName = jiaocaiName;
}
public HashMap<Integer, String> getMap() {
return map;
}
public void setMap(HashMap<Integer, String> map) {
this.map = map;
}
public List<JcExcelVo> getVoList() {
return voList;
}
public void setVoList(List<JcExcelVo> voList) {
this.voList = voList;
}

}

JcExcelVo.java

package com.jimmy.demo.poi;

import java.util.HashMap;
import java.util.List;

public class JcExcelVo {
private Integer gradeId;
private List<JcExcelSub> excelSubList;
public List<JcExcelSub> getExcelSubList() {
return excelSubList;
}
public void setExcelSubList(List<JcExcelSub> excelSubList) {
this.excelSubList = excelSubList;
}
public Integer getGradeId() {
return gradeId;
}
public void setGradeId(Integer gradeId) {
this.gradeId = gradeId;
}
}

JcExcelSub.java

package com.jimmy.demo.poi;
public class JcExcelSub {
private String p;// P2(2,"暑假"), P3(3,"秋季"), P4(4,"寒假"), P1(1,"春季");
private Integer lessonNo;
private String lessonName;
private String knowledge;
public String getP() {
return p;
}
public void setP(String p) {
this.p = p;
}
public Integer getLessonNo() {
return lessonNo;
}
public void setLessonNo(Integer lessonNo) {
this.lessonNo = lessonNo;
}
public String getLessonName() {
return lessonName;
}
public void setLessonName(String lessonName) {
this.lessonName = lessonName;
}
public String getKnowledge() {
return knowledge;
}
public void setKnowledge(String knowledge) {
this.knowledge = knowledge;
}

}

JcExcelUtil.java

package com.aixuexi.util;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFComment;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPalette;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
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.hssf.util.CellRangeAddress;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Row;

import com.aixuexi.vo.JcExcelVo;
import com.aixuexi.vo.JcExcelVoSuper;

/**
* 利用开源组件POI3.0.2动态导出EXCEL文档 转载时请保留以下信息,注明出处!
*
* @version v1.0
* @param <T>
* 应用泛型,代表任意一个符合javabean风格的类
* 注意这里为了简单起见,boolean型的属性xxx的get器方式为getXxx(),而不是isXxx()
* byte[]表jpg格式的图片数据
*/
public class JcExcelUtil<T> {

/**
* 这是一个通用的方法,利用了JAVA的反射机制,可以将放置在JAVA集合中并且符号一定条件的数据以EXCEL 的形式输出到指定IO设备上
*
* @param title
* 表格标题名
* @param headers
* 表格属性列名数组
* @param dataset
* 需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的
* javabean属性的数据类型有基本数据类型及String,Date,byte[](图片数据)
* @param out
* 与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
* @param pattern
* 如果有时间数据,设定输出格式。默认为"yyy-MM-dd"
*/
@SuppressWarnings("unchecked")
public void exportExcel(JcExcelVoSuper excelSuper, OutputStream out) {


String fileName ="导出数据";//设置导出的文件名称

// 声明一个工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
List<JcExcelVo> voList=excelSuper.getVoList();
HashMap<Integer,String> map=excelSuper.getMap();
int count=0;
for (JcExcelVo vo:voList) {

String gradeName="";
Iterator itName = map.entrySet().iterator();
while (itName.hasNext()) {
Map.Entry entry = (Map.Entry) itName.next();
Object key = entry.getKey();
Object value = entry.getValue();
if (vo.getGradeId()==(Integer)key) {
gradeName=(String) value;
}
}
// 生成一个表格
HSSFSheet sheet = workbook.createSheet(gradeName);
// 设置表格默认列宽度为15个字节
sheet.setDefaultColumnWidth(30);

// sheet.setDefaultRowHeightInPoints(25f);
/* CellRangeAddress cra = new CellRangeAddress(0, 3, 3, 9);*/
CellRangeAddress lineOne=new CellRangeAddress(0, 0, 0, 3);
// 在sheet里增加合并单元格
sheet.addMergedRegion(lineOne);
// 生成一个样式
HSSFCellStyle style = workbook.createCellStyle();
// 设置这些样式
/* style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);*/
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 生成一个字体
// 生成另一个字体
HSSFFont font= workbook.createFont();
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 把字体应用到当前的样式
style.setFont(font);
// 生成并设置另一个样式
HSSFCellStyle style2 = workbook.createCellStyle();
/*style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);*/
style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
// 生成另一个字体
HSSFFont font2 = workbook.createFont();
font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
// 把字体应用到当前的样式
style2.setFont(font2);
// 生成并设置另一个样式
HSSFCellStyle style3 = workbook.createCellStyle();
style3.setFillForegroundColor(HSSFColor.GOLD.index);
style3.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style3.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style3.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style3.setBorderRight(HSSFCellStyle.BORDER_THIN);
style3.setBorderTop(HSSFCellStyle.BORDER_THIN);
style3.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style3.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
// 生成另一个字体
HSSFFont font4 = workbook.createFont();
font4.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 把字体应用到当前的样式
style3.setFont(font4);

// 声明一个画图的顶级管理器
HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
// 定义注释的大小和位置,详见文档
HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(
0, 0, 0, 0, (short) 4, 2, (short) 6, 5));
// 设置注释内容
comment.setString(new HSSFRichTextString("可以在POI中添加注释!"));
// 设置注释作者,当鼠标移动到单元格上是可以在状态栏中看到该内容.
comment.setAuthor("wangjing5");
String[] headers = { "学期", "讲次数", "讲次名称", "知识点" };

HSSFRow row11 = sheet.createRow(0);
HSSFCell cell22 = row11.createCell(0);
cell22.setCellStyle(style3);
HSSFRichTextString text22 = new HSSFRichTextString(excelSuper.getTitle()+gradeName+"目录");
cell22.setCellValue(text22);

HSSFRow row = sheet.createRow(1);
for (int i = 0; i < headers.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellStyle(style);
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
cell.setCellValue(text);
}

int flag=0;
HSSFPalette customPalette = workbook.getCustomPalette();
customPalette.setColorAtIndex(HSSFColor.GREEN.index, (byte) 235, (byte) 241, (byte) 222);
HSSFCellStyle styleGreen = workbook.createCellStyle();
styleGreen.setFillForegroundColor(HSSFColor.GREEN.index);
styleGreen.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
styleGreen.setBorderBottom(HSSFCellStyle.BORDER_THIN);
styleGreen.setBorderLeft(HSSFCellStyle.BORDER_THIN);
styleGreen.setBorderRight(HSSFCellStyle.BORDER_THIN);
styleGreen.setBorderTop(HSSFCellStyle.BORDER_THIN);
styleGreen.setAlignment(HSSFCellStyle.ALIGN_CENTER);
styleGreen.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

customPalette.setColorAtIndex(HSSFColor.BLUE_GREY.index, (byte) 218, (byte) 238, (byte) 243);
HSSFCellStyle styleBlue = workbook.createCellStyle();
styleBlue.setFillForegroundColor(HSSFColor.BLUE_GREY.index);
styleBlue.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
styleBlue.setBorderBottom(HSSFCellStyle.BORDER_THIN);
styleBlue.setBorderLeft(HSSFCellStyle.BORDER_THIN);
styleBlue.setBorderRight(HSSFCellStyle.BORDER_THIN);
styleBlue.setBorderTop(HSSFCellStyle.BORDER_THIN);
styleBlue.setAlignment(HSSFCellStyle.ALIGN_CENTER);
styleBlue.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

customPalette.setColorAtIndex(HSSFColor.BROWN.index, (byte) 253, (byte) 233, (byte) 217);
HSSFCellStyle styleYello = workbook.createCellStyle();
styleYello.setFillForegroundColor(HSSFColor.BROWN.index);
styleYello.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
styleYello.setBorderBottom(HSSFCellStyle.BORDER_THIN);
styleYello.setBorderLeft(HSSFCellStyle.BORDER_THIN);
styleYello.setBorderRight(HSSFCellStyle.BORDER_THIN);
styleYello.setBorderTop(HSSFCellStyle.BORDER_THIN);
styleYello.setAlignment(HSSFCellStyle.ALIGN_CENTER);
styleYello.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

customPalette.setColorAtIndex(HSSFColor.PINK.index, (byte) 228, (byte) 223, (byte) 236);
HSSFCellStyle stylePurple = workbook.createCellStyle();
stylePurple.setFillForegroundColor(HSSFColor.PINK.index);
stylePurple.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
stylePurple.setBorderBottom(HSSFCellStyle.BORDER_THIN);
stylePurple.setBorderLeft(HSSFCellStyle.BORDER_THIN);
stylePurple.setBorderRight(HSSFCellStyle.BORDER_THIN);
stylePurple.setBorderTop(HSSFCellStyle.BORDER_THIN);
stylePurple.setAlignment(HSSFCellStyle.ALIGN_CENTER);
stylePurple.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

// 遍历集合数据,产生数据行
Iterator<T> it = (Iterator<T>) vo.getExcelSubList().iterator();
int index = 1;
while (it.hasNext()) {
index++;
row = sheet.createRow(index);
T t = (T) it.next();
// 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
Field[] fields = t.getClass().getDeclaredFields();
for (short i = 0; i < fields.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellStyle(style2);
Field field = fields[i];
String fieldName = field.getName();

String getMethodName = "get"
+ fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1);
try {
Class<?> tCls = t.getClass();
Method getMethod = tCls.getMethod(getMethodName,
new Class[] {});

Object value = getMethod.invoke(t, new Object[] {});


Method getMethod2 = tCls.getMethod("getP",
new Class[] {});

Object value2 = getMethod2.invoke(t, new Object[] {});

if (value2.toString().equals("暑假")) {
flag=1;
}else if(value2.toString().equals("春季")){
flag=2;
}else if(value2.toString().equals("寒假")){
flag=3;
}else{
flag=4;
}





// 判断值的类型后进行强制类型转换
String textValue = null;
if (value instanceof Date) {
Date date = (Date) value;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
textValue = sdf.format(date);
} else if (value instanceof byte[]) {
// 有图片时,设置行高为60px;
row.setHeightInPoints(60);
// 设置图片所在列宽度为80px,注意这里单位的一个换算
sheet.setColumnWidth(i, (int) (35.7 * 80));
// sheet.autoSizeColumn(i);
byte[] bsValue = (byte[]) value;
HSSFClientAnchor anchor = new HSSFClientAnchor(0,
0, 1023, 255, (short) 6, index, (short) 6,
index);
anchor.setAnchorType(2);
patriarch.createPicture(anchor, workbook
.addPicture(bsValue,
HSSFWorkbook.PICTURE_TYPE_JPEG));
} else {
// 其它数据类型都当作字符串简单处理
textValue = value.toString();

if (textValue.length()>30) {
sheet.setColumnWidth(2, 30 * 256);
sheet.setColumnWidth(3, 150 * 256);
}
}
// 如果不是图片数据,就利用正则表达式判断textValue是否全部由数字组成
if (textValue != null) {
Pattern p = Pattern.compile("^//d+(//.//d+)?$");
Matcher matcher = p.matcher(textValue);
if (matcher.matches()) {
// 是数字当作double处理
cell.setCellValue(Double.parseDouble(textValue));
if (flag==1) {
cell.setCellStyle(styleGreen);
}else if(flag==2){
cell.setCellStyle(styleBlue);
}else if(flag==3){
cell.setCellStyle(styleYello);
}else{
cell.setCellStyle(stylePurple);
}

} else {
HSSFRichTextString richString = new HSSFRichTextString(
textValue);
if (flag==1) {
cell.setCellStyle(styleGreen);
}else if(flag==2){
cell.setCellStyle(styleBlue);
}else if(flag==3){
cell.setCellStyle(styleYello);
}else{
cell.setCellStyle(stylePurple);
}
cell.setCellValue(richString);
}
}
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// 清理资源
}
}

}
if (vo.getExcelSubList().size()>0) {
addMergedRegionA(sheet, 0, 2, sheet.getLastRowNum(), workbook);
}

}
try {
workbook.write(out);
out.close();
} catch (IOException e) {
e.printStackTrace();
}

}

public void outExcel(JcExcelVoSuper excelSuper,OutputStream o) {
exportExcel(excelSuper,o);
}

/**
* 合并单元格
*
* @param sheet
* 要合并单元格的excel 的sheet
* @param cellLine
* 要合并的列
* @param startRow
* 要合并列的开始行
* @param endRow
* 要合并列的结束行
*/
private static void addMergedRegionA(HSSFSheet sheet, int cellLine,
int startRow, int endRow, HSSFWorkbook workBook) {

// 获取第一行的数据,以便后面进行比较
Row r=sheet.getRow(startRow);
String s_will = r.getCell(cellLine)
.getStringCellValue();

int count = 0;
boolean flag = false;
for (int i = 3; i <= endRow; i++) {
String s_current = sheet.getRow(i).getCell(0).getStringCellValue();

if (s_will.equals(s_current)) {
s_will = s_current;
if (flag) {
HSSFRow row = sheet.getRow(startRow - count);
String cellValueTemp = sheet.getRow(startRow - count)
.getCell(0).getStringCellValue();
HSSFCellStyle style=sheet.getRow(startRow - count).getCell(0).getCellStyle();
CellRangeAddress lineOne2=new CellRangeAddress(startRow - count, startRow, cellLine, cellLine);
// 在sheet里增加合并单元格
sheet.addMergedRegion(lineOne2);
HSSFCell cell = row.createCell(0);
cell.setCellValue(cellValueTemp); // 跨单元格显示的数据
cell.setCellStyle(style);
count = 0;
flag = false;

}
startRow = i;
count++;
} else {
flag = true;
s_will = s_current;
}
if (i == endRow&&s_will.equals(s_current)) {
CellRangeAddress lineOne2=new CellRangeAddress(startRow - count, startRow, cellLine, cellLine);
sheet.addMergedRegion(lineOne2);
}else{
// 由于上面循环中合并的单元放在有下一次相同单元格的时候做的,所以最后如果几行有相同单元格则要运行下面的合并单元格。
if (i == endRow && count > 0) {
sheet.addMergedRegion(new CellRangeAddress(endRow - count,
endRow, cellLine, cellLine));
String cellValueTemp = sheet.getRow(startRow - count)
.getCell(0).getStringCellValue();
HSSFCellStyle style=sheet.getRow(startRow - count).getCell(0).getCellStyle();
HSSFRow row = sheet.getRow(startRow - count);
HSSFCell cell = row.createCell(0);
cell.setCellValue(cellValueTemp); // 跨单元格显示的数据
cell.setCellStyle(style);
}
}
}

}
}

Data.java只有关键代码

 

JcExcelVoSuper excelSuper=new JcExcelVoSuper();
ExtendedAttribute attr=extendedAttributeService.load(course.getJiaocai());
SubjectProduct sp=subjectProductService.listById(course.getSubjectProductId());
excelSuper.setJiaocaiName(attr.getName());
excelSuper.setCourseName(course.getName());
excelSuper.setTitle(sp.getName());
//获取到年级id
Integer[] ids = new Integer[course.getCourseDetailList().size()];
int index = 0;
for (CourseDetail detail : course.getCourseDetailList()) {
ids[index++] = detail.getGrade();
}

List<Integer> list = new LinkedList<Integer>();
for (int i = 0; i < ids.length; i++) {
if (!list.contains(ids[i])) {
list.add(ids[i]);
}
}
ids = (Integer[]) list.toArray(new Integer[list.size()]);
List<Grade> gradeList = gradeService.listByIds(ids);
//生成N个年级
List<JcExcelVo> voList=new ArrayList<JcExcelVo>();
for (Grade gg:gradeList) {

JcExcelVo vo=new JcExcelVo();
vo.setGradeId(gg.getId());
//循环N次插入
List<JcExcelSub> subList=new ArrayList<JcExcelSub> ();//N个sublist
for (CourseDetail detail:course.getCourseDetailList()) {//16次循环
if (gg.getId()==detail.getGrade()) {
for (CourseDetailLesson detailLesson:detail.getDetailLessons()) {
JcExcelSub sub=new JcExcelSub();
sub.setP(detail.getPeriod().getName());
sub.setLessonName(detailLesson.getLessonName());
sub.setLessonNo(detailLesson.getSort());
List<String> temp=new ArrayList<String>();
for (Knowledge know:detailLesson.getKnowledges()) {
for (Knowledge know2:know.getChildren()) {
for (Knowledge know3:know2.getChildren()) {
temp.add(know3.getText());
}
}
}
String join = StringUtils.join(temp, "、");
sub.setKnowledge(join);
subList.add(sub);
}
}
}
vo.setExcelSubList(subList);
voList.add(vo);
}
excelSuper.setVoList(voList);
HashMap<Integer,String> map=new HashMap<Integer,String>();
for (Grade grade:gradeList) {
map.put(grade.getId(),grade.getName());
}
excelSuper.setMap(map);
JcExcelUtil excelUtil=new JcExcelUtil();
String contentType = "application/vnd.ms-excel";//定义导出文件的格式的字符串
response.setContentType(contentType);//设置导出文件格式
String excelName=excelSuper.getCourseName()+excelSuper.getJiaocaiName()+"教材计划";
String recommendedName = new String(excelName.getBytes(),"iso_8859_1");//设置文件名称的编码格式
response.setHeader("Content-Disposition", "attachment; filename=" + recommendedName+".xls");//
ServletOutputStream outputStream = response.getOutputStream();
excelUtil.outExcel(excelSuper,outputStream);
return ;

posted @ 2016-03-21 21:47  煮海焚天  阅读(561)  评论(0编辑  收藏  举报