java表格导出table成Excel

利用 把页面显示的表格导出成Excel


部分代码不能公布,大家可以参考思路和使用这个封装过的工具类。

需求:如下

根据筛选条件筛选,把显示的内容导出成Excel,每个筛选条件来自不同的表。简单的请参考:POI和EasyExcel实现Excel数据批量读取到数据库

在这里插入图片描述

前端

<form id="formpool" method="post" value=serializeObject2jsonStr($('#formpool'))>
	<div class="form-inline">
		<div class="control-group inline">
			<label class="inline" style="width: 80px;">产品:</label>
			<select id="productId" name="productId" class="input-medium" style="width: 200px;"></select>
		</div>
		<div class="control-group inline">
			<label class="inline" style="width: 80px;">渠道号:</label>
			<input id="channelIds" name="channelIds" class="input-medium" type="text" value="" style="width: 200px;"/>
		</div>
		<div class="control-group inline">
			<label class="inline" style="width: 80px;">合作伙伴:</label>
			<select id="parterId" name="parterId" class="input-medium" style="width: 200px;">
				<option value=""></option>
			</select>
		</div>
		<div class="control-group inline">
			<label class="inline" style="width: 80px;">对接商务:</label>
			<select id="businessPerId" name="businessPerId" class="input-medium" style="width: 200px;">
				<option value=""></option>
			</select>
		</div>
		<div class="control-group inline">
			<button type="button" class="btn btn-primary" id="qur_btn">查找</button>
		</div>
		<div class="control-group inline">
			<button type="button" class="btn btn-primary" id="export_btn">导出</button>
		</div><br/>
	</div>
</form>
	<!-- 查询表格 -->
	<div class="row-fluid toolbar">
		<table id="channelmanament_table" class="table table-hover table-bordered table-condensed table-striped">
			<thead>
				<tr>
					<th style="text-align: center;">序号</th>
					<th style="text-align: center;">产品</th>
					<th style="text-align: center;">渠道号</th>
					<th style="text-align: center;">合作伙伴</th>
					<th style="text-align: center;">渠道名称</th>
					<th style="text-align: center;">对接商务</th>
					<th style="text-align: center;">创建时间</th>
					<th style="text-align: center;">修改时间</th>
					<th style="text-align: center;">操作</th>
				</tr>
			</thead>
			<tbody></tbody>
		</table>
	</div>
</div>
/* 导出按钮被触发 */
    $("#export_btn").click(function () {
        //判断当前是否可以导出
        isCanExport();
    });
/* 当前是否可以导出*/
function isCanExport() {
    $.ajax({
        type: 'get',
        paramSelector: '#productId,#businessPerId,#parterId,#channelIds',
        url: ctx + '/web/channelmanagement/isCanExport',
        async: false,
        success: function (data) {
            if (data == true) {
                exportData();
            } else {
                myalert('', '当前同时导出任务数达到上线,请稍后进行导出....');
                return;
            }
        }
    });
}
/* 渠道信息导出 */
function exportData() {
    var url = ctx + "/web/channelmanagement/exportChannels";
    $('#formpool').attr('action', url);
    $('#formpool').submit();
}

后台【省略接口】

