Java导出Excel工具类

ExcelUtil.java

package util;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

public class ExcelUtil {
    public static void createExcel(OutputStream out, String[] title, List<Object[]> content) throws Exception {
        // 创建工作薄
        WritableWorkbook workbook = null;
        try {
            workbook = Workbook.createWorkbook(out);

            // 创建新的一页
            WritableSheet sheet = workbook.createSheet("Sheet1", 0);

            // 创建要显示的内容,创建一个单元格,第一个参数为列坐标,第二个参数为行坐标,第三个参数为内容
            for (int i = 0; i < title.length; i++) {
                Label label = new Label(i, 0, title[i]);
                sheet.addCell(label);
            }

            int rows = content.size();
            for (int row = 0; row < rows; row++) {
                Object[] record = content.get(row);
                for (int col = 0; col < record.length; col++) {
                    Object obj = record[col];
                    if (obj instanceof Integer) {
                        Number number = new Number(col, row + 1, (Integer) obj);
                        sheet.addCell(number);
                    } else if (obj instanceof Double) {
                        Number number = new Number(col, row + 1, (Double) obj);
                        sheet.addCell(number);
                    } else {
                        Label label = new Label(col, row + 1, (String) obj);
                        sheet.addCell(label);
                    }
                }
            }

            // 把创建的内容写入到输出流中,并关闭输出流
            workbook.write();
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("导出Excel异常", e);
        } finally {
            if (null != workbook) {
                try {
                    workbook.close();
                } catch (WriteException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

 

posted @ 2018-06-25 09:53  诚信天下  阅读(664)  评论(0编辑  收藏  举报