java前台传参后台条件导出 excel,及导出的excel 通用工具类

需求:

前台要导出excel表格,开始用的bootstrap table的tableExport.js插件导出但是只能导出当前页的数据,so 又改到了后台导出(悲催)

 

导出按钮:

JavaScript代码:

function supplierOutIncheckExport(){
    var url =inventoryObj.initStoreInventorycheckExportUrl;//请求后台要导出的地址
	//构建一个虚拟的form 表单并设置表单ID和名称提交方式等
    exportForm = document.createElement("form");
    exportForm.setAttribute('id','StorageInventoryVo')
    exportForm.setAttribute('name','StorageInventoryVo');
    exportForm.setAttribute("action", url);
    exportForm.setAttribute("contentType", 'application/x-xls');
    exportForm.setAttribute("hidden", true);
    exportForm.setAttribute("method", "post");
	//构建一个虚拟的input框并设置属性类型和值,并添入form表单中
    var userId = document.createElement("input");
    userId.type = "text";
    userId.name = "staffId";
    userId.value = currentUser.userId;
    exportForm.appendChild(userId);
    //构建一个虚拟的input框并设置属性类型和值,并添入form表单中
	var fileName = document.createElement("input");
    fileName.type = "text";
    fileName.name = "fileName";
    fileName.value = "库盘单(总部)报表.xls";
    exportForm.appendChild(fileName);
	//表单提交
    document.body.appendChild(exportForm);
    exportForm.submit();
}

java后台代码:

/**
	*
	* @Author: ruanyanghui
	* @Company: xxxx
	* @Description: 导出实时库存
	* @date 2018/12/6 14:35
	*/
	@PostMapping("/storageexport")
	public void getstorageexport(StorageInventoryVo vo, HttpServletResponse response) {
		vo = vo.getParams();
		String[] headArray = {"物品编码", "物品名称", "物品类别","所属仓库", "单位", "所属供应商", "订购状态",
				"标准门店价(¥)", "安全库存", "实时库存", "冻结库存", "总价(¥)"};
		List list = inventoryService.findStorageInventoryExport(vo.getStaffId(), vo.getGoodsName(), vo.getGoodsNo(), vo.isLowerThan(), vo.getSupplierName());
		List contentList = new ArrayList<>();
		if (list.size() > 0) {
			list.stream().forEach(entity -> {
				Object[] o = {
						entity.getGoodsNo(),//商品编码
						entity.getGoodsName(),
						entity.getGoodsTypeName(),
						entity.getSupplierName(),
						entity.getUnit(),
						entity.getSupplier(),
						entity.getIsBook(),
						entity.getStorePrice(),
						entity.getMinInventory(),
						entity.getActualInventory(),
						entity.getFreeze(),
						entity.getStorePrice().multiply(new BigDecimal(entity.getActualInventory()))
				};
				contentList.add(o);
			});
		} else {
			return;
		}
			ExeclUtil.ExportExcel(response, headArray, contentList, vo.getFileName());
	}

引入maven依赖:

        
            org.apache.poi
            poi
            3.9
        
        
            org.apache.poi
            poi-ooxml
            3.9
        

 

导出Excel工具类:

 此工具类也是我在网上找的,但是里面方法过时问题,还有导出文件名乱码的问题也被优化了,HXSSFWorkbook替换为了能处理跟多数据的SXSSFWorkbook,可以放心使用

package com.xxx.utils;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.*;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletResponse;


/**
 * @Author: ruanyanghui
 * @Company: xxx
 * @Description: Excel导出工具类
 * @date 2018/12/7 17:49
 */
public class ExeclUtil {