controller层

    /**
     * 判断是否可以导出
     *
     * @param request
     */
    @RequestMapping(value = "/isCanExport", method = RequestMethod.GET)
    @ResponseBody
    public boolean isCanExport(HttpServletRequest request) {
        CounterUtil.counter.incrementAndGet();
        int value = CounterUtil.counter.get();
        if (value > MAXEXPORTTASK) {
            CounterUtil.counter.decrementAndGet();
            return false;
        } else {
            HttpSession session = request.getSession(true);
            session.setAttribute("flag", "yes");
            return true;
        }
    }
	@Resource
    private IProductService productService;
    @Resource
    private IParterinfoService iParterinfoService;
    @Resource
    private IBusinessPersonnelService iBusinessPersonnelService;
    @Resource
    private IChannelManagementService iChannelManagementService;

    @RequestMapping(value = "/exportChannels", method = RequestMethod.POST)
    @ResponseBody
    public void exportChannels(HttpServletRequest request,
                                           HttpServletResponse response,
                                           @RequestParam(value = "productId", required = false, defaultValue = "") String productId,
                                           @RequestParam(value = "businessPerId", required = false, defaultValue = "") String businessPerId,
                                           @RequestParam(value = "parterId", required = false, defaultValue = "") String parterId,
                                           @RequestParam(value = "channelIds", required = false, defaultValue = "") String channelIds) {

        // 满足要求才能让其导出
        HttpSession session = request.getSession(true);
        if ("yes".equals(session.getAttribute("flag"))) {
            // Excel表头
            List<String> headerList = Lists.newArrayList();
            headerList.add("序号");
            headerList.add("产品");
            headerList.add("渠道号");
            headerList.add("合作伙伴");
            headerList.add("渠道名称");
            headerList.add("对接商务");
            headerList.add("创建时间");
            headerList.add("修改时间");

            List<List<Object>> dataList = Lists.newArrayList();


            List<String> visibleProduct = new ArrayList<>();

            // 产品处理(过滤用户可见的产品,数据权限)
            UserVO user = super.getUser();

            List<ProductVO> products = user.getProducts();
            if (products.size() == 0) {
                String fileName = HelperUtil.getCurrentDate() + "_ChannelConfig.xlsx";
                ExcelUtil.export("渠道信息数据", fileName, headerList, dataList, response);
                return;
            } else {
                for (ProductVO p : products) {
                    visibleProduct.add(p.getCode());
                }
            }


            //获取总的记录数
            long totalRecord = iChannelManagementService.getChannelManagementCount(productId, businessPerId, parterId, channelIds);

            // 定义每页数据数量
            int pageSize = MAXPAGESIZE;


            if (totalRecord > 0 && pageSize > 0) {
                //总的页数(总数量除以每页显示条数)
                long exportTimes = totalRecord % pageSize > 0 ? totalRecord / pageSize + 1 : totalRecord / pageSize;
                //循环获取每页数据
                for (int m = 0; m < exportTimes; m++) {
                    List<ChannelEntity> list = iChannelManagementService
                            .getChannelManagement(m * pageSize, pageSize, productId, businessPerId, parterId, channelIds);

                    if (!super.isEmpty(list)) {

                        //转换把id转换成name
                        List<ProductEntity> productEntities = productService.getAllProduct();
                        Map<String, String> mapProducts = new HashMap<String, String>(20);
                        if (!super.isEmpty(productEntities)) {
                            for (ProductEntity p : productEntities) {
                                mapProducts.put(p.getProductId(), p.getProductName());
                            }
                        }

                        List<ParterinfoEntity> parterinfoEntities = iParterinfoService.getParterConfig();
                        Map<String, String> mapParters = new HashMap<String, String>(20);
                        if (!super.isEmpty(parterinfoEntities)) {
                            for (ParterinfoEntity p : parterinfoEntities) {
                                mapParters.put(p.getParterID(), p.getParterName());
                            }
                        }

                        List<BusinessPersonnelEntity> businessPersonnelEntities = iBusinessPersonnelService.getBusinessConfigs();
                        Map<String, String> mapBusiness = new HashMap<String, String>(20);
                        if (!super.isEmpty(businessPersonnelEntities)) {
                            for (BusinessPersonnelEntity p : businessPersonnelEntities) {
                                mapBusiness.put(p.getBusinessPersonnelId() + "", p.getBusinessPersonnelName());
                            }
                        }

                        if (!super.isEmpty(list)) {
                            for (ChannelEntity cha : list) {
                                List<Object> dataRowList = Lists.newArrayList();
                                dataRowList.add(cha.getId());
                                dataRowList.add(mapProducts.get(cha.getProductId()));
                                dataRowList.add(cha.getChannelId());
                                dataRowList.add(mapParters.get(cha.getParterID()));
                                dataRowList.add(cha.getChannelName());
                                dataRowList.add(mapBusiness.get(cha.getBusinessPersonnelId()));
                                dataRowList.add(HelperUtil.parseDateTimeToString(cha.getCreatedTime()));
                                dataRowList.add(HelperUtil.parseDateTimeToString(cha.getUpdateTime()));
                                dataList.add(dataRowList);
                            }
                        }
                    }
                }
            }

            String dataInfo = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            String fileName = dataInfo + "_ChannelConfig.xlsx";
            ExcelUtil.export("渠道信息数据", fileName, headerList, dataList, response);
            CounterUtil.counter.decrementAndGet();
            session.removeAttribute("flag");
        }
    }

