自己写的,记录下来,方便以后使用。
package org.wsr.util; 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) { 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); // 内容列 for (int i = 0; i < temp.length; i++) { // 是数字的转化一下 if (temp[i].trim().matches("[+-]?[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); } // 设置列宽 int 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 block e.printStackTrace(); } catch (WriteException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
?