PoI:apached 的报表导出

Pomxml

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

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


    </dependencies>

 application.properties

spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost:3306/cn?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

PoIExcelUtils  

package com.hc.controller;

import com.hc.model.User;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;

import java.io.*;
//import java.lang.reflect.Method;
//import java.text.SimpleDateFormat;
//import java.util.Date;
import java.util.ArrayList;
import java.util.List;
//import java.util.Map;
//import java.util.UUID;

public final class PoIExcelUtils {


//    private static Logger log = LoggerFactory.getLogger(Obj2ExcelUtils.class);
//    private static final String LOGPRE = "Obj2ExcelUtils:";

    /***
     * 构造方法
     */
    private PoIExcelUtils() {

    }

    /***
     * 工作簿
     */
    private static HSSFWorkbook workbook;

    /***
     * sheet
     */
    private static HSSFSheet sheet;
    /***
     * 标题行开始位置
     */
    private static final int TITLE_START_POSITION = 1;

    /***
     * 时间行开始位置
     */
//    private static final int DATEHEAD_START_POSITION = 1;

    /***
     * 表头行开始位置
     */
    private static final int HEAD_START_POSITION = 0;//从0行开始

    /***
     * 文本行开始位置
     */
    private static final int CONTENT_START_POSITION = 1;//报表从第一行开始


//    /**
//     * @param //dataList  对象集合
//     * @param //titleMap  表头信息(对象属性名称->要显示的标题值)[按顺序添加]
//     * @param //sheetName sheet名称和表头值
//     */

    /**
     * @param dataList
     */

