將數據導出到Excel(java操作Excel)

1.封裝要到處的數據類,這裏使用Student類舉例:

[java] view plaincopy
package com.jeelon.exportExcle;  
  
public class Student {  
    private int id;  
    private String name ;  
    private int age;  
    private String address;  
    private String tel;  
    private char sex;  
    public int getId() {  
        return id;  
    }  
    public void setId(int id) {  
        this.id = id;  
    }  
    public String getName() {  
        return name;  
    }  
    public void setName(String name) {  
        this.name = name;  
    }  
    public int getAge() {  
        return age;  
    }  
    public void setAge(int age) {  
        this.age = age;  
    }  
    public String getAddress() {  
        return address;  
    }  
    public void setAddress(String address) {  
        this.address = address;  
    }  
    public String getTel() {  
        return tel;  
    }  
    public void setTel(String tel) {  
        this.tel = tel;  
    }  
    public char getSex() {  
        return sex;  
    }  
    public void setSex(char sex) {  
        this.sex = sex;  
    }  
    @Override  
    public String toString() {  
        return "Student [id=" + id + ", name=" + name + ", age=" + age  
                + ", address=" + address + ", tel=" + tel + ", sex=" + sex  
                + "]";  
    }  
    public Student(int id, String name, int age, String address, String tel,  
            char sex) {  
        super();  
        this.id = id;  
        this.name = name;  
        this.age = age;  
        this.address = address;  
        this.tel = tel;  
        this.sex = sex;  
    }  
    public Student() {  
        super();  
    }  
      
      
}  

 

2.ExportExcel工具類

[java] view plaincopy
package com.jeelon.exportExcle;  
  
import java.io.File;  
import java.io.FileNotFoundException;  
import java.io.FileOutputStream;  
import java.io.IOException;  
  
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;  
import org.apache.poi.hssf.util.Region;  
  
/** 
 * EXCEL報表工具類. 
 *  
 * @author Jeelon 
 */  
public class ExportExcel {  
  
    private HSSFWorkbook wb = null;  
    private HSSFSheet sheet = null;  
  
    /** 
     * @param wb 
     * @param sheet  
     */  
    public ExportExcel(HSSFWorkbook wb, HSSFSheet sheet) {  
        // super();  
        this.wb = wb;  
        this.sheet = sheet;  
    }  
  
    /** 
     * 創建通用EXCEL頭部 
     *  
     * @param headString 
     *            頭部顯示的字符 
     * @param colSum 
     *            該報表的列數 
     */  
    @SuppressWarnings({ "deprecation", "unused" })  
    public void createNormalHead(String headString, int colSum) {  
        HSSFRow row = sheet.createRow(0);  
        // 設置第一行  
        HSSFCell cell = row.createCell(0);  
        // row.setHeight((short) 1000);  
  
        // 定義單元格爲字符串類型  
        cell.setCellType(HSSFCell.ENCODING_UTF_16);// 中文處理  
        cell.setCellValue(new HSSFRichTextString(headString));  
  
        // 指定合併區域  
        /** 
         * public Region(int rowFrom, short colFrom, int rowTo, short colTo) 
         */  
        sheet.addMergedRegion(new Region(0, (short) 0, 0, (short) colSum));  
  
        // 定義單元格格式,添加單元格表樣式,並添加到工作簿  
        HSSFCellStyle cellStyle = wb.createCellStyle();  
        // 設置單元格水平對齊類型  
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 指定單元格居中對齊  
        cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 指定單元格垂直居中對齊  
        cellStyle.setWrapText(true);// 指定單元格自動換行  
  
        // 設置單元格字體  
        HSSFFont font = wb.createFont();  
        // font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
        // font.setFontName("宋體");  
        // font.setFontHeight((short) 600);  
        // cellStyle.setFont(font);  
        cell.setCellStyle(cellStyle);  
    }  
  
