码迷,mamicode.com
首页 > 其他好文 > 详细

通用导出excel(可控制内容)

时间:2017-09-17 23:38:01      阅读:462      评论:0      收藏:0      [点我收藏+]

标签:sim   正则表达   next   npoi   regex   集合   工作薄   style   oid   

实体类

package util;

import java.sql.Timestamp;

public class Book {
    private int bookId;
    private String name;
    private String author;
    private float price;
    private String isbn;
    private String pubName;
    private Timestamp date;
    
    public Book() {
    }

    public Book(int bookId, String name, String author, float price,
            String isbn, String pubName ,Timestamp date) {
        this.bookId = bookId;
        this.name = name;
        this.author = author;
        this.price = price;
        this.isbn = isbn;
        this.pubName = pubName;
        this.date=date;
    }

    
    public Timestamp getDate() {
        return date;
    }

    public void setDate(Timestamp date) {
        this.date = date;
    }

    public int getBookId() {
        return bookId;
    }

    public void setBookId(int bookId) {
        this.bookId = bookId;
    }

    public String getName() {
        return name;
    }

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

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public float getPrice() {
        return price;
    }

    public void setPrice(float price) {
        this.price = price;
    }

    public String getIsbn() {
        return isbn;
    }

    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }

    public String getPubName() {
        return pubName;
    }

    public void setPubName(String pubName) {
        this.pubName = pubName;
    }

    
}

导出通用类

package util;

import java.io.OutputStream;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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.HSSFRichTextString;
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;

/**
 * 
 * @author 通用导出 Excel 可以控制内容
 * @name liuyi
 * @version 1.0
 * @时间 2017-9-16 22:40
 */
public class exportExcel{
    /**
     * 
     * @param title 标题
     * @param headers 表头
     * @param dataset 数据集 -集合类型
     * @param out     输出流
     * @param pattern 时间格式
     * @param showAttribute 对象需要显示的属性
     */
    @SuppressWarnings({ "deprecation", "rawtypes" })
    public void exportExcel(String title, String[] headers,
            Collection dataset, OutputStream out, String pattern,String[]showAttribute) throws  Exception {
        // 声明一个工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet(title);
        // 设置表格默认列宽度为15个字节
        sheet.setDefaultColumnWidth((short) 15);
        // 生成一个样式
        HSSFCellStyle style = workbook.createCellStyle();
        // 设置这些样式
        /*style.setFillForegroundColor((short) 13); 表头背景颜色*/ 
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        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.RED.index);
        font.setFontHeightInPoints((short) 12);
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 把字体应用到当前的样式
        style.setFont(font);
        // 生成并设置另一个样式
        HSSFCellStyle style2 = workbook.createCellStyle();
        /*style2.setFillForegroundColor((short) 13); 内容背景颜色*/
        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.setColor(HSSFColor.BLACK.index);
        font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
        // 把字体应用到当前的样式
        style2.setFont(font2);
        //格式话时间类型
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        // 产生表格标题行
        HSSFRow row = sheet.createRow(0);
        for (short i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellStyle(style);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }
        // 遍历集合数据,产生数据行
        Iterator it = dataset.iterator();
        int index = 0;
        while (it.hasNext()) {
            //获得 单个对象
            Object t =it.next();
            index++;
            row = sheet.createRow(index);
            for (short i = 0; i < showAttribute.length; i++) {
                HSSFCell cell = row.createCell(i);
                cell.setCellStyle(style2);
                Object value=getValue(t,showAttribute[i]);
                // 判断值的类型后进行强制类型转换
                String textValue = null;
                if (value instanceof Boolean) {
                    boolean bValue = (Boolean) value;
                    textValue = "男";
                    if (!bValue) {
                        textValue = "女";
                    }
                } else if (value instanceof Date) {
                    Date date = (Date) value;
                    
                    textValue = sdf.format(date);
                } else if(value instanceof Timestamp){
                    Timestamp timestamp= (Timestamp) value;
                    textValue=sdf.format(timestamp);
                }
                else {
                    // 其它数据类型都当作字符串简单处理
                    textValue = value.toString();
                }
                // 如果不是图片数据,就利用正则表达式判断textValue是否全部由数字组成
                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);
                        System.out.println(richString);
                        cell.setCellValue(richString);
                    }
                }
            }
            workbook.write(out);
        }
    }
    
    /**
     * 
     * @param title 标题
     * @param headers 表头
     * @param dataset 数据集---数组类型
     * @param out    输出对象
     * @param pattern  时间格式
     * @param showIndex 要实现内容的下标
     */
    @SuppressWarnings("deprecation")
    public void exportExcel(String title, String[] headers,
            List<Object[]> dataset, OutputStream out, String pattern,Integer[]showIndex) throws  Exception {
        // 声明一个工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet(title);
        // 设置表格默认列宽度为15个字节
        sheet.setDefaultColumnWidth((short) 15);
        // 生成一个样式
        HSSFCellStyle style = workbook.createCellStyle();
        // 设置这些样式
        /*style.setFillForegroundColor((short) 13); 表头背景颜色*/ 
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        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.RED.index);
        font.setFontHeightInPoints((short) 12);
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 把字体应用到当前的样式
        style.setFont(font);
        // 生成并设置另一个样式
        HSSFCellStyle style2 = workbook.createCellStyle();
        /*style2.setFillForegroundColor((short) 13); 内容背景颜色*/
        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.setColor(HSSFColor.BLACK.index);
        font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
        // 把字体应用到当前的样式
        style2.setFont(font2);
        //格式话时间类型
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        // 产生表格标题行
        HSSFRow row = sheet.createRow(0);
        for (short i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellStyle(style);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }
        // 遍历集合数据,产生数据行
        int index = 0;
        for (Object[] data : dataset) {
            //获得 单个对象
            index++;
            row = sheet.createRow(index);
            for (short i = 0; i < showIndex.length; i++) {
                HSSFCell cell = row.createCell(i);
                cell.setCellStyle(style2);
                System.out.println("i="+i+"\t value="+data[showIndex[i]]);
                Object value=data[showIndex[i]];
                // 判断值的类型后进行强制类型转换
                String textValue = null;
                if (value instanceof Boolean) {
                    boolean bValue = (Boolean) value;
                    textValue = "男";
                    if (!bValue) {
                        textValue = "女";
                    }
                } else if (value instanceof Date) {
                    Date date = (Date) value;
                    
                    textValue = sdf.format(date);
                } else if(value instanceof Timestamp){
                    Timestamp timestamp= (Timestamp) value;
                    textValue=sdf.format(timestamp);
                }
                else {
                    // 其它数据类型都当作字符串简单处理
                    textValue = value.toString();
                }
                // 如果不是图片数据,就利用正则表达式判断textValue是否全部由数字组成
                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);
                        cell.setCellValue(richString);
                    }
                }
            }
            workbook.write(out);
        }
    }
    
    
    
    
    /**
     * 
     * @param obj 取值的对象
     * @param nameValue  取值的属性
     * @return 返回需要的属性值
     */
    public  Object getValue(Object obj,String nameValue) throws Exception, SecurityException{
        Object objValue=null;
        Method m = obj.getClass().getMethod(nameValue);
        objValue=m.invoke(obj);
        return objValue;
    }
}