Service层

	@Resource
    private IChannelManagementReadDao iChannelManagementReadDao;
    @Override
    public List<ChannelEntity> getChannelManagement(int start, int length, String productId, String businessPerId, String parterId, String channelIds) {
        return iChannelManagementReadDao.getChannelManagements(start, length,productId,businessPerId,parterId,channelIds);
    }

    @Override
    public long getChannelManagementCount(String productId, String businessPerId, String parterId, String channelIds) {
        return iChannelManagementReadDao.getChannelManagementCount(productId,businessPerId,parterId,channelIds);
    }

dao层

 @Resource
    private SqlSession sqlsessionRead;

    @Override
    public List<ChannelEntity> getChannelManagements(int start, int length,String productId,String businessPerId,
                                                     String parterId,String channelIds) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("start", start);
        params.put("limit", length);
        params.put("productId", productId);
        params.put("businessPerId", businessPerId);
        params.put("parterId", parterId);
        params.put("channelIds", channelIds);
        return sqlsessionRead.selectList("read.channel.listChannelManagements", params);
    }

    @Override
    public long getChannelManagementCount(String productId,String businessPerId,String parterId,String channelIds) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("productId", productId);
        params.put("businessPerId", businessPerId);
        params.put("parterId", parterId);
        params.put("channelIds", channelIds);
        return sqlsessionRead.selectOne("read.channel.channelManagementCount",params);
    }

mapper

	<select id="listChannelManagements" parameterType="java.util.Map" resultType="ChannelEntity">
		select c.ID, c.ProductId,c.ChannelId, c.ParterID, c.ChannelName, c.BusinessPersonnelId, c.CreatedTime, c.UpdateTime
		from Channels c
		where isValid = 1
		<if test="productId != null and productId != ''">  AND ProductId = #{productId} </if>
		<if test="businessPerId != -1 and businessPerId != ''">  AND BusinessPersonnelId = #{businessPerId} </if>
		<if test="parterId != -1 and parterId != ''">  AND ParterID = #{parterId} </if>
		<if test="channelIds != null and channelIds != ''">  AND ChannelId = #{channelIds} </if>
		order by ID ASC
		<if test="start >=0 and limit>0">limit #{start},#{limit}</if>
	</select>

	<select id="channelManagementCount" parameterType="java.util.Map" resultType="long">
		select count(ID) from Channels where isValid = 1
		<if test="productId != null and productId != ''">  AND ProductId = #{productId} </if>
		<if test="businessPerId != -1 and businessPerId != ''">  AND BusinessPersonnelId = #{businessPerId} </if>
		<if test="parterId != -1 and parterId != ''">  AND ParterID = #{parterId} </if>
		<if test="channelIds != null and channelIds != ''">  AND ChannelId = #{channelIds} </if>
	</select>

工具类

/**
 * excel导出类
 * @author dsqin
 *
 */
public class ExcelUtil {
	
	/**
	 * 导出文件至excel文件中
	 * @param title excel内容标题
	 * @param fileName 文件名
	 * @param headerList 表头
	 * @param dataList 表内容
	 * @param response
	 */
	public static void export(String title, String fileName, List<String> headerList, List<List<Object>> dataList, HttpServletResponse response) {
		ExportExcel ee = new ExportExcel(title, headerList);
		for (int i = 0; i < dataList.size(); i++) {
			Row row = ee.addRow();
			for (int j = 0; j < dataList.get(i).size(); j++) {
				ee.addCell(row, j, dataList.get(i).get(j));
			}
		}
		try {
			ee = ee.write(response, fileName);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ee.dispose();
	}
}
package com.iflytek.cbg.wmp.util;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
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.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;

import com.google.common.collect.Lists;

/**
 * 导出excel
 * 
 * @author dsqin
 * 
 */
public class ExportExcel {
	
	private static Logger LOGGER = Logger.getLogger(ExportExcel.class);

	/**
	 * 工作薄对象
	 */
	private SXSSFWorkbook wb;

	/**
	 * 工作表对象
	 */
	private Sheet sheet;

	/**
	 * 样式列表
	 */
	private Map<String, CellStyle> styles;

	/**
	 * 当前行号
	 */
	private int rownum;

	/**
	 * 注解列表(Object[]{ ExcelField, Field/Method })
	 */
	List<Object[]> annotationList = Lists.newArrayList();

	/**
	 * 构造函数
	 * 
	 * @param title
	 *            表格标题,传“空值”,表示无标题
	 * @param cls
	 *            实体对象,通过annotation.ExportField获取标题
	 */
	public ExportExcel(String title, Class<?> cls) {
		this(title, cls, 1);
	}

	/**
	 * 构造函数
	 * 
	 * @param title
	 *            表格标题,传“空值”,表示无标题
	 * @param cls
	 *            实体对象,通过annotation.ExportField获取标题
	 * @param type
	 *            导出类型(1:导出数据;2:导出模板)
	 * @param groups
	 *            导入分组
	 */
	public ExportExcel(String title, Class<?> cls, int type, int... groups) {
		// Get annotation field
		Field[] fs = cls.getDeclaredFields();
		for (Field f : fs) {
			ExcelField ef = f.getAnnotation(ExcelField.class);
			if (ef != null && (ef.type() == 0 || ef.type() == type)) {
				if (groups != null && groups.length > 0) {
					boolean inGroup = false;
					for (int g : groups) {
						if (inGroup) {
							break;
						}
						for (int efg : ef.groups()) {
							if (g == efg) {
								inGroup = true;
								annotationList.add(new Object[] { ef, f });
								break;
							}
						}
					}
				} else {
					annotationList.add(new Object[] { ef, f });
				}
			}
		}
		// Get annotation method
		Method[] ms = cls.getDeclaredMethods();
		for (Method m : ms) {
			ExcelField ef = m.getAnnotation(ExcelField.class);
			if (ef != null && (ef.type() == 0 || ef.type() == type)) {
				if (groups != null && groups.length > 0) {
					boolean inGroup = false;
					for (int g : groups) {
						if (inGroup) {
							break;
						}
						for (int efg : ef.groups()) {
							if (g == efg) {
								inGroup = true;
								annotationList.add(new Object[] { ef, m });
								break;
							}
						}
					}
				} else {
					annotationList.add(new Object[] { ef, m });
				}
			}
		}
		// Field sorting
		Collections.sort(annotationList, new Comparator<Object[]>() {
			public int compare(Object[] o1, Object[] o2) {
				return new Integer(((ExcelField) o1[0]).sort())
						.compareTo(new Integer(((ExcelField) o2[0]).sort()));
			};
		});
		// Initialize
		List<String> headerList = Lists.newArrayList();
		for (Object[] os : annotationList) {
			String t = ((ExcelField) os[0]).title();
			// 如果是导出,则去掉注释
			if (type == 1) {
				String[] ss = StringUtils.split(t, "**", 2);
				if (ss.length == 2) {
					t = ss[0];
				}
			}
			headerList.add(t);
		}
		initialize(title, headerList);
	}
	
	public ExportExcel(String title, List<String> headerList) {
		// TODO Auto-generated constructor stub
		initialize(title, headerList);
	}

