Java export data Excel file xls

1. View export examples

Insert image description here

2. Main export code


    /**
     * 
     * @param start 开始时间
     * @param end  结束时间
     * @param response
     */
    public void ex2(String start, String end, HttpServletResponse response) {
    
    

        String[] title = {
    
    "时间", "内容1", "内容2", "内容3"};
        String fileName = "文件名称.xls";
        String sheetName = "Sheet1";


        ArrayList<String> strings = null;
        //判断空的,可以替换你自己的工具类
        if (ToolUtil.isNotEmpty(start) && ToolUtil.isNotEmpty(end)) {
    
    
            //如果传时间的话返回时间集合
            strings = DateUtils.getDays(start, end);
        } else {
    
    
            //没有传时间查询最近七天
            strings = DateUtils.lastDay(7);
            Collections.reverse(strings);
        }

        String[][] content = new String[strings.size()][];
        for (int x = 0; x < strings.size(); x++) {
    
    
            content[x] = new String[title.length];
            content[x][0] = strings.get(x);
            for (int i = 1; i <= 7; i++) {
    
    
                content[x][1] = "内容1";
                content[x][2] =  "内容2";
                content[x][3] =  "内容3";
            }
        }


        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);

        //响应到客户端
        try {
    
    
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }


    }

3. This is the return time collection method

    public static ArrayList<String> getDays(String startTime, String endTime) {
    
    

        // 返回的日期集合
        ArrayList<String> days = new ArrayList<String>();

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
    
    
            Date start = dateFormat.parse(startTime);
            Date end = dateFormat.parse(endTime);

            Calendar tempStart = Calendar.getInstance();
            tempStart.setTime(start);

            Calendar tempEnd = Calendar.getInstance();
            tempEnd.setTime(end);
            tempEnd.add(Calendar.DATE, +1);// 日期加1(包含结束)
            while (tempStart.before(tempEnd)) {
    
    
                days.add(dateFormat.format(tempStart.getTime()));
                tempStart.add(Calendar.DAY_OF_YEAR, 1);
            }

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

        return days;
    }

4. Time method for the last seven days

    public static ArrayList<String> lastDay(int intervals) {
    
    
        ArrayList<String> pastDaysList = new ArrayList<>();
        for (int i = 0; i < intervals; i++) {
    
    
            pastDaysList.add(getPastDate(i));
        }
        return pastDaysList;
    }

    public static String getPastDate(int past) {
    
    
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String result = format.format(today);
        return result;
    }
5. Export Excel tool class
package cn.stylefeng.guns.sys.core.util;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;

/**
 * @description:
 * @author: 于双瑜
 * @create: 2021-07-29 16:42
 **/
public class ExcelUtil {
    
    

    /**
     * 导出Excel
     * @param sheetName sheet名称
     * @param title 标题
     * @param values 内容
     * @param wb HSSFWorkbook对象
     * @return
     */
    public static HSSFWorkbook getHSSFWorkbook(String sheetName, String []title, String [][]values, HSSFWorkbook wb){
    
    

        // 第一步,创建一个HSSFWorkbook,对应一个Excel文件
        if(wb == null){
    
    
            wb = new HSSFWorkbook();
        }

        // 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet(sheetName);

        // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
        HSSFRow row = sheet.createRow(0);

        // 第四步,创建单元格,并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式

        //声明列对象
        HSSFCell cell = null;

        //创建标题
        for(int i=0;i<title.length;i++){
    
    
            cell = row.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(style);
        }

        //创建内容
        for(int i=0;i<values.length;i++){
    
    
            row = sheet.createRow(i + 1);
            for(int j=0;j<values[i].length;j++){
    
    
                //将内容按顺序赋给对应的列对象
                row.createCell(j).setCellValue(values[i][j]);
            }
        }
        return wb;
    }

}

6. The last step is to send the response stream method
    public void setResponseHeader(HttpServletResponse response, String fileName) {
    
    
        try {
    
    
            try {
    
    
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
    
    
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
    
    
            ex.printStackTrace();
        }
    }
7. Import dependencies
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>4.0.1</version>
        </dependency>

Guess you like

Origin blog.csdn.net/weixin_45500785/article/details/129703542