这里写目录标题

  • 业务背景
  • 前端
  • 后端
  • 导出效果


业务背景

如下图,想将用户选中的记录导出excel,某一列内容导出后需要换行展示

java输出excel 换行 java导出excel换行_java输出excel 换行

前端

表格勾选框列代码:
注:cid是记录的主键,绑定cid的方法用的公司封装方法,不通用,大家自主替换即可。
其他表格元素就正常写,不再赘述

<td 绑定cid值,width:'2%',checkbox:true," >
<input type="checkbox" name="items" id="items" onclick="setCheckBoxState('cid',this.checked);" >
</td>

操作checkbox的选中状态的方法:

/**
 * 操作checkbox的选中状态.
 * @param checkbox_name 需要设置状态的checkbox的名称.
 * @param state   true:设置为选中状态;false:设置为未选中状态.
 */
function setCheckBoxState(checkbox_name, state) {
	checkbox_name = replaceDollar(checkbox_name);
	$("input[name="+checkbox_name+"]").each(function(){
		if($(this).prop("disabled") == false){
			$(this).prop("checked", state);
		}
	});
}

导出excel按钮:

<input  onclick="excelExport();" type="button" value="excel导出">

导出方法:

/*
 * excel导出
 */
function  excelExport(){
	var cids = getCheckBoxData("cid","cid");   //getCheckBoxData方法往下看
	if(cids==""){
		whir_alert('请选择记录!',function(){});
	}else{
	    //这一步调用后端导出方法,谁敢信2022年了我还在用jsp,屑!大家的公司肯定没这么拉吧 
		window.open('/***/***!excelExport.action?recordIds='+cids);  
	}
}
/**
 * 获得checkbox的选中值,如果返回值为空说明没有任何checkbox被选中.
 * @param checkbox_name checkbox的名称.
 * @param attr_name   你打算获得的属性值的属性名字,如id、value等属性.
 * @return 获得的属性值的拼串,多个值之间以英文半角逗号分隔且最后一个逗号被自动去除,如"value1,value2,value3" ,如果返回值为空说明没有任何checkbox被选中.
 */
function getCheckBoxData(checkbox_name, attr_name) {
    checkbox_name = replaceDollar(checkbox_name);
    var r = "" ;
    $("input[name='"+checkbox_name+"'][type='checkbox']").each(function(){
        if($(this).prop("checked")==true ){
            r = r + $(this).attr(attr_name)+",";
        }
    });
    if(r.indexOf(",")>0){
        r = r.substring(0, r.length-1);
    }
    return r;
}
function replaceDollar(str){
    if(str.indexOf('$')!=-1) {
        return str.replace(/\$/m, '\\$');
    }
    return str;
}

后端

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public void excelExport() {
    //后端代码也很out,总之这段目的就是取到前端传的checkbox的值,然后加到sql筛选条件里
	String recordIds = request.getParameter("recordIds") == null ? "" : request.getParameter("recordIds");
	List<String> idList = Arrays.asList(recordIds.split(","));
    //......把idList作为筛选条件加到原来的列表sql里
    
    
    //得到最终的结果列表:resultList  
    //注:构建resultList时,就要在需要换行的位置加入 \r\n 元素
    
    
    //开始构建excel
    try {
            //1.在内存中创建一个excel文件
            HSSFWorkbook hssfWorkbook = new HSSFWorkbook();

            //2.创建工作簿
            HSSFSheet sheet = hssfWorkbook.createSheet();

            // 设置列宽
            sheet.setColumnWidth(0, 7000);
            sheet.setColumnWidth(1, 7000);
            sheet.setColumnWidth(2, 7000);
            sheet.setColumnWidth(3, 7000);
            sheet.setColumnWidth(4, 7000);
            sheet.setColumnWidth(5, 7000);
            sheet.setColumnWidth(6, 7000);
            sheet.setColumnWidth(7, 7000);

            //3.创建标题行
            HSSFRow titleRow = sheet.createRow(0);
            titleRow.createCell(0).setCellValue("列名0");
            titleRow.createCell(1).setCellValue("列名1");
            titleRow.createCell(2).setCellValue("列名2需要换行展示");
            titleRow.createCell(3).setCellValue("列名3");
            titleRow.createCell(4).setCellValue("列名4");
            titleRow.createCell(5).setCellValue("列名5");
            titleRow.createCell(6).setCellValue("列名6");
            titleRow.createCell(7).setCellValue("列名7");

            //4.遍历数据,创建数据行
            for (int i = 0; i < resultList.size(); i++) {
                Object[] objs = (Object[]) resultList.get(i);

                //获取最后一行的行号
                int lastRowNum = sheet.getLastRowNum();
                HSSFRow dataRow = sheet.createRow(lastRowNum + 1);
                dataRow.createCell(0).setCellValue(objs[0].toString());
                dataRow.createCell(1).setCellValue(objs[1].toString());
				
				//第3列需要换行展示,特殊处理如下:
                HSSFCell cell2 = dataRow.createCell(2);
                HSSFCellStyle cellStyle=hssfWorkbook.createCellStyle();
                cellStyle.setWrapText(true);
                cell2.setCellStyle(cellStyle);
                //前提:构建resultList时,就在objs[2]中相应位置加入了 \r\n 元素
                //HSSFRichTextString会自动识别 \r\n 元素进行换行展示
                cell2.setCellValue(new HSSFRichTextString(objs[2].toString()));

                dataRow.createCell(3).setCellValue(objs[3].toString());
                dataRow.createCell(4).setCellValue(objs[4].toString());
                dataRow.createCell(5).setCellValue(objs[5].toString());
                dataRow.createCell(6).setCellValue(objs[6].toString());
                dataRow.createCell(7).setCellValue(objs[7].toString());
            }

            //5.创建文件名
            String fileName = "excel名称.xls";
            //6.获取输出流对象
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
            ServletOutputStream outputStream = response.getOutputStream();


            //7.写出文件,关闭流
            hssfWorkbook.write(outputStream);
            outputStream.flush();
            outputStream.close();

        } catch (Exception e) {
            e.printStackTrace();  
        }
}

导出效果

第三列换行了

java输出excel 换行 java导出excel换行_java_02


PS:保险起见,这种测试数据也打厚码了,应该不影响看效果