	/**
	 * 初始化函数
	 * @param title 表格标题,传“空值”,表示无标题
	 * @param headerList 表头列表
	 */
	private void initialize(String title, List<String> headerList) {
		this.wb = new SXSSFWorkbook(500);
		this.sheet = wb.createSheet("Export");
		this.styles = createStyles(wb);
		if (headerList == null){
			throw new RuntimeException("headerList not null!");
		}
		Row headerRow = sheet.createRow(rownum++);
		headerRow.setHeightInPoints(16);
		for (int i = 0; i < headerList.size(); i++) {
			Cell cell = headerRow.createCell(i);
			cell.setCellStyle(styles.get("header"));
			String[] ss = StringUtils.split(headerList.get(i), "**", 2);
			if (ss.length==2){
				cell.setCellValue(ss[0]);
				Comment comment = this.sheet.createDrawingPatriarch().createCellComment(
						new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6));
				comment.setString(new XSSFRichTextString(ss[1]));
				cell.setCellComment(comment);
			}else{
				cell.setCellValue(headerList.get(i));
			}
			sheet.autoSizeColumn(i);
		}
		for (int i = 0; i < headerList.size(); i++) {  
			int colWidth = sheet.getColumnWidth(i)*2;
	        sheet.setColumnWidth(i, colWidth < 3000 ? 3000 : colWidth);  
		}
	}

	/**
	 * 创建表格样式
	 * @param wb 工作薄对象
	 * @return 样式列表
	 */
	private Map<String, CellStyle> createStyles(Workbook wb) {
		Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
		
		CellStyle style = wb.createCellStyle();
		style.setAlignment(CellStyle.ALIGN_CENTER);
		style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
		Font titleFont = wb.createFont();
		titleFont.setFontName("宋体");
		titleFont.setFontHeightInPoints((short) 16);
//		titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
		style.setFont(titleFont);
		styles.put("title", style);

		style = wb.createCellStyle();
		style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
		style.setBorderRight(CellStyle.BORDER_THIN);
		style.setRightBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderLeft(CellStyle.BORDER_THIN);
		style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderTop(CellStyle.BORDER_THIN);
		style.setTopBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderBottom(CellStyle.BORDER_THIN);
		style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
		Font dataFont = wb.createFont();
		dataFont.setFontName("宋体");
		dataFont.setFontHeightInPoints((short) 11);
		style.setFont(dataFont);
		styles.put("data", style);
		
		style = wb.createCellStyle();
		style.cloneStyleFrom(styles.get("data"));
		style.setAlignment(CellStyle.ALIGN_LEFT);
		styles.put("data1", style);

		style = wb.createCellStyle();
		style.cloneStyleFrom(styles.get("data"));
		style.setAlignment(CellStyle.ALIGN_CENTER);
		styles.put("data2", style);

		style = wb.createCellStyle();
		style.cloneStyleFrom(styles.get("data"));
		style.setAlignment(CellStyle.ALIGN_RIGHT);
		styles.put("data3", style);
		
		style = wb.createCellStyle();
		style.cloneStyleFrom(styles.get("data"));
//		style.setWrapText(true);
		style.setAlignment(CellStyle.ALIGN_CENTER);
		style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
		style.setFillPattern(CellStyle.NO_FILL);
		Font headerFont = wb.createFont();
		headerFont.setFontName("宋体");
		headerFont.setFontHeightInPoints((short) 11);
		headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
		headerFont.setColor(IndexedColors.BLACK.getIndex());
		style.setFont(headerFont);
		styles.put("header", style);
		
		return styles;
	}

	/**
	 * 添加一行
	 * @return 行对象
	 */
	public Row addRow(){
		return sheet.createRow(rownum++);
	}
	

	/**
	 * 添加一个单元格
	 * @param row 添加的行
	 * @param column 添加列号
	 * @param val 添加值
	 * @return 单元格对象
	 */
	public Cell addCell(Row row, int column, Object val){
		return this.addCell(row, column, val, 0, Class.class);
	}
	
