重要:JAVA 導出EXCEL(POI方法)

package goodsmng;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
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 javax.swing.JOptionPane;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFComment;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
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;
import student.Book;
import student.ExportExcel;
import student.Student;

public class goodExcel<T>  {

 //메인입니다. ******************************************************************************************
 public static void main(String[] args)  {
     ExportExcel<Student> ex = new ExportExcel<Student>(); 
        String[] headers =  { "넘버", "이름", "나이", "성별", "출생년월" }; 
        List<Student> dataset = new ArrayList<Student>(); 
        dataset.add(new Student(10000001, "김아무개", 20, true, new Date())); 
        dataset.add(new Student(20000002, "홍길동", 24, false, new Date())); 
        dataset.add(new Student(30000003, "김삿갓", 22, true, new Date()));
       
        ExportExcel<Book> ex2 = new ExportExcel<Book>(); 
        String[] headers2 =  { "넘버", "도서명", "도서작가", "도서가격", "도서ISBN", "도서출판", "이미지" }; 
            List<Book> dataset2 = new ArrayList<Book>();
            try 
            {
             BufferedInputStream bis = new BufferedInputStream( new FileInputStream("Z://book.jpg")); 
                byte[] buf = new byte[bis.available()]; 
                while ((bis.read(buf)) != -1) 
                { 
                    // 
                }
                dataset2.add(new Book(1, "jsp", "leno", 300.33f, "1234567",     "출판서1", buf)); 
                dataset2.add(new Book(2, "java", "brucl", 300.33f, "1234567",   "출판서2", buf)); 
                dataset2.add(new Book(3, "DOM", "lenotang", 300.33f, "1234567", "출판서1", buf)); 
                dataset2.add(new Book(4, "c++", "leno", 400.33f, "1234567",     "출판서1", buf)); 
                dataset2.add(new Book(5, "c#", "leno", 300.33f, "1234567",      "출판서3", buf)); 
                OutputStream out = new FileOutputStream("Z://test_1.xls"); 
                OutputStream out2 = new FileOutputStream("Z://test_2.xls"); 
               
                ex.exportExcel(headers, dataset, out); 
                ex2.exportExcel(headers2, dataset2, out2); 
               
                out.close(); 
               
                JOptionPane.showMessageDialog(null, "성공!");
                System.out.println("excel성공!"); 
            } 
            catch (FileNotFoundException e) 
            { 
                e.printStackTrace(); 
            } 
            catch (IOException e) 
            { 
                e.printStackTrace(); 
            } 
        } 
 
 //엑셀 파일 만들기 ****************************************************************************************
 public void exportExcel(String title, String[] headers, Collection<T> dataset, OutputStream out, String pattern) {
  HSSFWorkbook workbook = new HSSFWorkbook();//workbook만들기
  HSSFSheet sheet = workbook.createSheet(title);//시트 만들기
  sheet.setDefaultColumnWidth((short) 15);//셀 넓이 지정하기
  HSSFCellStyle style = workbook.createCellStyle();//셀 스타일생성
  //스타일 지정
  style.setFillForegroundColor(HSSFColor.SKY_BLUE.index); 
  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.VIOLET.index); 
  font.setFontHeightInPoints((short) 12); 
  font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); 
        //생성된 폰트 사용
  style.setFont(font);
  //다른 스타일 지정
  HSSFCellStyle style2 = workbook.createCellStyle();
  style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index); 
  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.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL); 
  style2.setFont(font2);
  //그림판 관리기를 선언한다
  HSSFPatriarch patriarch  = sheet.createDrawingPatriarch();
  HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0,  0, 0, 0, (short) 4, 2, (short) 6, 5));//주석 위치 크기
  comment.setString(new HSSFRichTextString("셀 주석 달기")); 
  comment.setAuthor("저자 달기 "); 
  
  //셀 타이틀 생성하기
  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<T> it = dataset.iterator();
  int index = 0; 
   while (it.hasNext()){
    index++;
    row = sheet.createRow(index);
    T t = (T)it.next();
    Field[] fields = t.getClass().getDeclaredFields(); 
    for (short i = 0; i < fields.length; i++) 
             { 
                 HSSFCell cell = row.createCell(i); 
                 cell.setCellStyle(style2); 
                 Field field = fields[i]; 
                 String fieldName = field.getName(); 
                 String getMethodName = "get" 
                         + fieldName.substring(0, 1).toUpperCase() 
                         + fieldName.substring(1); 
                 try 
                 { 
                     Class tCls = t.getClass(); 
                     Method getMethod = tCls.getMethod(getMethodName, 
                             new Class[] 
                             {}); 
                     Object value = getMethod.invoke(t, new Object[] 
                     {}); 
                      
                     String textValue = null; 
                   
                     if (value instanceof Boolean) 
                     { 
                         boolean bValue = (Boolean) value; 
                         textValue = "남"; 
                         if (!bValue) 
                         { 
                             textValue = "녀"; 
                         } 
                     } 
                     else if (value instanceof Date) 
                     { 
                         Date date = (Date) value; 
                         SimpleDateFormat sdf = new SimpleDateFormat(pattern); 
                         textValue = sdf.format(date); 
                     } 
                     else if (value instanceof byte[]) 
                     { 
                       
                         row.setHeightInPoints(60); 
                       
                         sheet.setColumnWidth(i, (short) (35.7 * 80)); 
                         // sheet.autoSizeColumn(i); 
                         byte[] bsValue = (byte[]) value; 
                         HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 
                                 1023, 255, (short) 6, index, (short) 6, index); 
                         anchor.setAnchorType(2); 
                         patriarch.createPicture(anchor, workbook.addPicture( 
                                 bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG)); 
                     } 
                     else 
                     { 
                       
                         textValue = value.toString(); 
                     } 
                
                     if (textValue != null) 
                     { 
                         Pattern p = Pattern.compile("^//d+(//.//d+)?$"); 
                         Matcher matcher = p.matcher(textValue); 
                         if (matcher.matches()) 
                         { 
                           
                             cell.setCellValue(Double.parseDouble(textValue)); 
                         } 
                         else 
                         { 
                             HSSFRichTextString richString = new HSSFRichTextString( 
                                     textValue); 
                             HSSFFont font3 = workbook.createFont(); 
                             font3.setColor(HSSFColor.BLUE.index); 
                             richString.applyFont(font3); 
                             cell.setCellValue(richString); 
                         } 
                     } 
                 } 
                 catch (SecurityException e) 
                 { 
                     e.printStackTrace(); 
                 } 
                 catch (NoSuchMethodException e) 
                 { 
                     e.printStackTrace(); 
                 } 
                 catch (IllegalArgumentException e) 
                 { 
                     e.printStackTrace(); 
                 } 
                 catch (IllegalAccessException e) 
                 { 
                     e.printStackTrace(); 
                 } 
                 catch (InvocationTargetException e) 
                 { 
                     e.printStackTrace(); 
                 } 
                 finally 
                 { 
                  
                 } 
             }
   }
   try 
         { 
             workbook.write(out); 
         } 
         catch (IOException e) 
         { 
             e.printStackTrace(); 
         }
 }

}



文獻 http://blog.csdn.net/evangel_z/article/details/7332535

超級詳細    http://rensanning.iteye.com/blog/1538591




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章