废话不多说,贴代码:
package com.pinyu.system.utils.excel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
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.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
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.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
*
* @ClassName ExcelUtils
* @Description TODO(这里用一句话描述这个类的作用)
* @author ypp
*/
public class ExcelUtils {
Logger logger = LogManager.getLogger(ExcelUtils.class);
//%%%%%%%%-------常量部分 开始----------%%%%%%%%%
/**
* 默认的开始读取的行位置为第一行(索引值为0)
*/
private final static int READ_START_POS = 0;
/**
* 默认结束读取的行位置为最后一行(索引值=0,用负数来表示倒数第n行)
*/
private final static int READ_END_POS = 0;
/**
* 默认Excel内容的开始比较列位置为第一列(索引值为0)
*/
private final static int COMPARE_POS = 0;
/**
* 默认多文件合并的时需要做内容比较(相同的内容不重复出现)
*/
private final static boolean NEED_COMPARE = true;
/**
* 默认多文件合并的新文件遇到名称重复时,进行覆盖
*/
private final static boolean NEED_OVERWRITE = true;
/**
* 默认只操作一个sheet
*/
private final static boolean ONLY_ONE_SHEET = true;
/**
* 默认读取第一个sheet中(只有当ONLY_ONE_SHEET = true时有效)
*/
private final static int SELECTED_SHEET = 0;
/**
* 默认从第一个sheet开始读取(索引值为0)
*/
private final static int READ_START_SHEET= 0;
/**
* 默认在最后一个sheet结束读取(索引值=0,用负数来表示倒数第n行)
*/
private final static int READ_END_SHEET = 0;
/**
* 默认打印各种信息
*/
private final static boolean PRINT_MSG = true;
//%%%%%%%%-------常量部分 结束----------%%%%%%%%%
//%%%%%%%%-------字段部分 开始----------%%%%%%%%%
/**
* Excel文件路径
*/
private String excelPath = "data.xlsx";
/**
* 设定开始读取的位置,默认为0
*/
private int startReadPos = READ_START_POS;
/**
* 设定结束读取的位置,默认为0,用负数来表示倒数第n行
*/
private int endReadPos = READ_END_POS;
/**
* 设定开始比较的列位置,默认为0
*/
private int comparePos = COMPARE_POS;
/**
* 设定汇总的文件是否需要替换,默认为true
*/
private boolean isOverWrite = NEED_OVERWRITE;
/**
* 设定是否需要比较,默认为true(仅当不覆写目标内容是有效,即isOverWrite=false时有效)
*/
private boolean isNeedCompare = NEED_COMPARE;
/**
* 设定是否只操作第一个sheet
*/
private boolean onlyReadOneSheet = ONLY_ONE_SHEET;
/**
* 设定操作的sheet在索引值
*/
private int selectedSheetIdx =SELECTED_SHEET;
/**
* 设定操作的sheet的名称
*/
private String selectedSheetName = "";
/**
* 设定开始读取的sheet,默认为0
*/
private int startSheetIdx = READ_START_SHEET;
/**
* 设定结束读取的sheet,默认为0,用负数来表示倒数第n行
*/
private int endSheetIdx = READ_END_SHEET;
/**
* 设定是否打印消息
*/
private boolean printMsg = PRINT_MSG;
/**
* 导出Excel
* @param sheetName sheet名称
* @param title 标题
* @param values 内容
* @param wb HSSFWorkbook对象
* @return
*/
public static HSSFWorkbook getHSSFWorkbook(String sheetName,String []title,String [][]values, HSSFWorkbook wb){
// 第一步,创建一个HSSFWorkbook,对应一个Excel文件
if(wb == null){
wb = new HSSFWorkbook();
}
HSSFFont font = wb.createFont();
font.setBold(true);//加粗
// 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet
HSSFSheet sheet = wb.createSheet(sheetName);
// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
HSSFRow row = sheet.createRow(0);
// 第四步,创建单元格,并设置值表头 设置表头居中
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式
style.setWrapText(true);//设置自动换行
style.setFont(font);
//声明列对象
HSSFCell cell = null;
//创建标题
for(int i=0;i<title.length;i++){
cell = row.createCell(i);
cell.setCellValue(title[i]);
cell.setCellStyle(style);
}
//内容样式
HSSFCellStyle style2 = wb.createCellStyle();
style2.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式
style2.setWrapText(true);//设置自动换行
//创建内容
for(int i=0;i<values.length;i++){
row = sheet.createRow(i + 1);
for(int j=0;j<values[i].length;j++){
//将内容按顺序赋给对应的列对象
HSSFCell createCell = row.createCell(j);
createCell.setCellStyle(style2);
createCell.setCellValue(values[i][j]);
}
}
return wb;
}
}
只看核心方法getHSSFWorkbook
controller代码:
package com.pinyu.system.web.controller.finance;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.pinyu.system.entity.finance.FinanceIncomeEntity;
import com.pinyu.system.service.finance.FinanceIncomeService;
import com.pinyu.system.web.page.Page;
/**
* @author ypp 创建时间:2018年10月29日 下午1:28:57
* @Description: TODO(财务报表-收益)
*/
@Controller
@RequestMapping("/financeIncome")
public class FinanceIncomeController {
@Autowired
private FinanceIncomeService service;
/**
* 导出本页
* @param page
* @return
*/
@RequestMapping("/exportPage/")
@ResponseBody
public void exportPage(HttpServletResponse response,@RequestBody Page<FinanceIncomeEntity> page){
Map<String,Object> rsMap= service.exportPage(page);
String fileName=(String) rsMap.get("fileName");
HSSFWorkbook wb=(HSSFWorkbook) rsMap.get("wb");
//响应到客户端
this.setResponseHeader(response, fileName);
OutputStream os;
try {
os = response.getOutputStream();
wb.write(os);
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 导出全部
*
* @param page
* @return
*/
@RequestMapping("/exportAll/")
@ResponseBody
public void exportAll(HttpServletResponse response) {
Map<String,Object> rsMap= service.exportAll();
String fileName=(String) rsMap.get("fileName");
HSSFWorkbook wb=(HSSFWorkbook) rsMap.get("wb");
//响应到客户端
this.setResponseHeader(response, fileName);
OutputStream os;
try {
os = response.getOutputStream();
wb.write(os);
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 发送响应流方法
public void setResponseHeader(HttpServletResponse response, String fileName) {
try {
try {
fileName = new String(fileName.getBytes(), "ISO8859-1");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.setContentType("application/octet-stream;charset=ISO8859-1");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
service代码:
package com.pinyu.system.service.finance.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.pinyu.system.dao.finance.FinanceIncomeDao;
import com.pinyu.system.entity.finance.FinanceIncomeEntity;
import com.pinyu.system.service.finance.FinanceIncomeService;
import com.pinyu.system.utils.DateUtils;
import com.pinyu.system.utils.excel.ExcelUtils;
import com.pinyu.system.utils.excel.FinancePropertiesUtils;
import com.pinyu.system.web.page.Page;
/**
* @author ypp
* 创建时间:2018年10月29日 下午1:36:18
* @Description: TODO(财务--收益)
*/
@Service
@Transactional(propagation=Propagation.REQUIRED)
public class FinanceIncomeServiceImpl implements FinanceIncomeService {
@Autowired
private FinanceIncomeDao dao;
@Override
@Transactional(readOnly=true)
public List<FinanceIncomeEntity> findByPageList(Page<FinanceIncomeEntity> page) {
return dao.findByPageList(page);
}
@Override
public List<FinanceIncomeEntity> findAll() {
return dao.findAll();
}
@Override
public Map<String, Object> exportPage(Page<FinanceIncomeEntity> page) {
return export(this.findByPageList(page));
}
@Override
public Map<String, Object> exportAll() {
return export(this.findAll());
}
private Map<String, Object> export(List<FinanceIncomeEntity> fis) {
//表头
String t = FinancePropertiesUtils.getFinanceIncomeNameTitel();
String[] title = t.split(",");
//sheet名
String sheetName =FinancePropertiesUtils.getFinanceIncomeName();
//文件名
String fileName=sheetName+System.currentTimeMillis()+FinancePropertiesUtils.getExcelSuffix();
String[][] content = new String[fis.size()][];
if(fis!=null&&fis.size()>0){
for (int i = 0; i < fis.size(); i++) {
content[i] = new String[title.length];
FinanceIncomeEntity obj = fis.get(i);
content[i][0] = DateUtils.formatSortDate(obj.getMonth()).toString();
content[i][1] = obj.getRentalIncome()!=null?obj.getRentalIncome().toString():"";
content[i][2] = obj.getRedecoratedPurchases()!=null?obj.getRedecoratedPurchases().toString():"";
content[i][3] = obj.getProductionCostsPurchases()!=null?obj.getProductionCostsPurchases().toString():"";
content[i][4] = obj.getLeaseCostsPurchases()!=null?obj.getLeaseCostsPurchases().toString():"";
content[i][5] = obj.getRentalCostPurchases()!=null?obj.getRentalCostPurchases().toString():"";
content[i][6] = obj.getOperateCostsPurchases()!=null?obj.getOperateCostsPurchases().toString():"";
content[i][7] = obj.getPromotionPurchases()!=null?obj.getPromotionPurchases().toString():"";
content[i][8] = obj.getLoss()!=null?obj.getLoss().toString():"";
content[i][9] = obj.getTaxOther()!=null?obj.getTaxOther().toString():"";
content[i][10] = obj.getIncomeTaxPurchases()!=null?obj.getIncomeTaxPurchases().toString():"";
content[i][11] = obj.getNetCashFlow()!=null?obj.getNetCashFlow().toString():"";
content[i][12] = obj.getTotalNetCashFlow()!=null?obj.getTotalNetCashFlow().toString():"";
}
}
//创建HSSFWorkbook
HSSFWorkbook wb = ExcelUtils.getHSSFWorkbook(sheetName, title, content, null);
Map<String,Object> rsMap=new HashMap<String, Object>();
rsMap.put("wb", wb);
rsMap.put("fileName", fileName);
return rsMap;
}
}
拿去既可以使用,稍微改动下
效果图: