导出:
html:
<div class="btn_box">
<span class="all-export cur" οnclick="fcOtherMatterItem.excelExportAll()">
<img src="../res/web/img/index/daochu.png" alt="" >
导出
</span>
</div>
js:
//全部导出
excelExportAll:function(){
$('.moke_expor').show();
$('.qbdc-wrppaer').show();
$(".qbdc-true").click(function(){
var param = {};
//获取搜索条件
$(.main_pager_search").each(function(){
var key = $(this).attr("name");
var val = $.trim($(this).val());
page.searchData[key] = val;
param[key] = val;
});
BaseUtil.postDownloadInpage("../matters/excelExportMatters",page.searchData);
$(".moke_expor,.qbdc-wrppaer").hide();
})
$(".close,.qbdc-cancle").click(function () {
$(".moke_expor,.qbdc-wrppaer").hide();
})
}
java后台
/**
* 执行导出 全部导出
* @param
*/
@RequestMapping(value = "/excelExportMatters" , method = { RequestMethod.POST })
public void excelExecuteExportAll(MattersVo search) {
//search添加查询条件,没有可以不加
List<String> aaa = new ArrayList<>();
aaa.add("123456789");
search.setCompanyIds(aaa);
List<MattersVo> dataList = new ArrayList<>();
int startNum = 0;
while (true) {
log.info("==========excelExecuteExportAll.getList入参[]=======",search);
Pages<MattersVo> mattersVos = mattersService.getList(search, ++startNum, 5000);
dataList.addAll(mattersVos.getContent());
if (mattersVos.getContent().size() < 5000)
break;
}
String titleColumn[] = {"导出表格对应vo字段1", "导出表格对应vo字段2", "name", "size","remark"};
String titleName[] = {"导出表格所展示文字1", "导出表格所展示文字2", "名字", "尺码", "备注"};
try {
JxlsUtils.listToExcelB(dataList, titleColumn, titleName, "事项全部导出", response, request, "事项查询统计.xls");
} catch (ExcelException e) {
log.error("导出Excel文件异常{}", e);
} catch (UnsupportedEncodingException e) {
log.error("导出Excel,文件名编码转换异常{}", e);
}
}
主要调用了工具类JxlsUtils.listToExcelB()方法 下边
package com.aa.bb.support.core.utils;
import com.aa.bb.support.core.command.MergeCommand;
import com.aa.bb.support.core.exception.ExcelException;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import lombok.extern.slf4j.Slf4j;
import org.jxls.builder.xls.XlsCommentAreaBuilder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.*;
/**
* 自定义excel模板导出excel
*/
@Slf4j
public class JxlsUtils {
static {
//注册jxls指令
XlsCommentAreaBuilder.addCommandMapping("merge", MergeCommand.class);
}
private Map<String,Integer> countMap = new HashMap<>(); //用于jxls的foreach循环计数
private static final JxlsUtils me = new JxlsUtils();
public JxlsUtils(){
}
/**
* @MethodName : listToExcel
* @Description : 导出Excel(可以导出到本地文件系统,也可以导出到浏览器,可自定义工作表大小)
* @param list 数据源
* @param fieldMap 类的英文属性和Excel中的中文列名的对应关系
* 如果需要的是引用对象的属性,则英文属性使用类似于EL表达式的格式
* 如:list中存放的都是student,student中又有college属性,而我们需要学院名称,则可以这样写
* fieldMap.put("college.collegeName","学院名称")
* @param sheetName 工作表的名称
* @param sheetSize 每个工作表中记录的最大个数
* @param out 导出流
* @throws ExcelException
*/
private static <T> void listToExcel (
List<T> list ,
LinkedHashMap<String,String> fieldMap,
String sheetName,
int sheetSize,
OutputStream out
) throws ExcelException {
if(list.size()==0 || list==null){
throw new ExcelException("数据源中没有任何数据");
}
if(sheetSize>65535 || sheetSize<1){
sheetSize=65535;
}
if(sheetName.getBytes().length==0){
sheetName = "sheet";
}
//创建工作簿并发送到OutputStream指定的地方
WritableWorkbook wwb;
try {
wwb = Workbook.createWorkbook(out);
//因为2003的Excel一个工作表最多可以有65536条记录,除去列头剩下65535条
//所以如果记录太多,需要放到多个工作表中,其实就是个分页的过程
//1.计算一共有多少个工作表
double sheetNum=Math.ceil(list.size()/new Integer(sheetSize).doubleValue());
//2.创建相应的工作表,并向其中填充数据
for(int i=0; i<sheetNum; i++){
//如果只有一个工作表的情况
if(1==sheetNum){
WritableSheet sheet=wwb.createSheet(sheetName, i);
fillSheet(sheet, list, fieldMap, 0, list.size()-1);
//有多个工作表的情况
}else{
WritableSheet sheet=wwb.createSheet(sheetName+(i+1), i);
//获取开始索引和结束索引
int firstIndex=i*sheetSize;
int lastIndex=(i+1)*sheetSize-1>list.size()-1 ? list.size()-1 : (i+1)*sheetSize-1;
//填充工作表
fillSheet(sheet, list, fieldMap, firstIndex, lastIndex);
}
}
wwb.write();
wwb.close();
}catch (Exception e) {
e.printStackTrace();
//如果是ExcelException,则直接抛出
if(e instanceof ExcelException){
throw (ExcelException)e;
//否则将其它异常包装成ExcelException再抛出
}else{
throw new ExcelException("导出Excel失败");
}
}
}
/**
* @MethodName : listToExcel
* @Description : 导出Excel(导出到浏览器,工作表的大小是2003支持的最大值)
* @param list 数据源
* @param titleColumn 类的英文属性
* @param titleName Excel中的中文列名
* @param sheetName Excel中工作表名称
* @param response 使用response可以导出到浏览器
* @param fileName 定义下载的文件名
* @throws ExcelException
* @throws UnsupportedEncodingException
*/
public static <T> void listToExcelB (
List<T> list ,
String titleColumn[],
String titleName[],
String sheetName,
HttpServletResponse response,
HttpServletRequest request,
String fileName
) throws ExcelException, UnsupportedEncodingException{
listToExcel(list, toLinkMap(titleColumn,titleName), sheetName, 65535, response, request, fileName);
}
/**
* @MethodName : toLinkMap
* @Description : 将类的属性和excel列名放入集合
* @param titleColumn 类的英文属性
* @param titleName Excel中的中文列名
* @return
* @throws ExcelException
*/
private static LinkedHashMap<String,String> toLinkMap(String titleColumn[],String titleName[]) throws ExcelException{
LinkedHashMap<String,String> fieldMap = new LinkedHashMap<>();
if(titleColumn.length != titleName.length){
throw new ExcelException("类属性数组长度与excel列数组长度不一致");
}else{
for (int i = 0; i < titleColumn.length; i++) {
for (int j = 0; j < titleName.length; j++) {
if(i==j){
fieldMap.put(titleColumn[i],titleName[j]);
}
}
}
}
return fieldMap;
}
/**
* @MethodName : listToExcel
* @Description : 导出Excel(导出到浏览器,可以自定义工作表的大小)
* @param list 数据源
* @param fieldMap 类的英文属性和Excel中的中文列名的对应关系
* @param sheetSize 每个工作表中记录的最大个数
* @param response 使用response可以导出到浏览器
* @param fileName 定义下载的文件名
* @throws ExcelException
* @throws UnsupportedEncodingException
*/
private static <T> void listToExcel (
List<T> list ,
LinkedHashMap<String,String> fieldMap,
String sheetName,
int sheetSize,
HttpServletResponse response,
HttpServletRequest request,
String fileName
) throws ExcelException, UnsupportedEncodingException{
//设置默认文件名为当前时间:年月日时分秒
//String fileName=new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()).toString();
String header = request.getHeader("User-Agent").toUpperCase();
if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
fileName = URLEncoder.encode(fileName, "utf-8");
fileName = fileName.replace("+", "%20"); //IE下载文件名空格变+号问题
} else {
fileName = new String(fileName.getBytes("utf-8"), "ISO8859-1");
}
//设置response头信息
// response.reset();
response.setContentType("application/vnd.ms-excel"); //改成输出excel文件
// response.setHeader("Content-disposition","attachment; filename="+fileName+".xls" );
response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
//创建工作簿并发送到浏览器
try {
OutputStream out=response.getOutputStream();
listToExcel(list, fieldMap, sheetName, sheetSize,out );
} catch (Exception e) {
e.printStackTrace();
//如果是ExcelException,则直接抛出
if(e instanceof ExcelException){
throw (ExcelException)e;
//否则将其它异常包装成ExcelException再抛出
}else{
throw new ExcelException("导出Excel失败");
}
}
}
/*<-------------------------辅助的私有方法----------------------------------------------->*/
/**
* @MethodName : getFieldValueByName
* @Description : 根据字段名获取字段值
* @param fieldName 字段名
* @param o 对象
* @return 字段值
*/
private static Object getFieldValueByName(String fieldName, Object o) throws Exception{
Object value=null;
Field field=getFieldByName(fieldName, o.getClass());
if(field !=null){
field.setAccessible(true);
value=field.get(o);
}else{
throw new ExcelException(o.getClass().getSimpleName() + "类不存在字段名 "+fieldName);
}
return value;
}
/**
* @MethodName : getFieldByName
* @Description : 根据字段名获取字段
* @param fieldName 字段名
* @param clazz 包含该字段的类
* @return 字段
*/
private static Field getFieldByName(String fieldName, Class<?> clazz){
//拿到本类的所有字段
Field[] selfFields=clazz.getDeclaredFields();
//如果本类中存在该字段,则返回
for(Field field : selfFields){
if(field.getName().equals(fieldName)){
return field;
}
}
//否则,查看父类中是否存在此字段,如果有则返回
Class<?> superClazz=clazz.getSuperclass();
if(superClazz!=null && superClazz !=Object.class){
return getFieldByName(fieldName, superClazz);
}
//如果本类和父类都没有,则返回空
return null;
}
/**
* @MethodName : getFieldValueByNameSequence
* @Description :
* 根据带路径或不带路径的属性名获取属性值
* 即接受简单属性名,如userName等,又接受带路径的属性名,如student.department.name等
*
* @param fieldNameSequence 带路径的属性名或简单属性名
* @param o 对象
* @return 属性值
* @throws Exception
*/
private static Object getFieldValueByNameSequence(String fieldNameSequence, Object o) throws Exception{
Object value=null;
//将fieldNameSequence进行拆分
String[] attributes=fieldNameSequence.split("\\.");
if(attributes.length==1){
value=getFieldValueByName(fieldNameSequence, o);
}else{
//根据属性名获取属性对象
Object fieldObj=getFieldValueByName(attributes[0], o);
String subFieldNameSequence=fieldNameSequence.substring(fieldNameSequence.indexOf(".")+1);
value=getFieldValueByNameSequence(subFieldNameSequence, fieldObj);
}
return value;
}
/**
* @MethodName : setColumnAutoSize
* @Description : 设置工作表自动列宽和首行加粗
* @param ws
*/
private static void setColumnAutoSize(WritableSheet ws,int extraWith){
//获取本列的最宽单元格的宽度
for(int i=0;i<ws.getColumns();i++){
int colWith=0;
for(int j=0;j<ws.getRows();j++){
String content=ws.getCell(i,j).getContents().toString();
int cellWith=content.length();
if(colWith<cellWith){
colWith=cellWith;
}
}
//设置单元格的宽度为最宽宽度+额外宽度
ws.setColumnView(i, colWith+extraWith);
}
}
/**
* @MethodName : fillSheet
* @Description : 向工作表中填充数据
* @param sheet 工作表
* @param list 数据源
* @param fieldMap 中英文字段对应关系的Map
* @param firstIndex 开始索引
* @param lastIndex 结束索引
*/
private static <T> void fillSheet(
WritableSheet sheet,
List<T> list,
LinkedHashMap<String,String> fieldMap,
int firstIndex,
int lastIndex
)throws Exception{
//定义存放英文字段名和中文字段名的数组
String[] enFields=new String[fieldMap.size()];
String[] cnFields=new String[fieldMap.size()];
//填充数组
int count=0;
for(Map.Entry<String,String> entry:fieldMap.entrySet()){
enFields[count]=entry.getKey();
cnFields[count]=entry.getValue();
count++;
}
//填充表头
for(int i=0;i<cnFields.length;i++){
Label label=new Label(i,0,cnFields[i]);
sheet.addCell(label);
}
//填充内容
int rowNo=1;
for(int index=firstIndex;index<=lastIndex;index++){
//获取单个对象
T item=list.get(index);
for(int i=0;i<enFields.length;i++){
Object objValue=getFieldValueByNameSequence(enFields[i], item);
String fieldValue=objValue==null ? "" : objValue.toString();
Label label =new Label(i,rowNo,fieldValue);
sheet.addCell(label);
}
rowNo++;
}
//设置自动列宽
setColumnAutoSize(sheet, 5);
}
}
导出基础excel结果:
(资金)