java导数据到Excel

侵删。不足之处请谅解。

1,Excel导出工具类

package cn.ljs.util;

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

public class ExcelUtil {
    /**
     * 导出Excel
     * @param sheetName sheet名称
     * @param title 标题
     * @param values 内容
     * @param wb HSSFWorkbook对象
     * @return
     */
    public static HSSFWorkbook getHSSFWorkbook(String sheetName,String []title,String [][] values, HSSFWorkbook wb){

        // 第一步,创建一个HSSFWorkbook,对应一个Excel文件
        if(wb == null){
            wb = new HSSFWorkbook();
        }

        // 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet(sheetName);

        // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
        HSSFRow row = sheet.createRow(0);

        // 第四步,创建单元格,并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

        //声明列对象
        HSSFCell cell = null;

        //创建标题
        for(int i=0;i<title.length;i++){
            cell = row.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(style);
        }

        //创建内容
        for(int i=0;i<values.length;i++){
            row = sheet.createRow(i + 1);
            for(int j=0;j<values[i].length;j++){
                //将内容按顺序赋给对应的列对象
                row.createCell(j).setCellValue(values[i][j]);
            }
        }
        return wb;
    }
}

2,Java导出数据到Excel接口

/**
     * 导出数据到excel
     * @return
     */
    @RequestMapping("exportExcel")
    @ResponseBody
    public void exportExcel(HttpServletRequest request,HttpServletResponse response) {
        try {
            //获取导出到excel 的数据
            //sql查询的时候,要将查询出的每个字段起个别名 别名的格式必须是 从0开始依次递增
            //例如      select id '0', userName '1', userPhone '2', userAddress '3'  from user 
            //这里是按页面传的参查需要导出的数据,这里是导出企业信息,比如企业名称等等。。
            String enterpriseName = request.getParameter("enterpriseName");//企业名称
            String contacts = request.getParameter("contacts");//联系人
            String startTime = request.getParameter("startTime");//起时间
            String stopTime = request.getParameter("stopTime");//止时间
            GxptUser gxptUser = new GxptUser();
            if(enterpriseName!=null&&!"".equals(enterpriseName)) {
                gxptUser.setEnterpriseName(enterpriseName);
            }
            if(contacts!=null&&!"".equals(contacts)) {
                gxptUser.setContacts(contacts);
            }
            if(startTime!=null&&!"".equals(startTime)) {
                gxptUser.setStartTime(startTime);
            }
            if(stopTime!=null&&!"".equals(stopTime)) {
                gxptUser.setStopTime(stopTime);
            }
            List<Map<String, Object>> exportDataList = sysUserService.queryGxptUserAll(gxptUser);//查询需要导出的数据
            
            //设置excel标题   查询几个字段,就写几个标题,标题顺序跟0123对应
            String[] title = {"企业名称","社会统一信用代码","联系人","联系邮箱","联系电话","创建时间"};
            String[][] content = new String[exportDataList.size()][];
            Map<String, Object> map = new HashMap<>();
            
            for (int i = 0; i < exportDataList.size(); i++) {
                content[i] = new String[title.length];
                map = exportDataList.get(i);
                content[i][0] = (String) map.get("enterpriseName");
                content[i][1] = (String) map.get("enterpriseCode");
                content[i][2] = (String) map.get("contacts");
                if(map.get("mail")!=null && !"".equals(map.get("mail"))) {
                    content[i][3] = (String) map.get("mail");
                }else {
                    content[i][3] = "";
                }
                content[i][4] = (String) map.get("phone");
                content[i][5] = (String) map.get("createtimes");
                
            }
            //excel文件名 ,文件名字随便起
            SimpleDateFormat df = new SimpleDateFormat("MM月dd日HH时mm分");// 设置日期格式
            String fileName = "****企业表("+df.format(new Date())+").xls";
            
            //sheet名
            String sheetName = "****企业表";
            
            //创建HSSFWorkbook 
            HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
            
            //响应到客户端
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
                response.setContentType("application/octet-stream;charset=ISO8859-1");
                response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
                response.addHeader("Pargam", "no-cache");
                response.addHeader("Cache-Control", "no-cache");
                
                OutputStream os = response.getOutputStream();
                wb.write(os);
                os.flush();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

3,js访问java后台导出数据到Excel

  

          //搜索条件根据项目需求,不需要删掉就行
          var
enterpriseName = this.formInline.enterpriseName; var contacts = this.formInline.contacts; var startTime = ''; var stopTime = ''; if(this.formInline.kssj !=null && this.formInline.kssj !=''){ startTime = this.formInline.kssj; } if(this.formInline.jssj !=null && this.formInline.jssj !=''){ stopTime = this.formInline.jssj; }
          //用Ajax请求后台接口导不出来数据,接口可以正常访问 location.href
="../../UserController/exportExcel?enterpriseName="+enterpriseName+"&contacts="+contacts +"&startTime="+startTime+"&stopTime="+stopTime;

4,点击导出按钮,浏览器下方显示这个就成功了。最后再检查下导出数据是否有问题

原文地址:https://www.cnblogs.com/ljmm/p/12597111.html