    /** 
     * 創建通用報表第二行 
     *  
     * @param params 
     *            統計條件數組 
     * @param colSum 
     *            需要合併到的列索引 
     */  
    @SuppressWarnings("deprecation")  
    public void createNormalTwoRow(String[] params, int colSum) {  
        // 創建第二行  
        HSSFRow row1 = sheet.createRow(1);  
  
        row1.setHeight((short) 400);  
  
        HSSFCell cell2 = row1.createCell(0);  
  
        cell2.setCellType(HSSFCell.ENCODING_UTF_16);  
        cell2.setCellValue(new HSSFRichTextString("時間:" + params[0] + "至"  
                + params[1]));  
  
        // 指定合併區域  
        /** 
         * public Region(int rowFrom, short colFrom, int rowTo, short colTo) 
         */  
        sheet.addMergedRegion(new Region(1, (short) 0, 1, (short) colSum));  
  
        HSSFCellStyle cellStyle = wb.createCellStyle();  
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 指定單元格居中對齊  
        cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 指定單元格垂直居中對齊  
        cellStyle.setWrapText(true);// 指定單元格自動換行  
  
        // 設置單元格字體  
        HSSFFont font = wb.createFont();  
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
        font.setFontName("宋體");  
        font.setFontHeight((short) 250);  
        cellStyle.setFont(font);  
  
        cell2.setCellStyle(cellStyle);  
    }  
  
    /** 
     * 設置報表標題 
     *  
     * @param columHeader 
     *            標題字符串數組 
     */  
    public void createColumHeader(String[] columHeader) {  
  
        // 設置列頭 在第三行  
        HSSFRow row2 = sheet.createRow(2);  
  
        // 指定行高  
        row2.setHeight((short) 600);  
  
        HSSFCellStyle cellStyle = wb.createCellStyle();  
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 指定單元格居中對齊  
        cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 指定單元格垂直居中對齊  
        cellStyle.setWrapText(true);// 指定單元格自動換行  
  
        // 單元格字體  
        HSSFFont font = wb.createFont();  
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
        font.setFontName("宋體");  
        font.setFontHeight((short) 250);  
        cellStyle.setFont(font);  
  
        // 設置單元格背景色  
        cellStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);  
        cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  
  
        HSSFCell cell3 = null;  
  
