自己写的Java导出Excel组件
自己写的,记录下来,方便以后使用。
package org.wsr.utils;import java.io.IOException;import java.io.OutputStream;import java.util.Iterator;import java.util.List;import jxl.Workbook;import jxl.format.Colour;import jxl.write.Label;import jxl.write.WritableCellFormat;import jxl.write.WritableFont;import jxl.write.WritableSheet;import jxl.write.WritableWorkbook;import jxl.write.WriteException;/** * 导出excel工具 110829 * * @author wangsr * */public class JXLUtils {/** * 导出excel * @param os 输出流 * @param data 导出数据,格式:list(0)为标题的名字,list(1..n)vo/po的属性 * 例如: * list(0){"姓名","年龄","性别"} * list(1..n){"张三","10","男"},{"李四","10","女"} * @param sheetName sheet1的名字(暂时只有一个sheet) * @throws Exception */public static void exportExcel(OutputStream os, List<String[]> data,String sheetName) throws Exception {if (data == null || data.size() == 0) {throw new Exception("导出的数据不能为空!!");} else {// 创建工作簿try {WritableWorkbook wb = Workbook.createWorkbook(os);// 创建工作表WritableSheet sheet = wb.createSheet(sheetName, 0);//设置默认宽度sheet.getSettings().setDefaultColumnWidth(15);// 字体格式WritableFont wf = new WritableFont(WritableFont.ARIAL, 10,WritableFont.BOLD);WritableCellFormat wcf = new WritableCellFormat(wf);// 设置背景色wcf.setBackground(Colour.LIGHT_GREEN);// 对对齐方式wcf.setAlignment(jxl.format.Alignment.CENTRE);int count = 0;int[] len = new int[data.get(0).length];Iterator<String[]> iter = data.iterator();while (iter.hasNext()) {String[] temp = iter.next();// 单元格Label label = null;// 标题行,第一列为序号if (count == 0) {//标题行有特殊的格式(第一行)label = new Label(0, 0, "序号", wcf);sheet.addCell(label);for (int i = 0; i < temp.length; i++) {label = new Label(i+1, 0, temp[i], wcf);//设置列宽int tempLen = temp[i].getBytes().length;if (tempLen > len[i] && tempLen > 15) {//默认列宽为15,如果有大于15的列,则记下了,//并将该列设置为改宽度+4(效果好看点)【因为需求要求列必须容纳所有内容,而jxl不能自动适应列宽,所有手动设置】sheet.setColumnView(i+1, tempLen + 4);//每次都要记录下最大的列宽,方便添加新的一行数据时使用该值len[i] = tempLen;}sheet.addCell(label);}count++;} else {//第一列为序号jxl.write.Number labelNum = new jxl.write.Number(0, count, count);sheet.addCell(labelNum);// 内容列//列宽int tempLen = 0;for (int i = 0; i < temp.length; i++) {// 是数字的转化一下if (temp[i] != null && temp[i].trim().matches("[+-]?((0|([1-9]+[0-9]*))(\\.[0-9]+)?)")) {labelNum = new jxl.write.Number(i+1, count, Double.valueOf(temp[i]));sheet.addCell(labelNum);} else {label = new Label(i+1, count, temp[i]);sheet.addCell(label);}// 设置列宽if (temp[i] != null){tempLen = temp[i].getBytes().length;}if (tempLen > len[i] && tempLen > 15) {sheet.setColumnView(i+1, tempLen + 1);len[i] = tempLen;}}count++;}}// 写出wb.write();wb.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (WriteException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}??