java中使用poi导出excel表格数据并且可以手动修改导出路径

时间:2023-12-16 08:53:32

  在我们开发项目中,很多时候会提出这样的需求:将前端的某某数据以excel表格导出,今天就给大家写一个简单的模板。

  这里我们选择使用poi导出excel:

  第一步:导入需要的jar包到 lib 文件夹下

  aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQoAAAEKCAIAAABlqYyeAAATa0lEQVR4nO2dXchsVR2H34u87OOmIwZ2zlFJRSrDj3I0MQoCyVAQoYjsUM2B0ArK7oxAj1kXno3QB0khRB8qIp6OOxE9QiBEFFEGlSPU6eKIvQgFHbOrt4uZ2bM+/v+1P2a/e6219/MwF++7Zq81a2bWb/bas/cza2cPABR2YncAIF2IB4AK8QBQ6R6P187+78YnXrr04Rff8YM/LG+3PvXrz/zmz9W/lz784o1PvPTa2Td67C7AkHSPx30v/P3aU7ur2/O71z6/++jT9z/zwo+Wf69up3aP/erlHrsLMCQd43H6329c+NjfZs+9eujEmcMnXzl04pXDJ1459ulLHv3G1YdPnDl88syhE2cOnzgzO/XPC3720ul//bffTmdJOd+ZFYsOFRfFrGNN2JaO8Tj61F+uPnl69uyr5u3+2857/K5LnMKrT54++os/9tvpLCEeGdIxHlf88Hdf+evrzu3sy199/R/3++Xv+/4L/XY6SzrHA+LRMR7nfvvUZU+edm7fvPXAI18+ePHDv3fKD9z3y347nSXEI0M6xuMtd58858jxc44cP+fIA+s/jh+75cAjdx580413GOUPnHPk+JvnD0ptlPOdFethsynZ2ZmXm81mRVnMqtL1Vkat8AbBlgt348WqJXPLbj13ys0O+S1ohcsOrdsUOre8u5y71aAHOsbjoZs++OBHZ87tnlsO/PyOg1+6+t1O+b0f/oDXQDl33027pJyvB4Dxxi/Hz7J4M2gabaC2vNl4VizssSjTrudmFtcbmfuR6vH8ZtdsurQo5ustNm0vExPuM3SkYzzKm645+9hnnds9Nx/4yR0Hnz16m1P+vRve69X3ZhpuiTluZsag8P+u26BRy4tiZibMrFB9qIut6e075WZ/bWbFIjT1shPr7T/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Wu+90BDT4mIrvk+xEP+cRFf7BbjYVRQAtD4oLrl6sho6KkSa11zXxxvFw9BH7dHbzkPiN1SPAT93UYsNudmvl3bUFJHQ0+VOK65JI633HuIa6Irx7We2C3vPcSDfbvTFutfPDGfif/gDSR1NPRUGb1rngOM/1QZvWueAZw0T5bRu+Zpg4aeNrjmACroUAAqxANAhXgAqBAPABXiAaCyisfz5f3iLW7nAOLyf7aC8t3fr/v3AAAAAElFTkSuQmCC" alt="" />

   jar包下载路径:http://download.csdn.net/download/pumpkin09/7077011

  第二步:添加poi导出工具类

    

 package com.yjd.admin.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.Collection;
