1. 程式人生 > >通用導出excel(可控制內容)

通用導出excel(可控制內容)

timestamp data 設置 sheet 導出excel align ota 2.x getdate

實體類

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(可控制內容)