java导出excel表格

/**
 * 调用导出工具类,设置表头,设置表格内容
 *
 */
public void export( HttpServletResponse response) {

	List<List<String>> returnList = new ArrayList<>();
	//设置表头
	List<String> rowList = new ArrayList<>();
	rowList.add("序号");
	rowList.add("名字");
	rowList.add("性别");
	returnList.add(rowList);
	
	//设置表格内容
	for (int i = 0; i < 10; i++) {
		List<String> newRowList = new ArrayList<>();
		newRowList.add(i + 1 + "");//序号
		newRowList.add("xxx");//名字
		newRowList.add("23");//性别
		returnList.add(newRowList);
	}

	//导出标记信息
	try {
		exportExcel(response, "导出名称excel的文件名", returnList);
	} catch (Exception e) {
		log.error("导出时发生错误", e);
	}

}


/**
 * 导出excel
 *
 * @param response
 * @param title
 * @param dataList
 * @throws Exception
 */
public static void exportExcel(HttpServletResponse response, String title, List<List<String>> dataList) throws Exception {
    //获取一个HSSFWorkbook对象
    HSSFWorkbook workbook = new HSSFWorkbook();
    HSSFCellStyle style = getHSSFCellStyle(workbook);
    //创建一个sheet
    HSSFSheet sheet = workbook.createSheet("Sheet1");

    //表头
    HSSFRow row = sheet.createRow(0);

    //数据
    for (int i = 0; i < dataList.size(); i++) {
        row = sheet.createRow(i);
        for (int j = 0; j < dataList.get(i).size(); j++) {
            if (dataList.get(i).get(j) != null && dataList.get(i).get(j).length() > 0 && dataList.get(i).get(j).trim().length() > 0) {
                HSSFCell cell = row.createCell(j);
                HSSFCellStyle cellStyle = workbook.createCellStyle();
                HSSFFont font = workbook.createFont();
                if (i == 0) {
                    // 加粗
                    font.setBold(true);
                    font.setFontHeightInPoints((short) 13);
                    cellStyle.setFont(font);
                    sheet.setColumnWidth(j, 5000);
                }
                cellStyle.setWrapText(true);
                cell.setCellStyle(cellStyle);
                cell.setCellValue(dataList.get(i).get(j));
            }
        }
    }

    OutputStream outputStream = response.getOutputStream();
    //设置页面不缓存
    response.reset();
    String filename = title + ".xls";
    //设置返回文件名的编码格式
    response.setCharacterEncoding("utf-8");
    filename = URLEncoder.encode(filename, "utf-8");
    response.setHeader("Content-disposition", "attachment;filename=" + filename);
    response.setContentType("application/vnd.ms-excel");
    workbook.write(outputStream);
    outputStream.close();
}





/**
 * 创建一个style
 *
 * @param workbook
 * @return
 */
private static HSSFCellStyle getHSSFCellStyle(HSSFWorkbook workbook) {
    HSSFCellStyle cellStyle = workbook.createCellStyle();
    //居中
    cellStyle.setAlignment(CENTER);
    return cellStyle;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值