    public static void excelExport(List<User> dataList) {
//        初始化
        List<String> titleMap = new ArrayList<>();
        titleMap.add("编号");
        titleMap.add("名称");
        titleMap.add("日期");
        titleMap.add("说明");
        String sheetName = "用户信息";
        // 初始化workbook
        initHSSFWorkbook(sheetName);
        // 标题行
        createTitleRow(titleMap, sheetName);//userSize 对象几个属性
        // 时间行
//        createDateHeadRow(titleMap);
        // 表头行
        createHeadRow(titleMap);
        // 文本行
        createContentRow(dataList, titleMap.size());
        //设置自动伸缩
//        autoSizeColumn(titleMap.size());
        // 写入处理结果
        try {
            //生成UUID文件名称
//            UUID uuid = UUID.randomUUID();
            String fileDisplay = System.currentTimeMillis() + ".xls";
            //如果web项目,1、设置下载框的弹出(设置response相关参数);
            // 2、通过httpServletResponse.getOutputStream()获取
            OutputStream out = new FileOutputStream("D:\\" + fileDisplay);
            workbook.write(out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * web项目下载
     *
     //     * @param dataList  对象集合
     //     * @param titleMap  表头信息(对象属性名称->要显示的标题值)[按顺序添加]
     //     * @param sheetName sheet名称和表头值
     */
//    public static InputStream excelExportWeb(List<?> dataList, Map<String, String> titleMap,
// String sheetName) {
//        // 初始化workbook
//        initHSSFWorkbook(sheetName);
//        // 标题行
//        createTitleRow(titleMap, sheetName);
//        // 时间行
////        createDateHeadRow(titleMap);
//        // 表头行
//        createHeadRow(titleMap);
//        // 文本行
//        createContentRow(dataList, titleMap);
//        //设置自动伸缩
////        autoSizeColumn(titleMap.size());
//        // 写入处理结果
//        ByteArrayOutputStream os = null;
//        try {
//            if (workbook == null) {
////                log.error(LOGPRE + "HSSFWorkbook为空");
//                return null;
//            }
//            // 将文件存到流中
//            os = new ByteArrayOutputStream();
//            workbook.write(os);
//            byte[] fileContent = os.toByteArray();
//            return new ByteArrayInputStream(fileContent);
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            if (os != null) {
//                try {
//                    os.close();
//                } catch (IOException e) {
////                    log.error(LOGPRE + e.getMessage(), e);
//                }
//            }
//            if (workbook != null) {
//                try {
////	                    workbook.close();
//                } catch (Exception e) {
////                    log.error(LOGPRE + e.getMessage(), e);
//                }
//            }
//            // log.info("导出结束时间:"+new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").
// format(new Date(System.currentTimeMillis())));
//        }
//        return null;
//    }

    /***
     *
     //     * @param sheetName
     *        sheetName
     */
    private static void initHSSFWorkbook(String sheetName) {
        workbook = new HSSFWorkbook();
        sheet = workbook.createSheet(sheetName);
    }

    /**
     * 生成标题(第零行创建)
     * <p>
     * //     * @param titleMap  对象属性名称->表头显示名称
     * //     * @param sheetName sheet名称
     */
//    firstCol---3  userSize-1
    private static void createTitleRow(List<String> titleMap, String sheetName) {//5 对象属性
        CellRangeAddress titleRange = new CellRangeAddress(1, 1,
                titleMap.size() - 1, titleMap.size() - 1);
        sheet.addMergedRegion(titleRange);
        HSSFRow titleRow = sheet.createRow(TITLE_START_POSITION);
        HSSFCell titleCell = titleRow.createCell(0);
        titleCell.setCellValue(sheetName);
    }

    /**
     * 创建时间行(第一行创建)
     *
     //     * @param titleMap 对象属性名称->表头显示名称
     */
    //    firstCol---3
  /*  private static void createDateHeadRow(Map<String, String> titleMap) {
        CellRangeAddress dateRange = new CellRangeAddress(1, 1, 1, titleMap.size() - 1);
        sheet.addMergedRegion(dateRange);
        HSSFRow dateRow = sheet.createRow(DATEHEAD_START_POSITION);
        HSSFCell dateCell = dateRow.createCell(0);
        dateCell.setCellValue(new SimpleDateFormat("yyyy年MM月dd日").format(new Date()));
    }*/

    /**
     * 创建表头行(第二行创建)
     * <p>
     * //     * @param titleMap 对象属性名称->表头显示名称
     */
    private static void createHeadRow(List<String> titleMap) {
        // 第2行创建
        HSSFRow headRow = sheet.createRow(HEAD_START_POSITION);

        //不加标题和时间行,第0行创建
//        HSSFRow headRow = sheet.createRow(0);
        int i = 0;
        for (String entry : titleMap) {
            HSSFCell headCell = headRow.createCell(i);
            headCell.setCellValue(entry);
            i++;
        }
    }

    /**
     * //     * @param dataList 对象数据集合
     *
     * @param //tit//leMap 表头信息
     */
    private static void createContentRow(List<User> dataList, int titleSize) {
        try {
            int i = 0;
            for (User obj : dataList) {
                HSSFRow textRow = sheet.createRow(CONTENT_START_POSITION + i);

                //自定义列段
                for (int i1 = 0; i1 < titleSize; i1++) {
                    HSSFCell textcell = textRow.createCell(i1);
                    if (i1 == 0) {
                        textcell.setCellValue(obj.getUserId());
                    } else if (i1 == 1) {
                        textcell.setCellValue(obj.getUserName());
                    } else if (i1 == 2) {
                        textcell.setCellValue(obj.getUserDay());
                    } else if (i1 == 3) {
                        textcell.setCellValue(obj.getUserBase());
                    }
                }

                // 不加标题和时间行,第1行创建
                //  HSSFRow textRow = sheet.createRow(1 + i);
//                int j = 0;
//                for (String entry : titleMap.keySet()) {
//                    String method = "get" + entry.substring(0, 1).
// toUpperCase() + entry.substring(1);
//                    Method m = obj.getClass().getMethod(method, null);
//                    String value = m.invoke(obj, null).toString();
//                    HSSFCell textcell = textRow.createCell(j);
//                    textcell.setCellValue(value);
//                    j++;
//                }
                i++;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 自动伸缩列(如非必要,请勿打开此方法,耗内存)
     *
     //     * @param size 列数
     */
//    private static void autoSizeColumn(Integer size) {
//        for (int j = 0; j < size; j++) {
//            sheet.autoSizeColumn(j);
//        }
//    }

}

User 

package com.hc.model;

public class User {
    private int userId;
    private String userName;
    private String userDay;
    private String userBase;

    public User() {
    }

    public User(String userName, String userDay, String userBase) {
        this.userName = userName;
        this.userDay = userDay;
        this.userBase = userBase;
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserDay() {
        return userDay;
    }

    public void setUserDay(String userDay) {
        this.userDay = userDay;
    }

    public String getUserBase() {
        return userBase;
    }

    public void setUserBase(String userBase) {
        this.userBase = userBase;
    }
}

 UserMapper 

package com.hc.mapper;

import com.hc.model.User;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public interface UserMapper {
    @Select("select * from User")
    List<User> allUser();
}

UserService  

package com.hc.service;

import com.hc.model.User;

import java.util.List;

public interface UserService {
    List<User> allUser();
}

 UserServiceImpl 

package com.hc.service.impl;

import com.hc.mapper.UserMapper;
import com.hc.model.User;
import com.hc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> allUser() {
        return userMapper.allUser();
    }
}

UserController  

package com.hc.controller;

import com.hc.model.User;
import com.hc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("data")
    @ResponseBody
    public String PoIData() {
        List<User> staffs = userService.allUser();
        PoIExcelUtils.excelExport(staffs);

        return "yes";
    }

}

 DatapoiApplication 

package com.hc;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.hc.mapper")
public class DatapoiApplication {

    public static void main(String[] args) {
        SpringApplication.run(DatapoiApplication.class, args);
    }
}

Pol数据导出 

猜你喜欢

转载自blog.csdn.net/qq_43532342/article/details/84501190
今日推荐