        for (int i = 0; i < columHeader.length; i++) {  
            cell3 = row2.createCell(i);  
            cell3.setCellType(HSSFCell.ENCODING_UTF_16);  
            cell3.setCellStyle(cellStyle);  
            cell3.setCellValue(new HSSFRichTextString(columHeader[i]));  
        }  
    }  
  
    /** 
     * 創建內容單元格 
     *  
     * @param wb 
     *            HSSFWorkbook 
     * @param row 
     *            HSSFRow 
     * @param col 
     *            short型的列索引 
     * @param align 
     *            對齊方式 
     * @param val 
     *            列值 
     */  
    public void cteateCell(HSSFWorkbook wb, HSSFRow row, int col, short align,  
            String val) {  
        HSSFCell cell = row.createCell(col);  
        cell.setCellType(HSSFCell.ENCODING_UTF_16);  
        cell.setCellValue(new HSSFRichTextString(val));  
        HSSFCellStyle cellstyle = wb.createCellStyle();  
        cellstyle.setAlignment(align);  
        cell.setCellStyle(cellstyle);  
    }  
  
    /** 
     * 創建合計行 
     *  
     * @param colSum 
     *            需要合併到的列索引 
     * @param cellValue 
     */  
    @SuppressWarnings("deprecation")  
    public void createLastSumRow(int colSum, String[] cellValue) {  
  
        HSSFCellStyle cellStyle = wb.createCellStyle();  
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 指定單元格居中對齊  
        cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 指定單元格垂直居中對齊  
        cellStyle.setWrapText(true);// 指定單元格自動換行  
  
        // 單元格字體  
        HSSFFont font = wb.createFont();  
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
        font.setFontName("宋體");  
        font.setFontHeight((short) 250);  
        cellStyle.setFont(font);  
        // 獲取工作表最後一行  
        HSSFRow lastRow = sheet.createRow((short) (sheet.getLastRowNum() + 1));  
        HSSFCell sumCell = lastRow.createCell(0);  
  
        sumCell.setCellValue(new HSSFRichTextString("合計"));  
        sumCell.setCellStyle(cellStyle);  
        // 合併 最後一行的第零列-最後一行的第一列  
        sheet.addMergedRegion(new Region(sheet.getLastRowNum(), (short) 0,  
                sheet.getLastRowNum(), (short) colSum));// 指定合併區域  
  
        for (int i = 2; i < (cellValue.length + 2); i++) {  
            // 定義最後一行的第三列  
            sumCell = lastRow.createCell(i);  
            sumCell.setCellStyle(cellStyle);  
            // 定義數組 從0開始。  
            sumCell.setCellValue(new HSSFRichTextString(cellValue[i - 2]));  
        }  
    }  
  
    /** 
     * 輸入EXCEL文件 
     *  
     * @param fileName 
     *            文件名 
     */  
    public void outputExcel(String fileName) {  
        FileOutputStream fos = null;  
        try {  
            fos = new FileOutputStream(new File(fileName));  
            wb.write(fos);  
            fos.close();  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
  
    /** 
     * @return the sheet 
     */  
    public HSSFSheet getSheet() {  
        return sheet;  
    }  
  
    /** 
     * @param sheet 
     *            the sheet to set 
     */  
    public void setSheet(HSSFSheet sheet) {  
        this.sheet = sheet;  
    }  
  
    /** 
     * @return the wb 
     */  
    public HSSFWorkbook getWb() {  
        return wb;  
    }  
  
    /** 
     * @param wb 
     *            the wb to set 
     */  
    public void setWb(HSSFWorkbook wb) {  
        this.wb = wb;  
    }  
}  

 

 

3.這裏只使用了Servlet,可以根據需要來使用在不同的地方。

[java] view plaincopy
package com.jeelon.exportExcle;  
  
import java.io.BufferedOutputStream;  
import java.io.IOException;  
import java.io.OutputStream;  
import java.util.ArrayList;  
import java.util.List;  
  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
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;  
  
@SuppressWarnings("serial")  
public class OutputExcel extends HttpServlet {  
  
    protected void doGet(HttpServletRequest request,  
            HttpServletResponse response) throws ServletException, IOException {  
        this.doPost(request, response);  
    }  
  
    protected void doPost(HttpServletRequest request,  
            HttpServletResponse response) throws ServletException, IOException {  
        System.out.println("helloworld");  
        List<Student> list = new ArrayList<Student>();  
  
        Student student1 = new Student(1, "Jeelon", 21, "貴陽市 ", "15085943968",  
                '男');  
        Student student2 = new Student(2, "fengxu", 21, "貴陽市 ", "15085943968",  
                '男');  
        Student student3 = new Student(3, "jerry", 21, "貴陽市 ", "15085943968",  
                '男');  
        Student student4 = new Student(4, "merry", 21, "貴陽市 ", "15085943968",  
                '男');  
        Student student5 = new Student(5, "lariiy", 21, "貴陽市 ", "15085943968",  
                '男');  
        Student student6 = new Student(6, "monr", 21, "貴陽市 ", "15085943968",  
                '男');  
        Student student7 = new Student(7, "join", 21, "貴陽市 ", "15085943968",  
                '男');  
        Student student8 = new Student(8, "jay chou", 21, "貴陽市 ",  
                "15085943968", '男');  
        Student student9 = new Student(9, "laonb", 21, "貴陽市 ", "15085943968",  
                '男');  
        Student student0 = new Student(0, "mudg", 21, "貴陽市 ", "15085943968",  
                '男');  
  
        list.add(student1);  
        list.add(student2);  
        list.add(student3);  
        list.add(student4);  
        list.add(student5);  
        list.add(student6);  
        list.add(student7);  
        list.add(student8);  
        list.add(student9);  
        list.add(student0);  
  
        String fileName = "導出Excel.xls";  
        fileName = new String(fileName.getBytes("GBK"), "iso8859-1");  
        response.reset();  
        response.setHeader("Content-Disposition", "attachment;filename="  
                + fileName);// 指定下載的文件名  
        response.setContentType("application/vnd.ms-excel");  
        response.setHeader("Pragma", "no-cache");  
        response.setHeader("Cache-Control", "no-cache");  
        response.setDateHeader("Expires", 0);  
        OutputStream output = response.getOutputStream();  
        BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);  
  
        // 定義單元格報頭  
        String worksheetTitle = "Excel導出Student信息";  
  
        HSSFWorkbook wb = new HSSFWorkbook();  
  
        // 創建單元格樣式  
        HSSFCellStyle cellStyleTitle = wb.createCellStyle();  
        // 指定單元格居中對齊  
        cellStyleTitle.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
        // 指定單元格垂直居中對齊  
        cellStyleTitle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
        // 指定當單元格內容顯示不下時自動換行  
        cellStyleTitle.setWrapText(true);  
        // ------------------------------------------------------------------  
        HSSFCellStyle cellStyle = wb.createCellStyle();  
        // 指定單元格居中對齊  
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
        // 指定單元格垂直居中對齊  
        cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
        // 指定當單元格內容顯示不下時自動換行  
        cellStyle.setWrapText(true);  
        // ------------------------------------------------------------------  
        // 設置單元格字體  
        HSSFFont font = wb.createFont();  
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
        font.setFontName("宋體");  
        font.setFontHeight((short) 200);  
        cellStyleTitle.setFont(font);  
  
        // 工作表名  
        String id = "id";  
        String name = "name";  
        String age = "age";  
        String address = "address";  
        String tel = "tel";  
        String sex = "sex";  
  
        HSSFSheet sheet = wb.createSheet();  
        ExportExcel exportExcel = new ExportExcel(wb, sheet);  
        // 創建報表頭部  
        exportExcel.createNormalHead(worksheetTitle, 6);  
        // 定義第一行  
        HSSFRow row1 = sheet.createRow(1);  
        HSSFCell cell1 = row1.createCell(0);  
  
        //第一行第一列  
          
        cell1.setCellStyle(cellStyleTitle);  
        cell1.setCellValue(new HSSFRichTextString(id));  
        //第一行第er列  
        cell1 = row1.createCell(1);  
        cell1.setCellStyle(cellStyleTitle);  
        cell1.setCellValue(new HSSFRichTextString(name));  
  
        //第一行第san列  
        cell1 = row1.createCell(2);  
        cell1.setCellStyle(cellStyleTitle);  
        cell1.setCellValue(new HSSFRichTextString(age));  
  
        //第一行第si列  
        cell1 = row1.createCell(3);  
        cell1.setCellStyle(cellStyleTitle);  
        cell1.setCellValue(new HSSFRichTextString(address));  
  
        //第一行第wu列  
        cell1 = row1.createCell(4);  
        cell1.setCellStyle(cellStyleTitle);  
        cell1.setCellValue(new HSSFRichTextString(tel));  
  
        //第一行第liu列  
        cell1 = row1.createCell(5);  
        cell1.setCellStyle(cellStyleTitle);  
        cell1.setCellValue(new HSSFRichTextString(sex));  
  
        //第一行第qi列  
        cell1 = row1.createCell(6);  
        cell1.setCellStyle(cellStyleTitle);  
        cell1.setCellValue(new HSSFRichTextString(sex));  
  
          
        //定義第二行  
        HSSFRow row = sheet.createRow(2);  
        HSSFCell cell = row.createCell(1);  
        Student student = new Student();  
        for (int i = 0; i < list.size(); i++) {  
            student = list.get(i);  
            row = sheet.createRow(i + 2);  
  
            cell = row.createCell(0);  
            cell.setCellStyle(cellStyle);  
            cell.setCellValue(new HSSFRichTextString(student.getId() + ""));  
              
            cell = row.createCell(1);  
            cell.setCellStyle(cellStyle);  
            cell.setCellValue(new HSSFRichTextString(student.getName()));  
              
            cell = row.createCell(2);  
            cell.setCellStyle(cellStyle);  
            cell.setCellValue(new HSSFRichTextString(student.getAge() + ""));  
              
            cell = row.createCell(3);  
            cell.setCellStyle(cellStyle);  
            cell.setCellValue(new HSSFRichTextString(student.getAddress() + ""));  
              
            cell = row.createCell(4);  
            cell.setCellStyle(cellStyle);  
            cell.setCellValue(new HSSFRichTextString(student.getAddress()));  
              
            cell = row.createCell(5);  
            cell.setCellStyle(cellStyle);  
            cell.setCellValue(new HSSFRichTextString(student.getTel()));  
              
            cell = row.createCell(6);  
            cell.setCellValue(new HSSFRichTextString(String.valueOf(student.getSex())));  
            cell.setCellStyle(cellStyle);  
              
        }  
        try {  
            bufferedOutPut.flush();  
            wb.write(bufferedOutPut);  
            bufferedOutPut.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
            System.out.println("Output   is   closed ");  
        } finally {  
            list.clear();  
        }  
    }  
}  

4.由於使用的是Servlet  ,當然還有配置Servlet哦  這裏就不再說樂吧  相信他對於你是so easy!

 

5.前臺jsp頁面:

 

[html] view plaincopy
導出數據到excel  
        <form action="excel" method="post">  
            <input type="submit" name="" value="導出">  
        </form>  
 

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