springboot整合poi导出excel方法(三)

再分享一种excel导出 这种是需要反射获取实体类的get方法类实现动态获取值
依赖

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

实体类

import java.io.Serializable;
import java.math.BigDecimal;

/**
 * @Author: Administrator
 * @Description:
 * @Date: 2019-08-25 19:04
 * @Modified By: 商品信息
 */
public class Items implements Serializable{

    private String number;

    private String name;

    private BigDecimal amount;

    private String detil;

    private String batch;

    private Long stock;

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public BigDecimal getAmount() {
        return amount;
    }

    public void setAmount(BigDecimal amount) {
        this.amount = amount;
    }

    public String getDetil() {
        return detil;
    }

    public void setDetil(String detil) {
        this.detil = detil;
    }

    public String getBatch() {
        return batch;
    }

    public void setBatch(String batch) {
        this.batch = batch;
    }

    public Long getStock() {
        return stock;
    }

    public void setStock(Long stock) {
        this.stock = stock;
    }
}

控制层

import com.example.springboot08.com.pojo.Items;
import com.example.springboot08.com.util.ExportExcel;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: Administrator
 * @Description:
 * @Date: 2019-08-25 18:55
 * @Modified By:
 */
@Controller
@RequestMapping("/ExcelController")
public class ExcelController {

    private static final String dateFormat = "yyyy-MM-dd-HH-mm";

    @RequestMapping("/exportExcel")
    @ResponseBody
    public void exportExcel(@RequestParam("uuid") String uuid, HttpServletResponse response){
        //定义标题内容
        String title = "商品信息";
        String[] headers = { "商品编号", "商品名称", "商品价格", "商品明细", "批次号", "库存剩余"};
        List<Items> itemsList=new ArrayList<Items>();
        Items items=new Items();
        items.setNumber("1");
        items.setName("小米3");
        items.setAmount(new BigDecimal("1234"));
        items.setDetil("很好用哦!");
        items.setBatch("1001");
        items.setStock(1000L);
        Items items2=new Items();
        items2.setNumber("2");
        items2.setName("小米5");
        items2.setAmount(new BigDecimal("1234"));
        items2.setDetil("很好用哦!");
        items2.setBatch("1002");
        items2.setStock(1000L);
        Items items3=new Items();
        items3.setNumber("3");
        items3.setName("小米8");
        items3.setAmount(new BigDecimal("1234"));
        items3.setDetil("很好用哦!");
        items3.setBatch("1003");
        items3.setStock(1000L);
        itemsList.add(items);
        itemsList.add(items2);
        itemsList.add(items3);
        OutputStream out=null;
         try {
             response.setContentType("application/vnd.ms-excel;charset=utf-8");
             response.setHeader("Content-type", "text/html;charset=UTF-8");
             SimpleDateFormat dfThere = new SimpleDateFormat(dateFormat);
             String excelName ="总部当票回收单"+dfThere.format(new Date());
             response.addHeader("Content-Disposition", "attachment;filename="+new String( excelName.getBytes("utf-8"), "ISO8859-1" )+".xls");
             out = response.getOutputStream();
             //调用导出excel工具类
             ExportExcel.exportExcel(title, headers, itemsList, out, dateFormat);
         }catch (Exception e){
             e.printStackTrace();
         }finally {
             try {
                 if (out!=null) {
                     out.close();
                 }
             } catch (Exception e) {
                 e.printStackTrace();
             }
         }

    }
}

excel 工具方法

import com.example.springboot08.com.pojo.Items;
import jdk.nashorn.internal.ir.annotations.Ignore;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: Administrator
 * @Description:
 * @Date: 2019-08-25 19:13
 * @Modified By: excel导出工具类
 */
public class ExportExcel {

