java实现创建excel表并导出到本地之版本二

java创建excel的效果图:
这里写图片描述

代码块

1. 创建Member类,此类用来创建对象,存储在excel表格中的数据

package com.yu.bai.excel;

import java.util.Date;
//创建一个实体对象,用来存储到excel表中
public class Member {
    private Integer code;
    private String name;
    private Integer age;
    private Date birth;

    public Member(Integer code, String name, Integer age, Date birth) {
        super();
        this.code = code;
        this.name = name;
        this.age = age;
        this.birth = birth;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }
}

2. 初始化数据,并运行

package com.yu.bai.excel;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 创建excel,写入数据,然后下载到本地
 *
 * @author baiyu
 *
 */
public class DownloadExcel {

    public static void main(String[] args) {
        Map<String, List<String>> memberMap = getMember();
        String[] strArray = excelTitle();
        ExcelUtil.createExcel(memberMap, strArray);
    }

    /**
     * 初始化数据,将会被存储到excel表格中
     * 
     * @return
     * @throws Exception
     */
    private static Map<String, List<String>> getMember() {
        List<Member> list = new ArrayList<Member>();
        Map<String, List<String>> map = new HashMap<String, List<String>>();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd");

        try {
            Member user1 = new Member(1, "熊大", 24, df.parse("1993-08-28"));
            Member user2 = new Member(2, "熊二", 23, df.parse("1994-08-19"));
            Member user3 = new Member(3, "熊熊", 24, df.parse("1983-11-22"));


            list.add(user1);
            list.add(user2);
            list.add(user3);

            for (int i = 0; i < list.size(); i++) {
                ArrayList<String> members = new ArrayList<String>();
                members.add(list.get(i).getCode() + "");
                members.add(list.get(i).getName());
                members.add(list.get(i).getAge() + "");
                members.add(df.format(list.get(i).getBirth()));
                map.put(list.get(i).getCode() + "", members);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 创建excel title
     */
    public static String[] excelTitle() {
        String[] strArray = { "学号", "姓名", "年龄", "生日" };
        return strArray;
    }
}

3. 编写公共的ExcelUtil工具包,用来创建excel,并写入数据,和导入本地

package com.yu.bai.excel;

import java.io.FileOutputStream;
import java.util.List;
import java.util.Map;

import javax.swing.plaf.synth.Region;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
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.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.util.CellRangeAddress;

/**
 * 参考:https://blog.csdn.net/guo147369/article/details/78354213
 *      https://blog.csdn.net/hantiannan/article/details/5312133
 * @author baiyu
 *
 */
public class ExcelUtil {
    private static final String BIG_TITLE = "big_title";
    private static final String SMALL_TITLE = "small_title";
    private static final String TEXT = "text";

    /**
     * 设置单元格的边框(细)且为白色
     * @param wb
     * @return
     */
    @SuppressWarnings("deprecation")
    public static HSSFCellStyle titleStyle(HSSFWorkbook wb,String description){
        HSSFCellStyle style = wb.createCellStyle();

        if(description.equals(BIG_TITLE)){
            //设置单元格背景色
            style.setFillForegroundColor(IndexedColors.WHITE.getIndex());
            style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        }else if(description.equals(SMALL_TITLE)){
            //设置上下左右四个边框宽度
            style.setBorderBottom(BorderStyle.THIN); //下边框
            style.setBorderLeft(BorderStyle.THIN);//左边框
            style.setBorderTop(BorderStyle.THIN);//上边框
            style.setBorderRight(BorderStyle.THIN);//右边框

            //设置上下左右四个边框颜色
            style.setBottomBorderColor(IndexedColors.WHITE.getIndex());
            style.setLeftBorderColor(IndexedColors.WHITE.getIndex());
            style.setTopBorderColor(IndexedColors.WHITE.getIndex());
            style.setRightBorderColor(IndexedColors.WHITE.getIndex());

            //设置单元格背景色
            style.setFillForegroundColor(IndexedColors.TEAL.getIndex());
            style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        }else if(description.equals(TEXT)){
            //设置上下左右四个边框宽度
            style.setBorderBottom(BorderStyle.THIN); //下边框
            style.setBorderTop(BorderStyle.THIN);//上边框

            //设置上下左右四个边框颜色
            style.setBottomBorderColor(IndexedColors.GREY_25_PERCENT.getIndex());
            style.setTopBorderColor(IndexedColors.GREY_25_PERCENT.getIndex());
            style.setFillPattern(CellStyle.SOLID_FOREGROUND);
        }else{
            return null;
        }

        return style;
    }

    /**
     * 设置字体
     * @return
     */
    public static HSSFFont createFont(HSSFWorkbook wb,String description){
        HSSFFont font = wb.createFont();
        font.setFontName("宋体");
        if(description.equals(BIG_TITLE)){
            font.setFontHeightInPoints((short) 22);//设置字体大小
            font.setColor(IndexedColors.TEAL.getIndex()); //字体颜色
            font.setBoldweight(font.BOLDWEIGHT_BOLD);
        }else if(description.equals(SMALL_TITLE)){
            font.setFontHeightInPoints((short) 16);//设置字体大小
            font.setColor(IndexedColors.WHITE.getIndex()); //字体颜色
            font.setBoldweight(font.BOLDWEIGHT_BOLD);
        }else if(description.equals(TEXT)){
            font.setFontHeightInPoints((short) 12);//设置字体大小
            font.setColor(IndexedColors.BLACK.getIndex()); //字体颜色
        }else{
            return null;
        }
        return font;
    }

    /**
     * 设置单元格的宽度和高度
     * @param sheet
     * @param description
     * @return
     */
    public static HSSFRow createHigth(HSSFSheet sheet,int index){
        HSSFRow row = null;
        if(index == 0){
            row = sheet.createRow((int) 0);
            row.setHeight((short) (40*20)); 
        }else if(index == 1){
            row = sheet.createRow((int) index); 
            row.setHeight((short) (30*20));
        }else{
            row = sheet.createRow((int) index); 
            row.setHeight((short) (20*20));
        }
        return row;
    }

    /**
     * 合并单元格样式
     * @param wb
     * @return
     */
    public static HSSFSheet getMergedRegions(HSSFSheet sheet){
        CellRangeAddress region = new CellRangeAddress(0, 0, (short) 0, (short) 11);
        sheet.addMergedRegion(region);
        return sheet;

    }

    /**
     * @功能:手工构建一个简单格式的Excel
     */
    @SuppressWarnings("deprecation")
    public static void createExcel(Map<String, List<String>> map, String[] strArray) {
        //创建一个webbook,对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();

        //在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("sheet1");
        sheet.setDefaultColumnWidth(20);// 默认列宽

        //合并单元格,设置大标题行
        sheet = getMergedRegions(sheet);
        //设置合并单元格的高度
        HSSFRow row = createHigth(sheet,0);

        //添加大标题并设置样式
        row = createHigth(sheet,0);
        HSSFCell cell = null;
        cell = row.createCell((short) 0);
        cell.setCellValue("白名单列表");
        HSSFCellStyle style = titleStyle(wb,"big_title");
        style.setFont(createFont(wb,"big_title"));
        cell.setCellStyle(style);

        //添加小标题并设置样式
        row = createHigth(sheet,1);
        for (int i = 0; i < strArray.length; i++) {
            cell = row.createCell((short) i);
            cell.setCellValue(strArray[i]);
            style = titleStyle(wb,"small_title");
            style.setFont(createFont(wb,"small_title"));
            //设置排序
            //sheet.setAutoFilter(CellRangeAddress.valueOf("A2:B2"));
            //sheet.setAutoFilter(CellRangeAddress.valueOf("C2:D2"));
            cell.setCellStyle(style);
        }

        //设置未填满的单元格的颜色
        for (int i = strArray.length; i < 26; i++) {
            cell = row.createCell((short) i);
            style = titleStyle(wb,"small_title");
            cell.setCellStyle(style);
        }

        //添加text文本,list中字符串的顺序必须和数组strArray中的顺序一致
        int i = 1;
        for (String str : map.keySet()) {
            row = createHigth(sheet,i+1);
            List<String> list = map.get(str);
            style = titleStyle(wb,"text");
            style.setFont(createFont(wb,"text"));

            if(i%2 == 0){
                style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            }else{
                style.setFillForegroundColor(IndexedColors.LEMON_CHIFFON.getIndex());
            }

            // 第四步,创建单元格,并设置值
            for (int j = 0; j < strArray.length; j++) { 
                cell = row.createCell((short) j);
                cell.setCellValue(list.get(j));
                cell.setCellStyle(style);
            }

            //设置未填满的单元格的颜色
            for (int z = strArray.length; z < 26; z++) {
                cell = row.createCell((short) z);
                cell.setCellStyle(style);
            }


            // 第六步,将文件存到指定位置
            try {
                FileOutputStream fout = new FileOutputStream("E:/template/Members.xls");
                wb.write(fout);
                fout.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            i++;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/expect521/article/details/81191321