java后端导出excel文件

学习使用Apache的poi做下记录

        HSSFWorkbook workbook = new HSSFWorkbook();//创建一个工作簿
        HSSFSheet sheet = workbook.createSheet();

        //设置行宽度
        sheet.setColumnWidth(0, 20* 256);
        sheet.setColumnWidth(1, 20* 256);
        sheet.setColumnWidth(2, 50* 256);
        sheet.setColumnWidth(3, 20* 256);
        //冻结第一行
        sheet.createFreezePane( 0, 1, 0, 1 );

        //第一行标题格式
        HSSFCellStyle titleStyle = workbook.createCellStyle();
        titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        titleStyle.setAlignment(HorizontalAlignment.CENTER);
        Font fontTitle = workbook.createFont();
        fontTitle.setBold(true);//加粗
        fontTitle.setFontHeightInPoints(12);//设置字号
        titleStyle.setFont(fontTitle);


        //内容格式
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER);//水平居中

        HSSFRow row = sheet.createRow(0);//建立一行

        HSSFCell cell1 = row.createCell(0);//创建一列
        HSSFCell cell2 = row.createCell(1);
        HSSFCell cell3 = row.createCell(2);
        HSSFCell cell4 = row.createCell(3);

        cell1.setCellStyle(titleStyle);
        cell2.setCellStyle(titleStyle);
        cell3.setCellStyle(titleStyle);
        cell4.setCellStyle(titleStyle);

        cell1.setCellType(CellType.STRING);
        cell2.setCellType(CellType.STRING);
        cell3.setCellType(CellType.STRING);
        cell4.setCellType(CellType.STRING);

        cell1.setCellValue("姓名");
        cell2.setCellValue("性别");
        cell3.setCellValue("年龄");
        cell4.setCellValue("部门");



        String filename = "员工信息.xls";//文件名字
        try {
            filename = new String( filename.getBytes("gb2312"), "ISO8859-1" );
            response.setHeader("Content-Disposition", "attachment;filename="+filename);
            response.setContentType("application/x-download");
            OutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {

        }

猜你喜欢

转载自blog.csdn.net/ilovec1/article/details/53456762
今日推荐