import java.util.Date;
import java.util.Iterator;
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.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.HSSFColor; /**
* 利用开源组件POI3.0.2动态导出EXCEL文档 转载时请保留以下信息,注明出处!
*
* @author leno
* @version v1.0
* @param <T>
* 应用泛型,代表任意一个符合javabean风格的类
* 注意这里为了简单起见,boolean型的属性xxx的get器方式为getXxx(),而不是isXxx()
* byte[]表jpg格式的图片数据
*/
public class ExportExcel<T> {
public void exportExcel(Collection<T> dataset, OutputStream out) {
exportExcel("测试POI导出EXCEL文档", null, dataset, out, "yyyy-MM-dd");
} public void exportExcel(String[] headers, Collection<T> dataset,
OutputStream out) {
exportExcel("测试POI导出EXCEL文档", headers, dataset, out, "yyyy-MM-dd");
} public void exportExcel(String[] headers, Collection<T> dataset,
OutputStream out, String pattern) {
exportExcel("测试POI导出EXCEL文档", headers, dataset, out, pattern);
} /**
* 这是一个通用的方法,利用了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(String title, String[] headers,
Collection<T> dataset, OutputStream out, String pattern) {
// 声明一个工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
// 生成一个表格
HSSFSheet sheet = workbook.createSheet(title);
// 设置表格默认列宽度为15个字节
sheet.setDefaultColumnWidth((short) 15);
// 生成一个样式
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.setColor(HSSFColor.VIOLET.index);
font.setFontHeightInPoints((short) 12);
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);
// 声明一个画图的*管理器
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("leno");
// 产生表格标题行
HSSFRow row = sheet.createRow(0);
for (short i = 0; i < headers.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellStyle(style);
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
// 遍历集合数据,产生数据行
Iterator<T> it = dataset.iterator();
int index = 0;
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[] {});
// 判断值的类型后进行强制类型转换
String textValue = null;
// if (value instanceof Integer) {
// int intValue = (Integer) value;
// cell.setCellValue(intValue);
// } else if (value instanceof Float) {
// float fValue = (Float) value;
// textValue = new HSSFRichTextString(
// String.valueOf(fValue));
// cell.setCellValue(textValue);
// } else if (value instanceof Double) {
// double dValue = (Double) value;
// textValue = new HSSFRichTextString(
// String.valueOf(dValue));
// cell.setCellValue(textValue);
// } else if (value instanceof Long) {
// long longValue = (Long) value;
// cell.setCellValue(longValue);
// }
if (value instanceof Boolean) {
boolean bValue = (Boolean) value;
textValue = "男";
if (!bValue) {
textValue = "女";
}
} else if (value instanceof Date) {
Date date = (Date) value;
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
textValue = sdf.format(date);
} else if (value instanceof byte[]) {
// 有图片时,设置行高为60px;
row.setHeightInPoints(60);
// 设置图片所在列宽度为80px,注意这里单位的一个换算
sheet.setColumnWidth(i, (short) (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();
}
// 如果不是图片数据,就利用正则表达式判断textValue是否全部由数字组成
if (textValue != null) {
Pattern p = Pattern.compile("^//d+(//.//d+)?$");
Matcher matcher = p.matcher(textValue);
if (matcher.matches()) {
// 是数字当作double处理
cell.setCellValue(Double.parseDouble(textValue));
} else {
HSSFRichTextString richString = new HSSFRichTextString(
textValue);
HSSFFont font3 = workbook.createFont();
font3.setColor(HSSFColor.BLUE.index);
richString.applyFont(font3);
cell.setCellValue(richString);
}
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} finally {
// 清理资源
}
}
}
try {
workbook.write(out);
} catch (IOException e) {
e.printStackTrace();
}
} }

  第三步:由于我使用的的spring-mvc框架,所以在Controller调用上面的工具类ExportExcel

 

 package com.yjd.admin.vo;

 import java.util.Date;

 public class P2pLoanPlanVo {
private Date repayDate;
private double repayAmount;
private Integer repayDays;
private Integer repayYqDays;
private Double lateAmount;
private String isPosPaid;
private String statusName;
private String isSysPay;
public Date getRepayDate() {
return repayDate;
}
public void setRepayDate(Date repayDate) {
this.repayDate = repayDate;
}
public double getRepayAmount() {
return repayAmount;
}
public void setRepayAmount(double repayAmount) {
this.repayAmount = repayAmount;
}
public Integer getRepayDays() {
return repayDays;
}
public void setRepayDays(Integer repayDays) {
this.repayDays = repayDays;
}
public Integer getRepayYqDays() {
return repayYqDays;
}
public void setRepayYqDays(Integer repayYqDays) {
this.repayYqDays = repayYqDays;
}
public Double getLateAmount() {
return lateAmount;
}
public void setLateAmount(Double lateAmount) {
this.lateAmount = lateAmount;
}
public String getIsPosPaid() {
return isPosPaid;
}
public void setIsPosPaid(String isPosPaid) {
this.isPosPaid = isPosPaid;
}
public String getStatusName() {
return statusName;
}
public void setStatusName(String statusName) {
this.statusName = statusName;
}
public String getIsSysPay() {
return isSysPay;
}
public void setIsSysPay(String isSysPay) {
this.isSysPay = isSysPay;
} }
 /**
* 导出excel数据
* @param id
* @param m
* @return
*/
@RequestMapping("/exportExcel")
public void exportExcel(@RequestParam("id") Integer id, Model m,HttpServletRequest req, HttpServletResponse resp) {
try { ExportExcel<P2pLoanPlanVo> ex = new ExportExcel<P2pLoanPlanVo>();
String[] headers = {"最迟还款日", "还款金额","剩余几天","逾期几天", "罚息","是否垫付","状态","是否发放收益"};
List<P2pLoanPlanVo> dataset = new ArrayList<P2pLoanPlanVo>();
List<P2pLoanPlan> plans = this.planService.getListByLoan(id);
for (int i = 0; i < plans.size(); i++) {
P2pLoanPlanVo p2pLoanPlanVo = new P2pLoanPlanVo(); p2pLoanPlanVo.setRepayDate(plans.get(i).getRepayDate());
p2pLoanPlanVo.setRepayAmount(plans.get(i).getRepayAmount()); if(plans.get(i).getRepayDays() >= 0 && plans.get(i).getStatus() == 0){
p2pLoanPlanVo.setRepayDays(plans.get(i).getRepayDays());
}else{
p2pLoanPlanVo.setRepayDays(0);
}
if(plans.get(i).getRepayDays() < 0 && plans.get(i).getStatus() == 0){
p2pLoanPlanVo.setRepayYqDays(-plans.get(i).getRepayDays());
}else{
p2pLoanPlanVo.setRepayYqDays(0);
} p2pLoanPlanVo.setLateAmount(plans.get(i).getLateAmount());
String IsPosPaid = "";
if(plans.get(i).getIsPosPaid()==true){
IsPosPaid = "已垫付";
}else{
IsPosPaid = "未垫付";
}
p2pLoanPlanVo.setIsPosPaid(IsPosPaid);
p2pLoanPlanVo.setStatusName(plans.get(i).getStatusName());
String IsSysPay ="";
if(plans.get(i).getIsSysPay() == true){
IsSysPay = "已发放收益";
}else{
IsSysPay = "未发放收益";
}
p2pLoanPlanVo.setIsSysPay(IsSysPay); dataset.add(p2pLoanPlanVo); }
try {
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/x-download"); String filedisplay = "还款计划.xls";
//防止文件名含有中文乱码
filedisplay = new String( filedisplay.getBytes("gb2312"), "ISO8859-1" );
resp.setHeader("Content-Disposition", "attachment;filename="+ filedisplay); OutputStream out = resp.getOutputStream();
ex.exportExcel(headers, dataset, out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
Exceptions.getExceptionMsg(e, logger);
}
}

注意:此处ExportExcel<T>工具类中的泛型对应P2pLoanPlanVo这个类,P2pLoanPlanVo类中的属性要对应exportExcel()接口中headers中每个值并且都要有值,不允许为空,若有不足的地方还望各位大神多多指点!

未经博主允许,请勿转载