JAVA通過JXL工具操作EXCEL文件

由於數據量太大,頁面無法顯示全部,需要導出一個excel文件,查閱了一些資料,寫了個工具類,方便以後使用,與大家共享,有啥不足的希望指出,一起學習,專業報表二十年。哈哈

  1. 下面是工具類代碼,僅供參考:
package com.data.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sun.misc.BASE64Encoder;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

/**
 * 
 * @Title: ExcelUtil.java
 * @author you.xu
 * @version 1.0
 */
public class ExcelUtil {

    /**
     * 創建Excel文件流
     * 
     * @return
     */
    public static WritableWorkbook cWorkbook(OutputStream os) {
        try {
            return Workbook.createWorkbook(os);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 創建工作表
     * 
     * @param b
     * @param idx
     *            工作表索引,從1開始
     * @param name
     *            工作表顯示名稱
     * @return
     */
    public static WritableSheet cSheet(WritableWorkbook b, int idx, String name) {
        return b.createSheet(name, idx - 1);
    }

    /**
     * 創建單元格
     * 
     * @param a
     *            行
     * @param b
     *            列
     * @param value
     *            值
     * @return
     */
    public static Label cLabel(int a, int b, String value) {
        return new Label(b - 1, a - 1, value);
    }

    /**
     * 添加Label到Sheet
     * 
     * @param l
     *            label
     * @param s
     *            sheet
     */
    public static void aLabelToSheet(Label l, WritableSheet s) {
        try {
            s.addCell(l);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 設置工作表列寬
     * 
     * @param s
     * @param idx
     *            索引從1開始
     * @param width
     *            字符寬度
     */
    public static void sColumnSize(WritableSheet s, int idx, int width) {
        s.setColumnView(idx - 1, width);
    }

    /**
     * 設置工作表高度
     * 
     * @param s
     * @param idx
     *            索引從1開始
     * @param height
     *            字符高度
     */
    public static void sRowSize(WritableSheet s, int idx, int height) {
        try {
            s.setRowView(idx - 1, height * 20);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 設置單元格合併
     * 
     * @param a
     *            起始單元格行
     * @param b
     *            起始單元格列
     * @param c
     *            終止單元格行
     * @param d
     *            終止單元格列
     */
    public static void sMerge(WritableSheet s, int a, int b, int c, int d) {
        try {
            s.mergeCells(b - 1, a - 1, d - 1, c - 1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 設置單元格樣式
     * 
     * @param l
     * @param fontName
     *            字體:字符串,如"黑體"
     * @param fontSize
     *            字號:數字,如24
     * @param colour
     *            字體顏色:Colour常量
     * @param bgColour
     *            單元格背景色:Colour常量
     * @param align
     *            對齊模式:0-左;1-中;2-右
     * @param borderStyle
     *            邊框線樣式:字符串,如0000代表上下左右都不要邊框,
     *            如1100代表上下要邊框,如0011代表左右要邊框,如果0220代表左邊和下邊要粗邊框
     */
    public static void sLabelStyle(Label l, String fontName, int fontSize,
            Colour colour, Colour bgColour, int align, String borderStyle) {

        try {
            if (colour == null)
                colour = Colour.BLACK;
            if (bgColour == null)
                bgColour = Colour.WHITE;
            WritableFont wf = new WritableFont(
            // 設置字體
                    WritableFont.createFont(fontName),
                    // 設置字號
                    fontSize,
                    // 設置加粗
                    WritableFont.NO_BOLD,
                    // 設置傾斜
                    false,
                    // 設置下劃線
                    UnderlineStyle.NO_UNDERLINE,
                    // 設置字體顏色
                    colour);

            WritableCellFormat wcf = new WritableCellFormat(wf);
            // 設置背景色
            wcf.setBackground(bgColour);
            // 設置對其方式
            wcf.setAlignment(Alignment.CENTRE);

            // 設置邊框
            if (borderStyle != null && borderStyle.length() == 4) {
                char[] bs = borderStyle.toCharArray();
                if (bs[0] == '1') {
                    wcf.setBorder(Border.TOP, BorderLineStyle.THIN,
                            jxl.format.Colour.BLACK);
                } else if (bs[0] == '2') {
                    wcf.setBorder(Border.TOP, BorderLineStyle.MEDIUM,
                            jxl.format.Colour.BLACK);
                }
                if (bs[1] == '1') {
                    wcf.setBorder(Border.BOTTOM, BorderLineStyle.THIN,
                            jxl.format.Colour.BLACK);
                } else if (bs[1] == '2') {
                    wcf.setBorder(Border.BOTTOM, BorderLineStyle.MEDIUM,
                            jxl.format.Colour.BLACK);
                }
                if (bs[2] == '1') {
                    wcf.setBorder(Border.LEFT, BorderLineStyle.THIN,
                            jxl.format.Colour.BLACK);
                } else if (bs[2] == '2') {
                    wcf.setBorder(Border.LEFT, BorderLineStyle.MEDIUM,
                            jxl.format.Colour.BLACK);
                }
                if (bs[3] == '1') {
                    wcf.setBorder(Border.RIGHT, BorderLineStyle.THIN,
                            jxl.format.Colour.BLACK);
                } else if (bs[3] == '2') {
                    wcf.setBorder(Border.RIGHT, BorderLineStyle.MEDIUM,
                            jxl.format.Colour.BLACK);
                }
            }

            l.setCellFormat(wcf);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void downExcel(String fileName, HttpServletRequest request,
            HttpServletResponse response, ByteArrayOutputStream bos)
            throws Exception {
        // 當前excel文件的內容已經寫入到流os對象中,該流是一個輸出流
        // 表現層需要的是輸入流
        // 輸出流轉輸入流
        String mimeType = request.getServletContext().getMimeType(fileName);
        response.setContentType(mimeType);

        String agent = request.getHeader("user-agent");
        if (agent.contains("MSIE")) {
            // IE瀏覽器
            fileName = URLEncoder.encode(fileName, "utf-8");

        } else if (agent.contains("Firefox")) {
            // 火狐瀏覽器
            BASE64Encoder base64Encoder = new BASE64Encoder();
            fileName = "=?utf-8?B?"
                    + base64Encoder.encode(fileName.getBytes("utf-8")) + "?=";
        } else {
            // 其它瀏覽器
            fileName = URLEncoder.encode(fileName, "utf-8");
        }
        response.setContentType("application/msexcel;charset=GBK");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=\""
                + new String(fileName.getBytes(), "ISO8859-1") + "\"");
        ByteArrayInputStream downloadExcelStreamn = new ByteArrayInputStream(
                bos.toByteArray());
        OutputStream os = response.getOutputStream(); // 將要下載的文件內容通過輸出流寫回到瀏覽器端.
        int len = -1;
        byte[] b = new byte[1024 * 100];

        while ((len = downloadExcelStreamn.read(b)) != -1) {
            os.write(b, 0, len);
            os.flush();
        }
        os.close();
        downloadExcelStreamn.close();
    }
}

現在是我項目中目前所用到的其中的部分工具,代碼如下:

//創建輸出流
ByteArrayOutputStream bos = new ByteArrayOutputStream();
//創建Excel文件流
WritableWorkbook w = Workbook.createWorkbook(bos);
//創建工作表
WritableSheet s = w.createSheet("工作表名稱", 0);
//設置工作表列寬
ExcelUtil.sColumnSize(s, 1, 25);
ExcelUtil.sColumnSize(s, 2, 35);
ExcelUtil.sColumnSize(s, 3, 35);
ExcelUtil.sColumnSize(s, 4, 25);
//創建單元格
Label lab11 = ExcelUtil.cLabel(1, 1, "單元格值");
//設置單元格樣式,具體看工具類
ExcelUtil.sLabelStyle(lab11, "黑體", 18, Colour.BLACK,
        Colour.LIGHT_BLUE, 1, "2020");
//將單元格加入到工作表中
ExcelUtil.aLabelToSheet(lab11, s);
//同上
Label lab12 = ExcelUtil.cLabel(1, 2, "單元格值");
ExcelUtil.sLabelStyle(lab12, "黑體", 18, Colour.BLACK,
        Colour.LIGHT_BLUE, 1, "2020");
ExcelUtil.aLabelToSheet(lab12, s);
//遍歷list集合,將數據插入到單元格中
for (int j = 0; j < list.size(); j++) {
    Label lab_data_1 = ExcelUtil.cLabel(j + 2, 1, radioTypeList
            .get(j).getCode());
    ExcelUtil.sLabelStyle(lab_data_1, "宋體", 14, Colour.BLACK,
            Colour.WHITE, 1, "0110");
    ExcelUtil.aLabelToSheet(lab_data_1, s);

    Label lab_data_2 = ExcelUtil.cLabel(j + 2, 2, radioTypeList
            .get(j).getM().toString());
    ExcelUtil.sLabelStyle(lab_data_2, "宋體", 14, Colour.BLACK,
            Colour.WHITE, 1, "0110");
    ExcelUtil.aLabelToSheet(lab_data_2, s);

    Label lab_data_3 = ExcelUtil.cLabel(j + 2, 3, radioTypeList
            .get(j).getN().toString());
    ExcelUtil.sLabelStyle(lab_data_3, "宋體", 14, Colour.BLACK,
            Colour.WHITE, 1, "0110");
    ExcelUtil.aLabelToSheet(lab_data_3, s);
    Label lab_data_4 = ExcelUtil.cLabel(j + 2, 4, radioTypeList
            .get(j).getValue());
    ExcelUtil.sLabelStyle(lab_data_4, "宋體", 14, Colour.BLACK,
            Colour.WHITE, 1, "0110");
    ExcelUtil.aLabelToSheet(lab_data_4, s);
}
//寫流,關流
w.write();
w.close();
String fileName = "單元格名稱.xls";
ExcelUtil.downExcel(fileName, request, response, bos);
//通過response返回到前臺,無需返回值

相關資料可以查看http://download.csdn.net/detail/super_man_x/9366341 包含jxl源碼,和兩個文檔。

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