	/**
	 * 添加一个单元格
	 * @param row 添加的行
	 * @param column 添加列号
	 * @param val 添加值
	 * @param align 对齐方式(1:靠左;2:居中;3:靠右)
	 * @return 单元格对象
	 */
	public Cell addCell(Row row, int column, Object val, int align, Class<?> fieldType){
		Cell cell = row.createCell(column);
		CellStyle style = styles.get("data"+(align>=1&&align<=3?align:""));
		try {
			if (val == null){
				cell.setCellValue("");
			} else if (val instanceof String) {
				cell.setCellValue((String) val);
			} else if (val instanceof Integer) {
				cell.setCellValue((Integer) val);
			} else if (val instanceof Long) {
				cell.setCellValue((Long) val);
			} else if (val instanceof Double) {
				cell.setCellValue((Double) val);
			} else if (val instanceof Float) {
				cell.setCellValue((Float) val);
			} else if (val instanceof Date) {
				DataFormat format = wb.createDataFormat();
	            style.setDataFormat(format.getFormat("yyyy-MM-dd"));
				cell.setCellValue((Date) val);
			} else {
				if (fieldType != Class.class){
					cell.setCellValue((String)fieldType.getMethod("setValue", Object.class).invoke(null, val));
				}else{
					cell.setCellValue((String)Class.forName(this.getClass().getName().replaceAll(this.getClass().getSimpleName(), 
						"fieldtype."+val.getClass().getSimpleName()+"Type")).getMethod("setValue", Object.class).invoke(null, val));
				}
			}
		} catch (Exception ex) {
			ex.toString();
			cell.setCellValue("");
		}
		cell.setCellStyle(style);
		return cell;
	}

	/**
	 * 添加数据(通过annotation.ExportField添加数据)
	 * @return list 数据列表
	 */
	public <E> ExportExcel setDataList(List<E> list){
		for (E e : list){
			int colunm = 0;
			Row row = this.addRow();
			StringBuilder sb = new StringBuilder();
			for (Object[] os : annotationList){
				ExcelField ef = (ExcelField)os[0];
				Object val = null;
				try{
					if (StringUtils.isNotBlank(ef.value())){
						val = Reflections.invokeGetter(e, ef.value());
					}else{
						if (os[1] instanceof Field){
							val = Reflections.invokeGetter(e, ((Field)os[1]).getName());
						}else if (os[1] instanceof Method){
							val = Reflections.invokeMethod(e, ((Method)os[1]).getName(), new Class[] {}, new Object[] {});
						}
					}
				}catch(Exception ex) {
					val = "";
				}
				this.addCell(row, colunm++, val, ef.align(), ef.fieldType());
				sb.append(val + ", ");
			}
		}
		return this;
	}
	
	/**
	 * 输出数据流
	 * @param os 输出数据流
	 */
	public ExportExcel write(OutputStream os) throws IOException{
		wb.write(os);
		return this;
	}
	
	/**
	 * 输出到客户端
	 * @param fileName 输出文件名
	 */
	public ExportExcel write(HttpServletResponse response, String fileName) throws IOException{
		response.reset();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=\""+(fileName) + "\"");
		write(response.getOutputStream());
		return this;
	}
	
	/**
	 * 输出到文件
	 * @param fileName 输出文件名
	 */
	public ExportExcel writeFile(String name) throws FileNotFoundException, IOException{
		/*FileOutputStream os = new FileOutputStream(name);
		this.write(os);
		os.close();
		return this;*/
		
		FileOutputStream fos =null;
	    try {  
            fos = new FileOutputStream(name);  
            this.write(fos);  
        } catch (FileNotFoundException e) {  
        	LOGGER.error(e);
        } catch (IOException e) {  
        	LOGGER.error(e); 
        } finally {  
            // 如果fos不为null,才需要close()  
            if (fos != null) {  
                // 为了保证close()一定会执行,就放到这里了  
                try {  
                    fos.close();  
                } catch (IOException e) {  
                	LOGGER.error(e);
                }  
            }  
        }
	    return this;
	}
	
	/**
	 * 清理临时文件
	 */
	public ExportExcel dispose(){
		wb.dispose();
		return this;
	}
	
	/**
	 * 导出文件到客户端
	 */
	public ExportExcel exportToClient(String title, String fileName, List<String> headerList, List<List<String>> dataList, HttpServletResponse response) {
		ExportExcel ee = new ExportExcel(title, headerList);
		for (int i = 0; i < dataList.size(); i++) {
			Row row = ee.addRow();
			for (int j = 0; j < dataList.get(i).size(); j++) {
				ee.addCell(row, j, dataList.get(i).get(j));
			}
		}
		
		try {
			ee = ee.write(response, fileName);
		} catch (IOException e) {
			return null;
		}
		ee.dispose();
		
		return ee;
	}
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值