1.支撑准备 :
文件上传jar包
2.工具类实现
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
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;
import org.apache.poi.hssf.util.Region;
import com.cndey.core.model.KeyValueBean;
@SuppressWarnings("all")
public class Utils {
/**
*
*@注释 导出Excel
*@方法名称 genericSheet
* @param title 标题
* @param headList 表头列(KeyValueBean key是字段名称 value是说明文字)
* @param data 导出数据
* @param work 可添加新增的sheet
* @return
*/
public static HSSFWorkbook genericSheet(String title,List<KeyValueBean> headList, List<Map<String,Object>> data, HSSFWorkbook work) {
if(work == null) work = new HSSFWorkbook();
HSSFCellStyle dataStyle = work.createCellStyle();
dataStyle.setWrapText(true);
// 字体对象设置
HSSFFont font = work.createFont();
font.setFontHeightInPoints((short) 16);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 表头字体颜色
HSSFFont colorFont = work.createFont();
colorFont.setColor(HSSFColor.RED.index);
// 大标题格式
HSSFCellStyle titleStyle = work.createCellStyle();
titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
titleStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
titleStyle.setFont(font);
// 数据表头格式 并设置值表头 设置表头居中
HSSFCellStyle style = work.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);// 设置背景色
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
// 设置边框
style.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
style.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
style.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
// 说明格式
HSSFCellStyle explainStyle = work.createCellStyle();//说明格式加红标注
explainStyle.setWrapText(true);//设置自动换行
explainStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
explainStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
explainStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
explainStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
explainStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_TOP);
explainStyle.setFont(colorFont);
HSSFCellStyle wrapStyle = work.createCellStyle(); // 说明格式标注
wrapStyle.setWrapText(true);
wrapStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_TOP);
wrapStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
wrapStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
wrapStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
wrapStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
wrapStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_TOP);
// 创建sheet
HSSFSheet sheet = work.createSheet(title);
sheet.setDefaultColumnWidth(20); // 默认列宽
sheet.setDefaultRowHeightInPoints(20);
int rows = 2;// 行号
HSSFRow headerRow = sheet.createRow((int) 0);
Region region = new Region(0, (short) 0, 1, (short) (headList.size()-1)); //参数1:行号 参数2:起始列号 参数3:行号 参数4:终止列号O
sheet.addMergedRegion(region);
HSSFCell cellTitle = headerRow.createCell((short) 0);
cellTitle.setCellValue(title);
cellTitle.setCellStyle(titleStyle);
HSSFRow explRow1 = null;// 说明表头1
HSSFRow explRow2 = null;// 说明表头2
HSSFCell explCell1 = null;//说明1表头单元格
HSSFCell explCell2 = null;//说明2表头单元格
if(StringUtils.isNotBlank(headList.get(0).getValue())) {
explRow1 = sheet.createRow(rows);
explRow2 = sheet.createRow(rows + 1);
rows = rows + 2;
}
HSSFRow row = sheet.createRow(rows);//表头
HSSFCell cell = row.createCell((short) 0);//表头单元格
for (int k = 0; k < headList.size(); k++) {//循环迭代表头并设置说明及列名称
String colName = headList.get(k).getKey();
if(explRow1 != null && explRow2 != null) {// 存在说明表头设置列说明
explCell1 = explRow1.createCell((short) (k));//创建表头说明1单元格
explCell2 = explRow2.createCell((short) (k));//创建表头说明2单元格
explCell1.setCellValue(headList.get(k).getValue());
if(colName.indexOf("!") != -1){
explCell1.setCellStyle(explainStyle);
explCell2.setCellStyle(explainStyle);
} else {
explCell1.setCellStyle(wrapStyle);
explCell2.setCellStyle(wrapStyle);
}
Region explainRegion = new Region(2, (short) k, 3, (short) k); //参数1:行号 参数2:起始列号 参数3:行号 参数4:终止列号O
sheet.addMergedRegion(explainRegion);
}
cell = row.createCell((short) (k));// 设置列名称
cell.setCellValue(colName.replaceAll("!", ""));
cell.setCellStyle(style);
}
row = sheet.createRow(rows + 1); // 生成数据
if(!CollectionUtil.isEmpty(data)) {
for(int j = 0; j < data.size(); j++) {
Map<String,Object> obj = data.get(j);
row = sheet.createRow(rows + j + 1);
for(int i = 0; i < headList.size(); i++) {
HSSFCell createCell = row.createCell(i);
createCell.setCellStyle(dataStyle);
createCell.setCellValue(obj.get(headList.get(i).getKey()) != null?obj.get(headList.get(i).getKey()).toString():Constant.EMPTY_STRING);
}
}
}
return work;
}
/**
*@注释 写出work
*@方法名称 outPutToWork
* @param work
* @param fileName
*/
public static String writeToWork(HSSFWorkbook work,String fileName){
try {
FileOutputStream fout = new FileOutputStream(Utils.getToolsTempPath()+fileName);
work.write(fout);
fout.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return fileName;
}
/**
* 得到webroot下tools路径
*
* @return
*/
public static String getToolsTempPath() {
return ContextUtil.getServletContext().getRealPath("/temp/");
}
}
2.工具类的一个小的应用例子
Action层代码:
@RequestMapping("overallIncomeExp.data")
public void overallIncomeExp(){
String result = shopExportManager.overallIncomeExp(current.getShopOrder());
writeToFile(result,response);
}
业务层代码:
/**
* 店铺营业收入导出
* @param shopOrder
* @return
*/
@Override
public String overallIncomeExp(ShopOrderVO shopOrder) {
List<KeyValueBean> headList = new ArrayList<KeyValueBean>();
List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();
String[] header = new String[]{"日期","总订单金额","未付款金额","已付款未发货金额","已发货金额","回款订单金额","付款前关闭订单金额","成功退款订单金额","运费金额"};
for (String head : header) {
headList.add(new KeyValueBean(head, null));
}
Map<String, Object> param = new HashMap<String, Object>();
if(!StringUtil.isBlank(shopOrder.getStartTime()))
param.put("startTime", shopOrder.getStartTime());
if(!StringUtil.isBlank(shopOrder.getEndTime()))
param.put("endTime", shopOrder.getEndTime());
if(IntegerUtil.notEmpty(shopOrder.getShopId()))
param.put("o.SHOP_ID", shopOrder.getShopId());
List<ShopOrderVO> list = shopDAO.getOverallList(param);
for (ShopOrderVO so : list) {
Map<String,Object> map = new HashMap<String, Object>();
map.put(header[0], so.getOverallDate());
map.put(header[1], so.getOverallTotalOrder());
map.put(header[2], so.getOverallUnpaidOrder());
map.put(header[3], so.getOverallPaidNotShip());
map.put(header[4], so.getOverallShip());
map.put(header[5], so.getOverallPayback());
map.put(header[6], so.getOverallDownOrder());
map.put(header[7], so.getOverallRefund());
map.put(header[8], so.getOverallFare());
data.add(map);
}
return Utils.writeToWork(Utils.genericSheet("店铺营业收入情况导出", headList, data, new HSSFWorkbook()), "overallIncomeExport.xls");
}
说明:里面的KeyValueBean是一个键值对的实体类
/**
*
* 键值对<br>
* Title: kpi 1.0<br>
* Date: 2018年11月15日 <br>
*/
public class KeyValueBean {
private String key;
private String value;
public KeyValueBean(){}
public KeyValueBean(String key, String value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
writeToFile方法:
/**
*@注释 向页面输出文件
*@方法名称 writeToFile
* @param fileName
*/
public void writeToFile(String fileName,HttpServletResponse response){
if(StringUtils.isBlank(fileName)) return;
try {
response.setContentType(fileName);// 设置Content-Disposition
response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(), "ISO8859-1"));
InputStream in = new FileInputStream(Utils.getToolsTempPath()+fileName);// 读取文件
OutputStream out = response.getOutputStream();
int b;// 写文件
while ((b = in.read()) != -1) {
out.write(b);
}
in.close();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}