    /**
     * 导出excel数据
     * @param title
     * @param headers
     * @param dataset
     * @param out
     * @param pattern
     */
    public static void exportExcel(String title, String[] headers, List<Items> dataset, OutputStream out, String pattern){
        // 声明一个工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet(title);
        // 设置表格默认列宽度为15个字节
        sheet.setDefaultColumnWidth((short) 25);
        // 生成一个样式
        HSSFCellStyle style = workbook.createCellStyle();
        // 设置这些样式
        style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);	//设置背景颜色
        style.setFillBackgroundColor(HSSFColor.SKY_BLUE.index);
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);  //下边框
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);  //左边框
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);  //右边框
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);  //上边框
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);  //水平居中
        // 生成一个字体
        HSSFFont font = workbook.createFont();
        font.setColor(HSSFColor.VIOLET.index);  //颜色
        font.setFontHeightInPoints((short) 15);  //字号
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); //加粗
        font.setFontName("宋体");
        // 把字体应用到当前的样式
        style.setFont(font);

        // 生成并设置另一个样式
        HSSFCellStyle style2 = workbook.createCellStyle();
        style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
        style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 垂直居中
        // 生成另一个字体
        HSSFFont font2 = workbook.createFont();
        font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
        // 把字体应用到当前的样式
        style2.setFont(font2);

        //声明一个画图的顶级管理器
        HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
        // 定义注释的大小和位置,详见文档
        HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5));

        // 产生表格标题行
        HSSFRow row = sheet.createRow(0);

        for (short i = 0; i < headers.length; i++){
            HSSFCell cell = row.createCell(i);
            cell.setCellStyle(style);
            HSSFRichTextString text1 = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text1);
        }

        // 遍历集合数据,产生数据行
        Iterator<Items> it = dataset.iterator();
        int index = 0;
        while (it.hasNext()){
            index++;
            row = sheet.createRow(index);
            Items t = (Items) it.next();
            // 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
            Field[] fields = t.getClass().getDeclaredFields();
            int k = 0;
            for (short i = 0; i < fields.length; i++){
                /**
                 * 利用自定义注解,忽略不想导出的数据,为了防止忽略属性导致的输出结果错位,
                 * 我们定义一个变量,记录忽略的属性个数,创建第i-k个单元格
                 **/
                Ignore ignore = fields[i].getAnnotation(Ignore.class);
                if (ignore != null) {
                    k += 1;
                    continue;
                }
                HSSFCell cell = row.createCell(i-k);
                cell.setCellStyle(style2);
                Field field = fields[i];
                String fieldName = field.getName();
                String getMethodName = "get"+ fieldName.substring(0, 1).toUpperCase()+ fieldName.substring(1);
                try{
                    Class tCls = t.getClass();
                    Method getMethod = tCls.getMethod(getMethodName,new Class[]{});
                    Object value = getMethod.invoke(t, new Object[]{});
                    // 判断值的类型后进行强制类型转换
                    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(pattern);
                        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;
                        HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 255, (short) 6, index, (short) 6, index);
                        anchor.setAnchorType(2);
                        patriarch.createPicture(anchor, workbook.addPicture(bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG));
                    }else {  // 其它数据类型都当作字符串简单处理
                        if(value==null){
                            textValue = "";
                        }else{
                            textValue = value.toString();
                        }
                    }

                    if (textValue != null){
                        Pattern p = Pattern.compile("^//d+(//.//d+)?$");
                        Matcher matcher = p.matcher(textValue);
                        if (matcher.matches()){
                            // 是数字当作double处理
                            cell.setCellValue(Double.parseDouble(textValue));
                        }else {
                            HSSFRichTextString richString = new HSSFRichTextString(textValue);
                            HSSFFont font3 = workbook.createFont();
                            font3.setColor(HSSFColor.BLACK.index);
                            font3.setFontHeightInPoints((short) 12);
                            richString.applyFont(font3);
                            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                            cell.setCellValue(richString);
                        }
                    }
                }
                catch (SecurityException e){
                    e.printStackTrace();
                }catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException e){
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e){
                    e.printStackTrace();
                } finally {
                    // 清理资源
                }

            }
        }
        try {
            workbook.write(out);
        } catch (IOException e){
            e.printStackTrace();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值