从POI 生成EXCEL 到二进制下载

本文介绍如何利用Java POI库中的HSSF组件创建Microsoft Excel文件。通过具体代码示例展示了如何设置工作表、行和单元格,并实现样式设置及单元格合并等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

POI提供API给Java程序对Microsoft Office格式档案读和写的功能.非常好用.


结构如下:


HSSF - 提供读写Microsoft Excel格式档案的功能。


XSSF - 提供读写Microsoft Excel OOXML格式档案的功能。
HWPF - 提供读写Microsoft Word格式档案的功能。
HSLF - 提供读写Microsoft PowerPoint格式档案的功能。
HDGF - 提供读写Microsoft Visio格式档案的功能。
这次使用的格式是 HSSF - 提供读写Microsoft Excel格式档案的功能。

Service.
public static byte[] getByteExcel(xxx dto) throws IOException {
        
        XSSFWorkbook workbook = new XSSFWorkbook();
    
        XSSFSheet sheet = workbook.createSheet(dto.getCreater().getcName() + "_sheet名");
        //初始化第一行
        newBasicInfo(sheet, workbook);
        
        // 第二行 设置员工信息
        employeeInfo(sheet, workbook, dto.getcName());

        // 第三-五行 备注
        noteInfo(sheet, workbook, dto.getNote());
	//可以直接写硬盘
        //FileOutputStream outPut = new FileOutputStream("d:\\excel\\workbook.xls");
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        workbook.write(os);
        byte[] content = os.toByteArray();
        
        workbook.close();

        return content;
    }

  /**
     * 初始化第一行
     * @param sheet
     * @param workbook
     */
    private static void newBasicInfo(XSSFSheet sheet, XSSFWorkbook workbook) {
        //初始化第一行
        XSSFRow row1 = sheet.createRow(0);
        //第一行内容
        Cell cell0 = row1.createCell(0);
        Cell cell1 = row1.createCell(1);
        Cell cell2 = row1.createCell(2);
        Cell cell3 = row1.createCell(3);
        Cell cell4 = row1.createCell(4);
        cell0.setCellValue("姓名");
        cell1.setCellValue("岗位");
        cell2.setCellValue("所属部门");
        cell3.setCellValue("分管领导");
        cell4.setCellValue("起止时间");
	// 单元格合并
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 4, 5));
        //样式 颜色填充
        fillColor(workbook, false, IndexedColors.LIGHT_CORNFLOWER_BLUE
                .getIndex(), cell0, cell1, cell2 , cell3, cell4);
    }
  /**
     * 填充背景颜色和粗体居中  -- 在这边多处使用 提出了方法
     * @param workbook
     * @param flg 字体粗体设定有无flg
     * @param fg 颜色/可用 IndexedColors类
     * @param cells 多个cell
     */
    private static void fillColor(XSSFWorkbook workbook, boolean flg, short fg, Cell... cells) {
        XSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFillForegroundColor(fg);
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        
        cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
        cellStyle.setBorderLeft(BorderStyle.THIN);//左边框
        cellStyle.setBorderTop(BorderStyle.THIN);//上边框
        cellStyle.setBorderRight(BorderStyle.THIN);//右边框
        cellStyle.setAlignment(HorizontalAlignment.CENTER);//居中
        
        if (flg) {
            XSSFFont font = workbook.createFont();
            font.setBold(true);
            cellStyle.setFont(font);
        }
        
        for (Cell cell : cells) {
            cell.setCellStyle(cellStyle);
        }
    }
Controller.
	@GetMapping("/download")
    public HttpEntity<byte[]> exportProject(xxxx xx)throws Exception {

		String excelName = "";
    		byte[] data =  ExcelExportService.getByteExcel(xxx); //调用生成Excel方法
		HttpHeaders httpHeaders = new HttpHeaders(); 
		httpHeaders.setContentLength(data.length); //设置长度
		httpHeaders.setContentType(MediaType.valueOf("application/vnd.ms-excel")); // ContentType类型 application/vnd.ms-excel 必要
 
		httpHeaders.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode(excelName + ".xls", "UTF-8")); //必要
		HttpEntity<byte[]> httpEntity = new ResponseEntity<byte[]>(data, httpHeaders, HttpStatus.OK); //必要
		return httpEntity;
    }


Jsp.
要用a标签. 这边因为业务原因 写了js
<a class="automateHrefExcel">导出Excel</a>
	$('body').on('click','.automateHrefExcel',function(){
		var = xxx;
		window.location.href = '../download?xxx='+str;  
	})



然后就是效果啦.
a标签的excel .(图片被我二次编辑干掉了 郁闷..)


点击后 弹出下载框..(图片被我二次编辑干掉了 郁闷..)


保存后




好啦.大概就是这些, 如果朋友们有更好的实现方式 求分享啊~~~ 


另外 代码中不足之处 请告知! 谢谢咯~~



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值