java poi导出Excel表格

在这里记录一下,以便以后查找。

配置pom.xml

        <poi.version>3.14</poi.version>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>${poi.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>${poi.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>${poi.version}</version>
        </dependency>
controller层代码:
    /**
     * 导出订单销售记录数据信息
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/exportSaleRecord", method = RequestMethod.GET)
    public ResponseEntity<byte[]> exportSaleRecord(HttpServletRequest request, HttpServletResponse response, String startDate, String endDate, String storeId, String searchKey) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        //查询条件的判断
        if (searchKey != null) {
            searchKey = URLDecoder.decode(searchKey, "UTF-8");
        }

        List<AugeStore> allStoreList = null;
        if (Strings.isNullOrEmpty(storeId)) {
            allStoreList = (List<AugeStore>) session.getAttribute("storeList");
        } else {
            allStoreList = new ArrayList<>();
            AugeStore augeStore = new AugeStore();
            augeStore.setId(storeId);
            allStoreList.add(augeStore);
        }

        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        String fileName = new String(("订单销售明细.xls").getBytes("UTF-8"), "iso-8859-1");
        headers.setContentDispositionFormData("attachment", fileName);
        byte[] bytes = saleService.exportSaleRecord(request, response, Strings.emptyToNull(startDate), Strings.emptyToNull(endDate), allStoreList, Strings.emptyToNull(searchKey));
        return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.CREATED);
    }

SaleService.java中的exportSaleRecord方法:

    /**
     * 导出销售记录数据信息
     *
     * @param request
     * @param response
     * @return
     */
    public byte[] exportSaleRecord(HttpServletRequest request, HttpServletResponse response, String startDate, String endDate, List<AugeStore> augeStoreList, String searchKey) {
        int count = augeSaleMapper.selectSaleCount(startDate, endDate, augeStoreList, searchKey);
        List<Map> maps = augeSaleMapper.selectSale(startDate, endDate, 0, count, augeStoreList, searchKey);//数据库查询数据

        String[] rowsName = new String[]{"订单号", "手机号码", "消费总价", "支付方式", "所在店铺", "设备编号", "消费时间"};
        String[] parames = new String[]{"orderNumber", "phone", "sumPrice", "payStyle", "name", "deviceId", "createTime"};
        //创建导出工具类
        ExcelExport excelExport = new ExcelExport();
        excelExport.setHeardKey(parames).setData(maps).setHeardList(rowsName);
        byte[] bytes = excelExport.exportExport(request, response);
        return bytes;
    }

ExcelExport.java工具类

import java.io.*;
import java.math.BigDecimal;
import java.util.*;
import com.google.common.base.Strings;
import com.xiaodou.park.util.ExcelException;
import org.apache.poi.hssf.usermodel.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ExcelExport {

    //表头
    private String title;
    //各个列的表头
    private String[] heardList;
    //各个列的元素key值
    private String[] heardKey;
    //需要填充的数据信息
    private List<Map> data;
    //字体大小
    private int fontSize = 14;
    //行高
    private int rowHeight = 30;
    //列宽
    private int columWidth = 200;
    //工作表
    private String sheetName = "sheet1";


    public String getTitle() {
        return title;
    }

    public ExcelExport setTitle(String title) {
        this.title = title;
        return this;
    }

    public String[] getHeardList() {
        return heardList;
    }

    public ExcelExport setHeardList(String[] heardList) {
        this.heardList = heardList;
        return this;
    }

    public String[] getHeardKey() {
        return heardKey;
    }

    public ExcelExport setHeardKey(String[] heardKey) {
        this.heardKey = heardKey;
        return this;
    }

    public List<Map> getData() {
        return data;
    }

    public ExcelExport setData(List<Map> data) {
        this.data = data;
        return this;
    }

    public int getFontSize() {
        return fontSize;
    }

    public ExcelExport setFontSize(int fontSize) {
        this.fontSize = fontSize;
        return this;
    }

    public int getRowHeight() {
        return rowHeight;
    }

    public ExcelExport setRowHeight(int rowHeight) {
        this.rowHeight = rowHeight;
        return this;
    }

    public int getColumWidth() {
        return columWidth;
    }

    public ExcelExport setColumWidth(int columWidth) {
        this.columWidth = columWidth;
        return this;
    }

    public String getSheetName() {
        return sheetName;
    }

    public ExcelExport setSheetName(String sheetName) {
        this.sheetName = sheetName;
        return this;
    }

    /**
     * 开始导出数据信息
     *
     * @throws ExcelException 抛出数据异常类
     */
    public byte[] exportExport(HttpServletRequest request, HttpServletResponse response) throws ExcelException {
        //检查参数配置信息
        checkConfig();

        //创建工作簿
        HSSFWorkbook wb = new HSSFWorkbook();
        //创建工作表
        HSSFSheet wbSheet = wb.createSheet(this.sheetName);
        //在第0行创建rows
        HSSFRow row = wbSheet.createRow((int) 0);
        //创建单元格,设置表头,表头居中
        HSSFCellStyle style = wb.createCellStyle();
        //设置单元格样式
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        HSSFFont font = wb.createFont();
        font.setFontHeightInPoints((short) this.fontSize);

        //设置列头元素
        HSSFCell cellHead = null;
        for (int i = 0; i < heardList.length; i++) {
            cellHead = row.createCell(i);
            cellHead.setCellValue(heardList[i]);
            cellHead.setCellStyle(style);
        }
        //开始写入实体数据信息
        style.setFont(font);
        for (int i = 0; i < data.size(); i++) {
            HSSFRow roww = wbSheet.createRow((int) i + 1);
            Map map = data.get(i);
            HSSFCell cell = null;
            for (int j = 0; j < heardKey.length; j++) {
                cell = roww.createCell(j);
                cell.setCellStyle(style);
                Object valueObject = map.get(heardKey[j]);
                String value = null;
                if (valueObject == null) {
                    valueObject = "";
                }

                if (valueObject instanceof String) {
                    //取出的数据是字符串直接赋值
                    value = (String) map.get(heardKey[j]);
                } else if (valueObject instanceof Integer) {
                    //取出的数据是Integer
                    value = String.valueOf(((Integer) (valueObject)).floatValue());
                } else if (valueObject instanceof BigDecimal) {
                    //取出的数据是BigDecimal
                    value = String.valueOf(((BigDecimal) (valueObject)).floatValue());
                } else {
                    value = valueObject.toString();
                }
                cell.setCellValue(Strings.isNullOrEmpty(value) ? "" : value);
            }
        }

        //设置行高
        //设置行高的过程需要注意的一不包含标题
        for (int i = 0; i < data.size() + 1; i++) {
            HSSFRow hssfRow = wbSheet.getRow(i);
            hssfRow.setHeightInPoints(this.rowHeight);
        }
        //设置列宽
        if (data.size() > 0) {
            for (int i = 0; i < data.get(0).size(); i++) {
                wbSheet.setColumnWidth(i, MSExcelUtils.pixel2WidthUnits(this.columWidth));
            }
        } else {
            for (int i = 0; i < heardList.length; i++) {
                wbSheet.setColumnWidth(i, MSExcelUtils.pixel2WidthUnits(this.columWidth));
            }
        }

        //导出数据
        try {
            //设置Http响应头告诉浏览器下载这个附件
            response.setHeader("Content-Disposition", "attachment;Filename=" + System.currentTimeMillis() + ".xls");
            OutputStream outputStream = response.getOutputStream();
            wb.write(outputStream);
            outputStream.close();
            return wb.getBytes();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new ExcelException("导出Excel出现严重异常,异常信息:" + ex.getMessage());
        }

    }

    /**
     * 检查数据配置问题
     *
     * @throws ExcelException 抛出数据异常类
     */
    protected void checkConfig() throws ExcelException {
      /*  if (data == null || data.size() == 0) {
            throw new ExcelException("导出的数据不能为空或者为NULL");
        }*/

        if (heardKey == null || heardList.length == 0) {
            throw new ExcelException("列名数组不能为空或者为NULL");
        }

        if (fontSize < 0 || rowHeight < 0 || columWidth < 0) {
            throw new ExcelException("字体、宽度或者高度不能为负值");
        }

        if (Strings.isNullOrEmpty(sheetName)) {
            throw new ExcelException("工作表表名不能为NULL");
        }
    }
}

结果示例(导出的Excel表格示例):


猜你喜欢

转载自blog.csdn.net/qq_23543983/article/details/80339421