Java代码实现下载Excel

该博客展示了如何使用Spring MVC和Apache POI库在Java中实现Excel文件的下载。通过创建一个Controller和Service,实现了从数据库查询数据,然后填充到Excel表格中,最后提供了下载Excel的功能。
package com.envision.hr.portal.center.mvc;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

public static void main(String[]args){

//=============================================================Controller=============================================================================>>>
public class DownloadExcelController {
    @Autowired
    DownloadExcelService downloadExcelService;

    @PostMapping(value = "downloadExcel")
    public void downloadExcel(HttpServletResponse response, @RequestBody String a) throws IOException {

        downloadExcelService.downloadExcel(response, "a");
    }
}

//=============================================================service=============================================================================>>>
public class DownloadExcelService {


    
    public void downloadExcel(HttpServletResponse response, String a) throws IOException {

        ArrayList header_list = new ArrayList();
        header_list.add(0, "工号");
        header_list.add(1, "姓名");
        header_list.add(2, "级别");
        header_list.add(3, "总分");
        header_list.add(4, "满意度");
        header_list.add(5, "优化人才");
        header_list.add(6, "人才发展体系");
        header_list.add(7, "得分");
        header_list.add(8, "价值传承");
        header_list.add(9, "规则");
        header_list.add(10, "能力");
        header_list.add(11, "氛围");
        header_list.add(12, "梯队");
        header_list.add(13, "组织");
        ArrayList header_code_list = new ArrayList();
        header_code_list.add(0, "a");
        header_code_list.add(1, "b");
        header_code_list.add(2, "c");
        header_code_list.add(3, "d");
        header_code_list.add(4, "e");
        header_code_list.add(5, "dd");
        header_code_list.add(6, "ee");
        header_code_list.add(7, "ww");
        header_code_list.add(8, "ss");
        header_code_list.add(9, "cc");
        header_code_list.add(10, "gg");
        header_code_list.add(11, "aa");
        header_code_list.add(12, "zz");
        header_code_list.add(13, "bb");

        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("report");
        String fileName = "人才" + ".xls";
        int rowNum = 1;
        String[] headers = (String[]) header_list.toArray(new String[0]);
        HSSFRow row = sheet.createRow(0);
        //在excel表中添加表头
        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }
        JdbcTemplate jdbcTemplate = DataSourcePageConfig.obtainJdbcConnect();
        StringBuffer nativeSql = new StringBuffer();
        nativeSql.append("select * from t ");
        List<Map<String, Object>> listResult = jdbcTemplate.queryForList(nativeSql.toString());
        //将查询到的数据放入对应的列
        for (int i = 0; i < listResult.size(); i++) {
            HSSFRow row1 = sheet.createRow(rowNum);
            String[] strArray = (String[]) header_code_list.toArray(new String[0]);
            List arrayToList = Arrays.asList(strArray);
            for (int j = 0; j < arrayToList.size(); j++) {
                Object values = listResult.get(i).get(arrayToList.get(j));
                if (values != null) {
                    row1.createCell(j).setCellValue(listResult.get(i).get(arrayToList.get(j)).toString());
                }
            }
            rowNum++;
        }
        System.out.println(downloadExcel(workbook));
/*        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());*/
    }


    public boolean downloadExcel(HSSFWorkbook wb) {
        boolean flag = true;
        Date date = new Date();
        String sdf = new SimpleDateFormat("yyyy-MM-dd").format(date.getTime());
        String filePath = "C:\\Users\\Administrator\\Desktop\\" + sdf + ".xls";
        File file = new File(filePath);

        FileOutputStream fos = null;
        try {

            fos = new FileOutputStream(file);
            wb.write(fos);
        } catch (IOException e) {
            e.printStackTrace();
            flag = false;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    flag = false;
                }
            }
        }
        return flag;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值