JavaWeb 利用POI实现前端数据到Excel导出

需求

我们用Ext的gridPanel完成了如下表格:
这里写图片描述
现在我们需要对前端表格中的数据导出到本地的Excel格式,如下:
这里写图片描述

实现

1、简介

Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。自2009-09-28后,推出了3.5版本,提供了对Office2007的支持,

关于Apache POI一些重要的地方:
- 1)Apache POI 包含适合Excel97-2007(.xls文件)的HSSF实现.
- 2)Apache POI XSSF实现用来处理Excel2007文件(.xlsx).
- 3)Apache POI HSSF和XSSF提供了读/写/修改Excel表格的机制.
- 4)Apache POI 提供了XSSF的一个扩展SXSSF用来处理非常大的Excel工作单元.SXSSF
API需要更少的内存,因此当处理非常大的电子表格同时堆内存又有限时,很合适使用.
- 5)有两种模式可供选择–事件模式和用户模式.事件模式要求更少的内存,因为用tokens来读取Excel并处理.用户模式更加面向对象并且容易使用,因此在我们的示例中使用用户 模式.
- 6)Apache POI为额外的Excel特性提供了强大支持,例如处理公式,创建单元格样式–颜色,边框,字体,头部,脚部,数据验证,图像,超链接等.

2、实现步骤

2.1 POI依赖的jar包
2.1.1需要导入的jar包

  • Poi-3.10-Final.jar (用于xls)
  • Poi-ooxml-3.10-Final.jar (用于xlsx)
  • Poi-ooxml-schemas-3.10.jar
  • Xmlbeans-2.30.jar
  • dom4j-1.6.1.jar
  • poi-scratchpad-3.10-FINAL-20140208.jar(用于word,ppt)

2.1.2maven构建项目
我们只需要在pom.xml写入依赖

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

2.2controller层的具体实现
service取数据的过程和前端gridpanel获取数据相同即可

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.salmon.share.entity.dataApplyManager.PipePermissionApply;
import com.salmon.share.service.dataApplyManager.DataPermissionApplyService;

@RestController
@RequestMapping("/exportExcelController")
public class PartExportController {

    @Autowired
    private DataPermissionApplyService dataPermissionApplyService;