测试类

public class Test {
    public static void main(String[] args) throws Exception {
        String[] headers2 = { "图书编号", "图书名称", "图书作者", "图书价格", "图书ISBN",
        "图书出版社"};
        exportExcel ex2 = new exportExcel();
        OutputStream out1 = new FileOutputStream("D:\\book1.xls");
        OutputStream out2 = new FileOutputStream("D:\\book2.xls");
        //对象
        List<Book> dataset2 = new ArrayList<Book>();
        dataset2.add(new Book(1, "jsp", "leno", 300.33f, "1234567",
                "清华出版社",Timestamp.valueOf("2017-5-5 00:00:00")));
        dataset2.add(new Book(2, "java编程思想", "brucl", 300.33f, "1234567",
                "阳光出版社",Timestamp.valueOf("2017-5-5 00:00:00")));
        dataset2.add(new Book(3, "DOM艺术", "lenotang", 300.33f, "1234567",
                "清华出版社",Timestamp.valueOf("2017-5-5 00:00:00")));
        dataset2.add(new Book(4, "c++经典", "leno", 400.33f, "1234567",
                "清华出版社",Timestamp.valueOf("2017-5-5 00:00:00")));
        dataset2.add(new Book(5, "c#入门", "leno", 300.33f, "1234567",
                "汤春秀出版社",Timestamp.valueOf("2017-5-5 00:00:00")));
        //指定  要显示的属性
        String [] showAttribute= {"getName","getPrice","getDate"};
        
        //数组
        List<Object[]>dataset1=new ArrayList<Object[]>();
        dataset1.add(new Object[]{1,"小白",Timestamp.valueOf("2017-5-5 00:00:00")});
        //指定要显示的下标
        Integer[] showIndex={1,2};
        
        
        ex2.exportExcel("测试", headers2, dataset2, out2,"yyyy-MM-dd HH:mm:ss", showAttribute);
        ex2.exportExcel("测试",headers2, dataset1, out1,"yyyy-MM-dd HH:mm:ss",showIndex);

    }
}

 

通用导出excel(可控制内容)

标签:sim   正则表达   next   npoi   regex   集合   工作薄   style   oid   

原文地址:http://www.cnblogs.com/LY123/p/7538403.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!