Apache

Excel有两种版本,一种是.xls类型,另一种是.xlsx类型。所以在导出的时候一定要对症下药!!!

今天主要说的是导出.xlsx类型的Excel,用到的就是Apache POI中的XSSFWorkbook,感觉炒鸡好用~

1、首先在maven项目中引入依赖

        <dependency>
		    <groupId>org.apache.poi</groupId>
		    <artifactId>poi</artifactId>
		    <version>3.17</version>
		</dependency>
		
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>
        
        <dependency>
		    <groupId>org.apache.poi</groupId>
		    <artifactId>poi-ooxml-schemas</artifactId>
		    <version>3.17</version>
		</dependency>

我用的是3.17版本的,没有选那么高是因为高版本的POI中Workbook.close()方法不见了!

2、直接开写代码

public void exportEnquiryExcel(List<Student> students, HttpServletResponse response) throws Exception {
        /** 行头 */
        String[] sheetHeader = HeaderConstant.SHEET_HEADERS;
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook();
        XSSFSheet sheet = xssfWorkbook.createSheet("数据模板");
        /** 设置每一列的宽度 */
        sheet.setColumnWidth(0, 23*256);
        sheet.setColumnWidth(1, 19*256);
        sheet.setColumnWidth(2, 25*256);
        /** 设置高度 */
        sheet.setDefaultRowHeightInPoints(14);
        /** 设置样式 */
        XSSFCellStyle cellStyle = xssfWorkbook.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        Font font = xssfWorkbook.createFont();
        font.setBold(false);
        cellStyle.setFont(font);
        XSSFRow row = sheet.createRow(0);
        /** 创建表头*/
        for(int i = 0; i < sheetHeader.length; i ++) {
            Cell cell = row.createCell(i);
            cell.setCellValue(sheetHeader[i]);
            cell.setCellStyle(cellStyle);
        }
        /** 封装数据 */
        for(int i = 0; i < students.size(); i ++) {
            row = sheet.createRow(i + 1);
            Student student = students.get(i);
            /** 学号 */
            row.createCell(0).setCellValue(student.getNo());
            /** 姓名 */
            row.createCell(1).setCellValue(student.getName());
            /** 性别 */
            row.createCell(2).setCellValue(student.getSex());
            
        }
        OutputStream outputStream = response.getOutputStream(); 
        response.reset(); 
        response.setContentType("application/vnd.ms-excel");    
        response.setHeader("Content-disposition", "attachment;filename="+URLEncoder.encode("数据模板.xlsx", "UTF-8"));      
        xssfWorkbook.write(outputStream);
        outputStream.flush();    
        outputStream.close();
        xssfWorkbook.close();
    }

这样就OK了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值