Strust2+POI导出exel表格且解决文件名中文乱码/不显示

第一步:下载并导入项目【[poi.3.17.jar](http://central.maven.org/maven2/org/apache/poi/poi/3.17/poi-3.17.jar)】

第二步:配置strust.xml

 <action name="returnLate_*" class="com.stureturnlate.moudels.biz.action.return_late.ReturnLateAction" method="{1}">
                <result name="list">/page/moudels/biz/return_late/returnLateList.jsp</result>
                <result name="openAdd">/page/moudels/biz/return_late/returnLateAdd.jsp</result>
                <!--<result name="openEdit">/page/biz/student/studentUpdate.jsp</result>-->
                <result name="openDetails">/page/moudels/biz/return_late/returnLateDetails.jsp</result>
    
                <!-- 导出Excel -->
                <result name="download" type="stream">
                    <param name="contentType">application/vnd.ms-excel</param><!-- 注意这里的ContentType -->
                    <param name="contentDisposition">attachment;filename="${fileName}.xls"</param><!-- 下载文件的名字 -->
                    <param name="bufferSize">1024</param><!-- 下载文件的大小 1048576=1M -->
                    <param name="inputName">excelFile</param><!-- 这里需要和Action里的变量名一致 -->
                </result>
    </action>

第三步:ReturnLateAction.class的导出方法

		/**
         * 导出
         * @return
         */
        public String download() throws Exception  {

            List<ReturnLateEntity> returnLateEntityList = new ArrayList<>();
            fileName = fileName+ DateTool.dateFormat(new Date());
           ==fileName=new String(fileName.getBytes("gb2312"), "iso8859-1");//防止中文乱码或不显示==
    		//TODO 第一步:声明excel的文档对象
            HSSFWorkbook returnLateExcel;
            try {
                //查询的结果,插入Excel填充数据
                String[] ids = returnLateIds.split(",");
                returnLateEntityList = returnLateService.selectAllReturnLate(ids);

                //TODO 第二步:获取excel的文档对象
                returnLateExcel = CreateExcel.createReturnLateExcel(returnLateEntityList);

                ByteArrayOutputStream output = new ByteArrayOutputStream();//字节数组输出流

                //TODO 第三步:写入字节数组输出流
                returnLateExcel.write(output);
                byte[] ba = output.toByteArray();

                //TODO 第四步:为输入流对象赋值
                excelFile = new ByteArrayInputStream(ba);

                output.flush();
                output.close();//关闭
            } catch (SQLException e) {
                System.out.println("晚归记录文件内容写入或者创建失败失败!");
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return "download";
        }

第四步:文件导出类CreateExcel.class

package com.stureturnlate.common;
import com.stureturnlate.moudels.vo.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;

import java.sql.SQLException;
import java.util.List;

/**
 * @author soldier
 * @title: CreateExcel
 * @projectName stu_return_late
 * @description: 文件导出Excel
 * @date 19-6-10下午9:56
 */
public class CreateExcel {

    public static HSSFWorkbook createReturnLateExcel(List<ReturnLateEntity> returnLateEntityList) throws SQLException {
        // 创建一个Excel文件
        HSSFWorkbook workbook = new HSSFWorkbook();//excel的文档对象
        // 创建一个工作表
        HSSFSheet sheet = workbook.createSheet("学生晚归记录");
        // 添加表头行
        HSSFRow hssfRow = sheet.createRow(0);
        // 设置单元格格式居中
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);

        int index = 0;
        // 添加表头内容
        HSSFCell headCell = hssfRow.createCell(index++);
        headCell.setCellValue("晚归编号");
        headCell.setCellStyle(cellStyle);

        headCell = hssfRow.createCell(index++);
        headCell.setCellValue("晚归学生");
        headCell.setCellStyle(cellStyle);

        headCell = hssfRow.createCell(index++);
        headCell.setCellValue("所属学院");
        headCell.setCellStyle(cellStyle);

        headCell = hssfRow.createCell(index++);
        headCell.setCellValue("学生所在宿舍");
        headCell.setCellStyle(cellStyle);

        headCell = hssfRow.createCell(index++);
        headCell.setCellValue("晚归时间");
        headCell.setCellStyle(cellStyle);

        headCell = hssfRow.createCell(index++);
        headCell.setCellValue("晚归原因");
        headCell.setCellStyle(cellStyle);

        headCell = hssfRow.createCell(index++);
        headCell.setCellValue("记录者工号");
        headCell.setCellStyle(cellStyle);

        headCell = hssfRow.createCell(index);
        headCell.setCellValue("记录者姓名");
        headCell.setCellStyle(cellStyle);

        // 添加数据内容
        for (int i = 0; i < returnLateEntityList.size(); i++) {
            hssfRow = sheet.createRow((int) i + 1);
            ReturnLateEntity returnLateEntity = returnLateEntityList.get(i);

            index = 0;
            // 创建单元格,并设置值
            HSSFCell cell = hssfRow.createCell(index++);
            cell.setCellValue(returnLateEntity.getReturnLateId());
            cell.setCellStyle(cellStyle);

            cell = hssfRow.createCell(index++);
            StudentEntity studentEntity = new StudentEntity();//获取学生名称
            cell.setCellValue(studentEntity.getStudentName());
            cell.setCellStyle(cellStyle);

            cell = hssfRow.createCell(index++);
            CollegeEntity collegeEntity = new CollegeEntity();//获取学院
            cell.setCellValue(collegeEntity.getCollegeName());
            cell.setCellStyle(cellStyle);

            cell = hssfRow.createCell(index++);
            HostelEntity hostelEntity = new HostelEntity();//获取宿舍名称
            cell.setCellValue(hostelEntity.getHostelName());
            cell.setCellStyle(cellStyle);

            cell = hssfRow.createCell(index++);
            cell.setCellValue(DateTool.dateTimeFormat(returnLateEntity.getReturnLateTime()));
            cell.setCellStyle(cellStyle);

            cell = hssfRow.createCell(index++);
            cell.setCellValue(returnLateEntity.getReturnLateCause());
            cell.setCellStyle(cellStyle);

            cell = hssfRow.createCell(index++);
            DormMasterEntity dormMasterEntity = new DormMasterEntity();
            cell.setCellValue(dormMasterEntity.getDormMasterId());
            cell.setCellStyle(cellStyle);

            cell = hssfRow.createCell(index);
            cell.setCellValue(dormMasterEntity.getDormMasterName());
            cell.setCellStyle(cellStyle);
        }

        try {
            return workbook;

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

jsp页面

<button type="button" onclick="exportExcel()" class="button border-black" id="exportExcel"><span
                class="icon-file-excel-o"></span> 导出

//请假单导出
function exportExcel(){
    var exportIds=new Array();
    var index = 0;
    var Checkbox=false;
    $("input[name='id[]']").each(function(){//取当前页面所有name='id[]'的input元素,循环每一个取到的元素,将其value的值赋
        if (this.checked==true) {//如果被选中
            Checkbox=true;//记录有多选框被选中了
            var exportId = $(this).val();
            // alert(exportId);
            exportIds[index++] = exportId;
        }
    });
    if (Checkbox){//如果有被选中的
        var t=confirm("您确认要导出选中的内容吗?");
        if (t==false) return false;
        // $.ajax({
        //     type: "post",
        //     data: {
        //         fileName: fileName,
        //         returnLateIds: exportIds,
        //     },
        //     url: projectPath + "/biz/returnLate_download.action",
        //     success: function (data) {
        //     }
        // })
        window.location.href = projectPath + "/biz/returnLate_download.action?fileName=学生晚归记录表&returnLateIds=" + exportIds;
    }
    else{
        alert("请选择您要导出的内容!");
        return false;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值