    //导出配件列表
    @RequestMapping(value = "/exportExcel", method={RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public void exportReportStaticsData( HttpServletRequest request, HttpServletResponse response) {
        String mether =request.getMethod();
        //获取查询数据,在service层实现
        List<PipePermissionApply> list = dataPermissionApplyService.getDataToExportExcel();

        HSSFWorkbook wb = new HSSFWorkbook();//声明工
        Sheet sheet = wb.createSheet("数据权限申请审批表");//新建表
        sheet.setDefaultColumnWidth(15);//设置表宽
        HSSFCellStyle style = wb.createCellStyle();
        org.apache.poi.hssf.usermodel.HSSFFont font = wb.createFont();
        font.setFontHeightInPoints((short) 12);
        HSSFCellStyle headerStyle = wb.createCellStyle();
        org.apache.poi.hssf.usermodel.HSSFFont headerFont = wb.createFont();
        headerFont.setFontHeightInPoints((short) 14);
        headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        headerStyle.setFont(headerFont);
        CellRangeAddress cra0 = new CellRangeAddress(0, 1,0,9);
        sheet.addMergedRegion(cra0);
        sheet.setDefaultColumnWidth((short) 15);
        Row row = sheet.createRow(0);
        Cell cell1 = row.createCell(0);

        cell1.setCellValue("数据权限申请审批表");
        cell1.setCellStyle(headerStyle);
        //设置字体样式
        org.apache.poi.hssf.usermodel.HSSFFont titleFont = wb.createFont();
        titleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        style.setFont(titleFont);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        Row row1 = sheet.createRow(2);
        Cell cell = row1.createCell(0);
        cell.setCellValue("申请流水号");
        cell.setCellStyle(style);
        cell = row1.createCell(1);
        cell.setCellValue("申请事由");
        cell.setCellStyle(style);
        cell = row1.createCell(2);
        cell.setCellValue("申请人");
        cell.setCellStyle(style);
        cell = row1.createCell(3);
        cell.setCellValue("提交时间");
        cell.setCellStyle(style);
        cell = row1.createCell(4);
        cell.setCellValue("开始时间");
        cell.setCellStyle(style);
        cell = row1.createCell(5);
        cell.setCellValue("到期时间");
        cell.setCellStyle(style);
        cell = row1.createCell(6);
        cell.setCellValue("审批人");
        cell.setCellStyle(style);
        cell = row1.createCell(7);
        cell.setCellValue("审批时间");
        cell.setCellStyle(style);
//      cell = row1.createCell(8);
//      cell.setCellValue("最小值");
//      cell = row1.createCell(9);
//      cell.setCellValue("最小值时间");
//      cell.setCellStyle(style);
        //时间转字符串的格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0, imax = list.size(); i < imax; i++) {
            row1 = sheet.createRow(i + 3);
            if (list.get(i).getCode()== null||"".equals(list.get(i).getCode())) {
                row1.createCell(0).setCellValue("-");
            } else {
                row1.createCell(0).setCellValue(list.get(i).getCode());
            }
            if (list.get(i).getApply_reason() == null ||"".equals(list.get(i).getApply_reason())) {
                row1.createCell(1).setCellValue("-");
            } else {
                row1.createCell(1).setCellValue(list.get(i).getApply_reason());
            }
            if (list.get(i).getApply_user_name() == null ||"".equals(list.get(i).getApply_user_name())) {
                row1.createCell(2).setCellValue("-");
            } else {
                row1.createCell(2).setCellValue(list.get(i).getApply_user_name());
            }
            if (list.get(i).getSubmit_time() == null||"".equals(list.get(i).getSubmit_time())) {
                row1.createCell(3).setCellValue("-");
            } else {
                row1.createCell(3).setCellValue(sdf.format(list.get(i).getSubmit_time()));
            }
            if (list.get(i).getStart_time() == null||"".equals(list.get(i).getStart_time())) {
                row1.createCell(4).setCellValue("-");
            } else {
                row1.createCell(4).setCellValue(sdf.format(list.get(i).getStart_time()));
            }
            if (list.get(i).getEnd_time() == null||"".equals(list.get(i).getEnd_time())) {
                row1.createCell(5).setCellValue("-");
            } else {
                row1.createCell(5).setCellValue(sdf.format(list.get(i).getEnd_time()));
            }
            if (list.get(i).getApproval_user_name() == null||"".equals(list.get(i).getApproval_user_name())) {
                row1.createCell(6).setCellValue("-");
            } else {
                row1.createCell(6).setCellValue(list.get(i).getApproval_user_name());
            }
            if (list.get(i).getApproval_time() == null||"".equals(list.get(i).getApproval_time())) {
                row1.createCell(7).setCellValue("-");
            } else {
                row1.createCell(7).setCellValue(sdf.format(list.get(i).getApproval_time()));
            }

        }
        response.reset();
        response.setContentType("application/msexcel;charset=UTF-8");
        try {
            SimpleDateFormat newsdf=new SimpleDateFormat("yyyyMMddHHmmss");
            String date = newsdf.format(new Date());
            response.addHeader("Content-Disposition", "attachment;filename=\""
                    + new String(("数据权限申请审批表" + date + ".xls").getBytes("GBK"),
                            "ISO8859_1") + "\"");
            OutputStream out = response.getOutputStream();
            wb.write(out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(null, "导出失败!");
            e.printStackTrace();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "导出失败!");
            e.printStackTrace();
        }
    }
}

2.3前台调用
我们在前台设置一个按钮,在按钮点击触发事件中写

var urlLink = window.loction.href;//获取当前页面的链接
var exportLink = urlLink .split("/xxxx")[0];//按照实际情况获取服务器链接
exportLink +="/exportExcelController/exportExcel";//拼接controller访问地址
window.open(exportLink ,'_self');进行访问

3、拓展–HSSFCellStyle样式详解

// 生成一个样式
HSSFCellStyle style = workbook.createCellStyle();
// 设置这些样式
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//水平居中 
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直居中

 // 背景色
style.setFillForegroundColor(HSSFColor.YELLOW.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); 
style.setFillBackgroundColor(HSSFColor.YELLOW.index); 

// 设置边框
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);  
// 自动换行  
style.setWrapText(true);  

// 生成一个字体
HSSFFont font = workbook.createFont();
font.setFontHeightInPoints((short) 10);
font.setColor(HSSFColor.RED.index);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
font.setFontName("宋体");

// 把字体 应用到当前样式
style.setFont(font);

//style设置好后,为cell设置样式
cell.setCellStyle(style)//cell为已有的单元格

更多详细解释请看:
http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFCellStyle.html

  • 2
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值