    /**
     * @param title
     * @param headers
     * @param dataset
     */
    public static InputStream exportExcel(String title, String[] headers, List dataset) {
        InputStream is;
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        // 声明一个工作薄
        SXSSFWorkbook workbook = new SXSSFWorkbook();
        // 生成一个表格
        Sheet sheet = workbook.createSheet(title);
        // 设置表格默认列宽度为15个字节
        sheet.setDefaultColumnWidth(15);
        // 生成一个样式
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setFontHeightInPoints((short) 12);
        font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
        style.setFillForegroundColor((short) 1);
        // 把字体应用到当前的样式
        style.setFont(font);
        // 生成并设置另一个样式
        CellStyle style2 = workbook.createCellStyle();

        // 生成另一个字体
        Font font2 = workbook.createFont();
        font2.setBoldweight(XSSFFont.BOLDWEIGHT_NORMAL);
        // 把字体应用到当前的样式
        style2.setFont(font2);
        // 声明一个画图的顶级管理器
        Drawing patriarch = sheet.createDrawingPatriarch();
        // 定义注释的大小和位置,详见文档
        Row row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            Cell cell = row.createCell(i);
            cell.setCellStyle(style);
            XSSFRichTextString text = new XSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }
        // 遍历集合数据,产生数据行
        int index = 0;
        for (Object[] o : dataset) {
            index++;
            row = sheet.createRow(index);
            for (int i = 0; i < o.length; i++) {
                Cell cell = row.createCell(i);
                cell.setCellStyle(style2);
                try {
                    Object value = o[i];
                    if (value == null) {
                        value = "";
                    }
                    // 判断值的类型后进行强制类型转换
                    String textValue = null;
                    if (value instanceof Boolean) {
                        boolean bValue = (Boolean) value;
                        textValue = "男";
                        if (!bValue) {
                            textValue = "女";
                        }
                    } else if (value instanceof Date) {
                        Date date = (Date) value;
                        SimpleDateFormat sdf = new SimpleDateFormat(
                                "yyyy-MM-dd HH:mm:ss");
                        textValue = sdf.format(date);
                    } else if (value instanceof byte[]) {
                        // 有图片时,设置行高为60px;
                        row.setHeightInPoints(60);
                        // 设置图片所在列宽度为80px,注意这里单位的一个换算
                        sheet.setColumnWidth(i, (short) (35.7 * 80));
                        // sheet.autoSizeColumn(i);
                        byte[] bsValue = (byte[]) value;
                        XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0,
                                1023, 255, (short) 7, index, (short) 7, index);
                        anchor.setAnchorType(2);
                        patriarch.createPicture(anchor, workbook.addPicture(
                                bsValue, XSSFWorkbook.PICTURE_TYPE_JPEG));
                    } else {
                        // 其它数据类型都当作字符串简单处理
                        textValue = value.toString();
                    }
                    // 如果不是图片数据,就利用正则表达式判断textValue是否全部由数字组成
                    if (textValue != null) {
                        Pattern p = Pattern.compile("([0-9]\\d*\\.?\\d*)|(0\\.\\d*[0-9])");
                        Matcher matcher = p.matcher(textValue);
                        if (matcher.matches()) {
                            // 是数字当作double处理
                            cell.setCellValue(Double.parseDouble(textValue));
                        } else {
                            XSSFRichTextString richString = new XSSFRichTextString(
                                    textValue);
                             Font font3 = workbook.createFont();
                            richString.applyFont(font3);
                            cell.setCellValue(richString);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    // 清理资源
                }
            }
        }
        try {
            workbook.write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        is = new ByteArrayInputStream(os.toByteArray());
        return is;
    }

    public static void ExportExcel(HttpServletResponse response, String[] headArray,
                                   List contentList, String fileName) {
        // 读到流中
        InputStream inStream = exportExcel(fileName, headArray, contentList);
        // 设置输出的格式
        response.reset();
        response.setContentType("bin");
        try {
            response.addHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("gbk"), "iso8859-1"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 循环取出流中的数据
        byte[] b = new byte[1000];
        int len;
        try {
            while ((len = inStream.read(b)) > 0)
                response.getOutputStream().write(b, 0, len);
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}

 

你可能感兴趣的:(java,前端)