package org.wisdomfish.doc; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.util.List; import jxl.Workbook; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import jxl.write.WriteException; import jxl.write.biff.RowsExceededException; public class Excel { /** * * @param os * @param headers * @param data * @return unclosed WritableWorkbook * @throws IOException * @throws RowsExceededException * @throws WriteException */ public WritableWorkbook export(OutputStream os, String[] headers, String[][] data) throws IOException, RowsExceededException, WriteException { // new Excel and Sheet WritableWorkbook wwb = Workbook.createWorkbook(os); WritableSheet ws = wwb.createSheet("Sheet 1", 0); insertHeaderAndData(ws, headers, data); wwb.write(); wwb.close(); return wwb; } /** * * @param os * @param headers * @param data * @return unclosed WritableWorkbook * @throws IOException * @throws RowsExceededException * @throws WriteException */ public WritableWorkbook export(OutputStream os, List<String> headers, List<List<String>> data) throws RowsExceededException, WriteException, IOException { String[][] dataArray = new String[data.size()][headers.size()]; // 這段可以拆到org.wisdomfish.util 作為 二維轉換的API for (int i = 0; i < dataArray.length; i++) { for (int j = 0; j < dataArray[i].length; j++) { dataArray[i][j] = data.get(i).get(j); } } String[] headersArray = new String[headers.size()]; for (int i = 0; i < headersArray.length; i++) { headersArray[i] = headers.get(i); } return export(os, headersArray, dataArray); } /** * * @param os * @param headers * @param data * @return unclosed WritableWorkbook * @throws IOException * @throws RowsExceededException * @throws WriteException */ public WritableWorkbook export(File file, String[] headers, String[][] data) throws IOException, RowsExceededException, WriteException { // new Excel and Sheet WritableWorkbook wwb = Workbook.createWorkbook(file); WritableSheet ws = wwb.createSheet("Sheet 1", 0); insertHeaderAndData(ws, headers, data); wwb.write(); wwb.close(); return wwb; } private void insertHeaderAndData(WritableSheet ws, String[] headers, String[][] data) throws RowsExceededException, WriteException { // 這兩行保證immutable String[] headersCopy = headers.clone(); String[][] dataCopy = data.clone(); // insert header Label label = null; int row = 0; // first row for (int index = 0; index < headersCopy.length; index++) { label = new Label(index, row, headersCopy[index]); ws.addCell(label); } // insert data for (int i = 0; i < dataCopy.length; i++) { row += 1; // next row for (int j = 0; j < dataCopy[i].length; j++) { label = new Label(j, row, dataCopy[i][j]); ws.addCell(label); } } } } |
R01.Non-JEE >