编译Schema:
xjc jxl.xsd -p jxl.jaxb
生成N多文件:
生成的Java文件全部放在jxl.jaxb包下。
然后对Excel类编辑:
@XmlRootElement(name="excel")//添加 @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "excel", propOrder = { "format", "sheet" }) public class Excel { ... }
JAXBExcel类:
构造函数:
public JAXBExcel(Source xml, Source xsl) { try { Transformer trans = TransformerFactory.newInstance() .newTransformer(xsl); JAXBContext context = JAXBContext.newInstance("jxl.jaxb"); JAXBResult result = new JAXBResult(context); trans.transform(xml, result); table = (Excel) result.getResult(); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty("jaxb.formatted.output", true); marshaller.setProperty("jaxb.encoding", "UTF-8"); marshaller.marshal(table, System.out); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } }
处理XML文件:
public void process(OutputStream os) throws IOException, WriteException, ParseException { if (table == null) { throw new RuntimeException("The table is not init yet"); } processFormat(table.getFormat()); WritableWorkbook excel = Workbook.createWorkbook(os); Iterator<ExcelSheet> excelSheets = table.getSheet().iterator(); for (int i = 0; excelSheets.hasNext(); i++) { ExcelSheet sheetData = excelSheets.next(); WritableSheet sheet = excel.createSheet(sheetData.getName(), i); // sheet.getSettings().setProtected(true); // sheet.getSettings().setPassword("zhaobq"); // 锁定单元格,设置保护密码 int row = 0; if (sheetData.getHead().getRow().size() > 0) { this.setView(sheet, sheetData.getHead().getRow().get( sheetData.getHead().getRow().size() - 1)); } row = processTitle(sheetData.getTitle(), sheet, row); row = processHead(sheetData.getHead(), sheet, row); row = processBody(sheetData.getBody(), sheet, row); row = processFoot(sheetData.getFoot(), sheet, row); }// TABLE excel.write(); excel.close(); }
JAXBExcel类中公共的方法就这两个:
首先用XML数据文件和XSL模板文件构造JAXBExcel对象,
然后用JAXBExcel.process()得到文件的输出流
全部代码:
package jxl; import static jxl.write.WritableFont.ARIAL; import static jxl.write.WritableFont.BOLD; import static jxl.write.WritableFont.DEFAULT_POINT_SIZE; import static jxl.write.WritableFont.NO_BOLD; import java.io.*; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import javax.xml.bind.*; import javax.xml.bind.util.JAXBResult; import javax.xml.transform.*; import jxl.format.*; import jxl.jaxb.*; import jxl.write.*; /** * * @author Allen 赵本钱 * */ public class JAXBExcel { private Excel table = null; /** * 默认CELLFORMAT */ public static Map<String, WritableCellFormat> CELL_FORMAT = new HashMap<String, WritableCellFormat>(); private Map<String, WritableCellFormat> cellFormat = null; private String numberFormat = "####.##"; private String dateFormat = "yyyy-MM-dd"; private static List<String> COLUMN_TYPE = new ArrayList<String>(); static { WritableFont foot = new WritableFont(ARIAL, 10); WritableFont body = foot; WritableFont head = new WritableFont(ARIAL, 10); WritableFont title = new WritableFont(ARIAL, 15); try { head.setBoldStyle(BOLD); title.setBoldStyle(BOLD); } catch (WriteException e) { e.printStackTrace(); } WritableCellFormat cfoot = new WritableCellFormat(); WritableCellFormat cbody = cfoot; WritableCellFormat chead = new WritableCellFormat(); WritableCellFormat ctitle = new WritableCellFormat(); try { cfoot.setAlignment(Alignment.GENERAL); cfoot.setWrap(false); chead.setAlignment(Alignment.CENTRE); chead.setWrap(false); chead.setBackground(Colour.GRAY_25); ctitle.setAlignment(Alignment.CENTRE); ctitle.setWrap(false); } catch (WriteException e) { e.printStackTrace(); } cfoot.setFont(foot); cbody.setFont(body); chead.setFont(head); ctitle.setFont(title); CELL_FORMAT.put("foot", cfoot); CELL_FORMAT.put("body", cbody); CELL_FORMAT.put("head", chead); CELL_FORMAT.put("title", ctitle); } public JAXBExcel(Source xml, Source xsl) { try { Transformer trans = TransformerFactory.newInstance().newTransformer(xsl); JAXBContext context = JAXBContext.newInstance("jxl.jaxb"); JAXBResult result = new JAXBResult(context); trans.transform(xml, result); table = (Excel) result.getResult(); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty("jaxb.formatted.output", true); marshaller.setProperty("jaxb.encoding", "UTF-8"); marshaller.marshal(table, System.out); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } } /* * (non-Javadoc) * * @see jxl.Excel#process(java.io.OutputStream) */ public void process(OutputStream os) throws IOException, WriteException, ParseException { if (table == null) { throw new RuntimeException("The table is not init yet"); } processFormat(table.getFormat()); WritableWorkbook excel = Workbook.createWorkbook(os); Iterator<ExcelSheet> excelSheets = table.getSheet().iterator(); for (int i = 0; excelSheets.hasNext(); i++) { ExcelSheet sheetData = excelSheets.next(); WritableSheet sheet = excel.createSheet(sheetData.getName(), i); // sheet.getSettings().setProtected(true); // sheet.getSettings().setPassword("zhaobq"); // 锁定单元格,设置保护密码 int row = 0; if (sheetData.getHead().getRow().size() > 0) { this.setView(sheet, sheetData.getHead().getRow().get(sheetData.getHead().getRow().size() - 1)); } row = processTitle(sheetData.getTitle(), sheet, row); row = processHead(sheetData.getHead(), sheet, row); row = processBody(sheetData.getBody(), sheet, row); row = processFoot(sheetData.getFoot(), sheet, row); }// TABLE excel.write(); excel.close(); } private void setView(WritableSheet sheet, ExcelRow view) { Iterator<ExcelHCell> hcell = view.getHcell().iterator(); for (int i = 0; hcell.hasNext(); i++) { ExcelHCell c = hcell.next(); if (null != c.getWidth()) { sheet.setColumnView(i, c.getWidth()); } if (null != c.getType()) { COLUMN_TYPE.add(c.getType()); } else { COLUMN_TYPE.add("string"); } } } /** * 处理Format节点 * * @param format * @throws WriteException */ private void processFormat(Format format) throws WriteException { if (format == null) { return; } Iterator<CellFormat> cf = format.getCellFormat().iterator(); cellFormat = new HashMap<String, WritableCellFormat>(); while (cf.hasNext()) { CellFormat f = cf.next(); String id = f.getId(); String backColour = f.getBackColour(); String foreColour = f.getForeColour(); String borderColour = f.getBorderColour(); String border = f.getBorder(); String align = f.getAlign(); String valign = f.getVerticalAlign(); String fontName = f.getFontName(); int fontSize = (null == f.getFontSize()) ? DEFAULT_POINT_SIZE : f.getFontSize(); boolean bold = nullToFalse(f.isBold()); boolean italic = nullToFalse(f.isItalic()); String underLine = f.getUnderLine(); WritableCellFormat cell = new WritableCellFormat(); if (isNotEmptyorNull(backColour)) { Colour c = null; try { c = fetchStaticObject(Colour.class, backColour); cell.setBackground(c); } catch (RuntimeException e) { e.printStackTrace(); } }// 背景 if (isNotEmptyorNull(align)) { Alignment a = null; try { a = fetchStaticObject(Alignment.class, align); cell.setAlignment(a); } catch (RuntimeException e) { e.printStackTrace(); } }// 水平对齐方式 if (isNotEmptyorNull(valign)) { VerticalAlignment a = null; try { a = fetchStaticObject(VerticalAlignment.class, align); cell.setVerticalAlignment(a); } catch (RuntimeException e) { e.printStackTrace(); } }// 垂直对齐方式 if (isNotEmptyorNull(border)) { String[] b = border.split(" "); if (b.length == 2) { Border bd = fetchStaticObject(Border.class, b[0]); BorderLineStyle bs = fetchStaticObject(BorderLineStyle.class, b[1]); if (isNotEmptyorNull(borderColour)) { Colour c = null; try { c = fetchStaticObject(Colour.class, borderColour); cell.setBorder(bd, bs, c); } catch (RuntimeException e) { e.printStackTrace(); } } else { cell.setBorder(bd, bs); } } } WritableFont fontFormat; if (isNotEmptyorNull(fontName)) { WritableFont.FontName font = null; try { font = fetchStaticObject(WritableFont.FontName.class, fontName); } catch (RuntimeException e) { e.printStackTrace(); font = WritableFont.createFont(fontName); } fontFormat = new WritableFont(font); } else { fontFormat = new WritableFont(ARIAL); }// 名字 fontFormat.setPointSize(fontSize);// 大小 if (bold) { fontFormat.setBoldStyle(BOLD); } else { fontFormat.setBoldStyle(NO_BOLD); }// 粗体 fontFormat.setItalic(italic);// 斜体 if (isNotEmptyorNull(underLine)) { UnderlineStyle us = null; try { us = fetchStaticObject(UnderlineStyle.class, underLine); } catch (RuntimeException e) { e.printStackTrace(); us = UnderlineStyle.NO_UNDERLINE; } fontFormat.setUnderlineStyle(us); }// 下划线 if (isNotEmptyorNull(foreColour)) { Colour c = null; try { c = fetchStaticObject(Colour.class, foreColour); } catch (RuntimeException e) { e.printStackTrace(); c = Colour.BLACK; } fontFormat.setColour(c); }// 颜色 cell.setFont(fontFormat); cell.setWrap(false); cellFormat.put(id, cell); } } /** * 处理Title节点 * * @param title * @param sheet * @param row * @return * @throws WriteException */ private int processTitle(ExcelTitle title, WritableSheet sheet, int row) throws WriteException { if (title == null) { return row; } WritableCellFormat cf = exactFormat(title.getCellFormat(), "title"); WritableCellFeatures ft = new WritableCellFeatures(); ft.setComment(title.getComment()); if (null != title.getHeight()) { sheet.setRowView(0, title.getHeight()); } int colspan = (null == title.getColspan()) ? 1 : title.getColspan(); this.writeLabel(sheet, cf, title.getValue(), 0, row, colspan, 1, ft); row++; return row; } /** * 处理Head节点 * * @param head * @param sheet * @param row * @return * @throws WriteException * @throws ParseException */ private int processHead(ExcelHead head, WritableSheet sheet, int row) throws WriteException, ParseException { if (head == null) { return row; } List<ExcelRow> rowDate = head.getRow(); if (null == rowDate || rowDate.isEmpty()) { return row; } WritableCellFormat cf = exactFormat(head.getCellFormat(), "head"); for (int i = 0; i < rowDate.size(); i++) { ExcelRow r = rowDate.get(i); if (null != r.getHeight()) { sheet.setRowView(row, r.getHeight()); } Iterator<ExcelHCell> c = r.getHcell().iterator(); for (int j = 0; c.hasNext(); j++) { ExcelHCell hcell = c.next(); processHCell(sheet, hcell, cf, row, j); } row++; } return row; } /** * 处理Body节点 * * @param body * @param sheet * @param row * @return * @throws WriteException * @throws ParseException */ private int processBody(ExcelBody body, WritableSheet sheet, int row) throws WriteException, ParseException { if (body == null) { return row; } List<ExcelRow> rowDate = body.getRow(); if (rowDate == null || rowDate.isEmpty()) { return row; } WritableCellFormat cf = exactFormat(body.getCellFormat(), "body"); for (int i = 0; i < rowDate.size(); i++) { ExcelRow r = rowDate.get(i); if (null != r.getHeight()) { sheet.setRowView(row, r.getHeight()); } Iterator<ExcelCell> c = r.getCell().iterator(); for (int j = 0; c.hasNext(); j++) { ExcelCell cell = c.next(); String type = COLUMN_TYPE.get(j); String cfname = cell.getCellFormat(); if (isNotEmptyorNull(cfname)) { processCell(sheet, cell, exactCellFormat(cell.getCellFormat()), type, row, j); } else { processCell(sheet, cell, cf, type, row, j); } } row++; } return row; } /** * 处理Foot节点 * * @param foot * @param sheet * @param row * @return * @throws WriteException * @throws ParseException */ private int processFoot(ExcelFoot foot, WritableSheet sheet, int row) throws WriteException, ParseException { if (foot == null) { return row; } List<ExcelRow> rowDate = foot.getRow(); if (rowDate == null || rowDate.isEmpty()) { return row; } WritableCellFormat cf = exactFormat(foot.getCellFormat(), "foot"); for (int i = 0; i < rowDate.size(); i++) { ExcelRow r = rowDate.get(i); if (null != r.getHeight()) { sheet.setRowView(row, r.getHeight()); } Iterator<ExcelCell> c = r.getCell().iterator(); for (int j = 0; c.hasNext(); j++) { ExcelCell cell = c.next(); String type = COLUMN_TYPE.get(j); String cfname = cell.getCellFormat(); if (isNotEmptyorNull(cfname)) { processCell(sheet, cell, exactCellFormat(cell.getCellFormat()), type, row, j); } else { processCell(sheet, cell, cf, type, row, j); } } row++; } return row; } /** * 获取Format信息 * * @param cellFormatName * @param font * @param position * @return */ private WritableCellFormat exactFormat(String cellFormatName, String position) { WritableCellFormat cf; if (isNotEmptyorNull(cellFormatName)) { cf = this.cellFormat.get(cellFormatName); } else { cf = CELL_FORMAT.get(position); }// SETTING THE CELL FORMAT return cf; } /** * 获取Cell Format信息 * * @param cellFormatName * @param font * @param position * @return */ private WritableCellFormat exactCellFormat(String cellFormatName) { WritableCellFormat cf = null; if (isNotEmptyorNull(cellFormatName)) { cf = this.cellFormat.get(cellFormatName); } // SETTING THE CELL FORMAT return cf; } /** * 处理单元格 * * @param sheet * @param cell * @param cellFormat * @param row * @param j * @throws WriteException * @throws ParseException */ private void processCell(WritableSheet sheet, ExcelCell cell, WritableCellFormat cellFormat, String type, int row, int j) throws WriteException, ParseException { Integer c = (null == cell.getColspan()) ? 1 : cell.getColspan(); Integer r = (null == cell.getRowspan()) ? 1 : cell.getRowspan(); WritableCellFeatures features = new WritableCellFeatures(); features.setComment(cell.getComment()); if (!isNotEmptyorNull(type)) { type = "string"; } if (type.equalsIgnoreCase("date")) { writeDate(sheet, cellFormat, cell.getValue(), j, row, c, r, features); } else if (type.equalsIgnoreCase("number")) { writeNumber(sheet, cellFormat, Double.parseDouble(cell.getValue()), j, row, c, r, features); } else { writeLabel(sheet, cellFormat, cell.getValue(), j, row, c, r, features); } } /** * 处理单元格 * * @param sheet * @param cell * @param cellFormat * @param row * @param j * @throws WriteException * @throws ParseException */ private void processHCell(WritableSheet sheet, ExcelHCell cell, WritableCellFormat cellFormat, int row, int j) throws WriteException, ParseException { Integer c = (null == cell.getColspan()) ? 1 : cell.getColspan(); Integer r = (null == cell.getRowspan()) ? 1 : cell.getRowspan(); WritableCellFeatures features = new WritableCellFeatures(); features.setComment(cell.getComment()); writeLabel(sheet, cellFormat, cell.getValue(), j, row, c, r, features); } /** * 写普通格式数据 * * @param sheet * @param cellFormat * @param labelName * @param x * @param y * @param width * @param height * @throws WriteException */ private void writeLabel(WritableSheet sheet, WritableCellFormat cellFormat, String labelName, int x, int y, int width, int height, WritableCellFeatures ft) throws WriteException { if ((x >= 0) && (y >= 0) && (width > 0) && (height > 0)) { Label c = null; if ((width != 1) || (height != 1)) { sheet.mergeCells(x, y, (x + width) - 1, (y + height) - 1); } c = new Label(x, y, labelName, cellFormat); c.setCellFeatures(ft); sheet.addCell(c); } } /** * 写数字类型数据 * * @param sheet * @param cellFormat * @param numberData * @param x * @param y * @param width * @param height * @throws WriteException */ private void writeNumber(WritableSheet sheet, WritableCellFormat cellFormat, double numberData, int x, int y, int width, int height, WritableCellFeatures ft) throws WriteException { if ((x >= 0) && (y >= 0) && (width > 0) && (height > 0)) { jxl.write.Number c = null; if ((width != 1) || (height != 1)) { sheet.mergeCells(x, y, (x + width) - 1, (y + height) - 1); } c = new jxl.write.Number(x, y, numberData, cellFormat); c.setCellFeatures(ft); sheet.addCell(c); } } /** * 写日期类型的数据 * * @param sheet * @param cellFormat * @param date * @param x * @param y * @param width * @param height * @throws WriteException * @throws ParseException */ private void writeDate(WritableSheet sheet, WritableCellFormat cellFormat, String date, int x, int y, int width, int height, WritableCellFeatures ft) throws WriteException, ParseException { if ((x >= 0) && (y >= 0) && (width > 0) && (height > 0)) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat); DateTime c = new DateTime(x, y, simpleDateFormat.parse(date), cellFormat); if ((width != 1) || (height != 1)) { sheet.mergeCells(x, y, (x + width) - 1, (y + height) - 1); } c.setCellFeatures(ft); sheet.addCell(c); } } @SuppressWarnings("unchecked") private <T> T fetchStaticObject(Class<T> clazz, String name) { T t = null; try { t = (T) clazz.getDeclaredField(name).get(null); } catch (Exception e) { throw new RuntimeException(e.getMessage() + "不能找类:" + clazz.getName() + "的静态字段:" + name); } return t; } /** * 判断字符串是否为null或者空 * * @param str * @return */ public static boolean isNotEmptyorNull(String str) { if (null != str && !"".equals(str)) { return true; } return false; } public static boolean nullToFalse(Boolean b) { if (null == b) { return false; } else return b; } public void setNumberFormat(String nf) { this.numberFormat = nf; } public void setDateFormat(String df) { this.dateFormat = df; } public static String say() { return "I Said ,I'M Allen"; } }
使用:
String xml = "FOP.XML"; String xsl = "FOP.XSL"; JAXBExcel helper = new JAXBExcel(new StreamSource(new File(xml)), new StreamSource(new File(xsl))); File f = new File("C:/a.xls"); OutputStream os = new FileOutputStream(f); helper.process(os); os.close();
其中FOP.xml FOP.xsl文件见附件:
相关推荐
在实际项目中,通常会创建工具类来封装这些操作,以提高代码的复用性和可维护性。工具类可能包含如`exportToExcel()`和`importFromExcel()`等方法,分别用于数据导出和导入。导入时,通常会解析Excel文件,将数据...
在Java编程领域,导出Excel数据是一项常见的任务,特别...通过合理的封装和设计,可以使得这类工具类在不同的项目中重用,降低维护成本。同时,`jxl`库提供的API丰富且易于理解,是进行Java Excel操作的一个优秀选择。
本文章要介绍的是一个对JXL框架进行封装,实现读取Excle文件数据并生成相应的Entity对象,实现直接将Entity数据写入到Excellent文件中。 JXLUtil框架功能 1、读取Excle数据,生成相应的Entity 2、将Entity数据...
**JXL工具详解:实现Excel数据导入数据库** 在IT行业中,数据处理是一项常见的任务,而Excel作为广泛使用的电子表格软件,其数据导入到数据库的操作尤为常见。`jxl`库是一个Java库,专为处理Excel文件(.xls格式)...
综上所述,`jxl`库为Java开发者提供了一个强大的工具,用于处理Excel文件。通过熟悉其API,我们可以高效地读取、解析和操作Excel数据,满足各种业务需求。不过要注意,`jxl`库只支持旧版的`.xls`格式,对于`.xlsx`新...
在IT行业中,处理数据是日常任务之一,而Excel作为数据管理的重要工具,其与编程语言的结合使用可以大大提高工作效率。本话题聚焦于使用Java的JXL库来实现对Excel文件中两列数据的比较,从而找出不同和相同值的功能...
jxl.jar库为Java开发者提供了一个强大的工具,它允许我们方便地读取、写入和修改Excel文件。本文将对jxl.jar的源码进行深入探讨,揭示其内部工作机制,帮助读者更好地理解和利用这个开源库。 首先,jxl.jar的核心...
对于复杂的导入需求,如批量导入,我们可以创建一个`ExcelUtil`工具类,封装上述操作,提供便捷的接口供其他模块调用。例如,`importDataFromExcel(String filePath, ImportConfig config)`方法,其中`ImportConfig`...
在实际应用中,通常我们会封装这些操作到一个工具类中,比如`ExcelUtil`,以便于复用和管理。这个类可以包含读取单个单元格、整列数据,甚至整个工作簿的各种方法。 总的来说,jxl库为Java开发者提供了一种便捷的...
在实际应用中,通常会将上述代码封装成一个服务或工具类,以便在需要导出Excel时调用。这样不仅可以复用代码,还能提高开发效率。 总结来说,`jxl`库为Java开发者提供了一个强大而灵活的工具,用于生成和处理Excel...
总的来说,JXL是一个强大的工具,对于需要在Java应用中生成或处理Excel报表的开发者来说,是一个很好的选择。通过封装类,我们可以将复杂的JXL操作简化,提高代码的可读性和可维护性。学习并理解这个例子,将有助于...
`PoiUtil.java`工具类可能封装了这些基本操作,提供方便的方法,例如`readExcel()`或`readSheet()`,以简化读取Excel数据的过程。 2. **JExcelApi (JXL)**: - **Workbook接口**:与POI类似,JXL也有一个名为`...
Java中的JXL库是一个非常实用的工具,它允许开发者创建、读取和修改Microsoft Excel文件。在本例中,我们将探讨如何使用JXL库来创建一个Excel文件,并对其进行各种定制,如合并单元格、设置列和单元格的属性,包括...
总的来说,jxl库结合Row-Bean模式,为Java开发者提供了一个强大且灵活的工具来处理Excel数据。这种模式不仅简化了数据的读取和写入,还使得数据处理过程更加直观,尤其适合处理结构化的数据表格。通过熟练掌握这一...
压缩包中的`JxlExcelUtils.java`文件很可能是封装好的工具类,它可能包含了一些静态方法,以便于开发者快速调用,例如批量导出数据到Excel。这样的工具类通常会提供如`exportToExcel(List<T> dataList, Class)`这样...
总的来说,"JXLExcel生成简单excel表"是一个旨在简化Java开发中Excel处理的工具,通过抽象和封装,降低了JXL库的使用难度,使得开发者可以更高效地进行数据导出和报告生成工作。在实际开发中,这样的工具能极大地...
这个工具类的实现充分利用了JXL库的功能,为Java开发者提供了一个便捷的方式来处理Excel数据的导入和导出。下面我们将深入探讨这个实用工具类背后的原理和关键知识点。 1. **JXL库介绍** JXL库允许Java应用程序与...
在实际项目中,通常会封装成一个工具类,提供静态方法供其他代码调用,以实现读写Excel的便捷功能。例如,该类可能包含`writeExcel()`和`readExcel()`方法,分别用于创建和读取Excel文件。 总结起来,Java中的JXL库...
在实际应用中,我们通常会将这些操作封装成服务或工具类,以便在不同地方重用。例如,你可以创建一个`ExcelService`和`XmlService`,分别包含读写Excel和XML的方法。提供的`ExcelDome`文件可能就是这样一个示例,...
而“JExcelUtil.java”很可能是一个自定义工具类,封装了使用jxl库的常用操作。这样的工具类可以提高代码复用性,减少重复代码。它可能包含静态方法,如`public static void writeExcel(List<List<String>> data, ...