<?xml version="1.0" encoding="UTF-8"?> <excel id="student" code="student" name="學生信息導入"> <colgroup> <col index="A" width='17em'></col> <col index="B" width='17em'></col> <col index="C" width='17em'></col> <col index="D" width='17em'></col> <col index="E" width='17em'></col> <col index="F" width='17em'></col> </colgroup> <title> <tr height="16px"> <td rowspan="1" colspan="6" value="學生信息導入" /> </tr> </title> <thead> <tr height="16px"> <th value="編號" /> <th value="姓名" /> <th value="年齡" /> <th value="性別" /> <th value="出生日期" /> <th value=" 愛好" /> </tr> </thead> <tbody> <tr height="16px" firstrow="2" firstcol="0" repeat="5"> <td type="string" isnullable="false" maxlength="30" /><!--用戶編號 --> <td type="string" isnullable="false" maxlength="50" /><!--姓名 --> <td type="numeric" format="##0" isnullable="false" /><!--年齡 --> <td type="enum" format="男,女" isnullable="true" /><!--性別 --> <td type="date" isnullable="false" maxlength="30" /><!--出生日期 --> <td type="enum" format="足球,籃球,乒乓球" isnullable="true" /><!--愛好 --> </tr> </tbody> </excel>
HSSFCellStyle cellStyle = wb.createCellStyle();//建立單元格樣式
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);//設置單元格對齊方式java
HSSFFont font = wb.createFont(); font.setFontName("仿宋_GB2312"); font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//字體加粗 //font.setFontHeight((short)12); font.setFontHeightInPoints((short)12); cellStyle.setFont(font); cell.setCellStyle(cellStyle);
sheet.addMergedRegion(new CellRangeAddress(rspan, rspan, 0, cspan));
/** * 測試單元格樣式 * @author David * @param wb * @param cell * @param td */ private static void setType(HSSFWorkbook wb, HSSFCell cell, Element td) { Attribute typeAttr = td.getAttribute("type"); String type = typeAttr.getValue(); HSSFDataFormat format = wb.createDataFormat(); HSSFCellStyle cellStyle = wb.createCellStyle(); if("NUMERIC".equalsIgnoreCase(type)){ cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC); Attribute formatAttr = td.getAttribute("format"); String formatValue = formatAttr.getValue(); formatValue = StringUtils.isNotBlank(formatValue)? formatValue : "#,##0.00"; cellStyle.setDataFormat(format.getFormat(formatValue)); }else if("STRING".equalsIgnoreCase(type)){ cell.setCellValue(""); cell.setCellType(HSSFCell.CELL_TYPE_STRING); cellStyle.setDataFormat(format.getFormat("@")); }else if("DATE".equalsIgnoreCase(type)){ cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC); cellStyle.setDataFormat(format.getFormat("yyyy-m-d")); }else if("ENUM".equalsIgnoreCase(type)){ CellRangeAddressList regions = new CellRangeAddressList(cell.getRowIndex(), cell.getRowIndex(), cell.getColumnIndex(), cell.getColumnIndex()); Attribute enumAttr = td.getAttribute("format"); String enumValue = enumAttr.getValue(); //加載下拉列表內容 DVConstraint constraint = DVConstraint.createExplicitListConstraint(enumValue.split(",")); //數據有效性對象 HSSFDataValidation dataValidation = new HSSFDataValidation(regions, constraint); wb.getSheetAt(0).addValidationData(dataValidation); } cell.setCellStyle(cellStyle); }
/** * 方法名稱:SetDataValidation * 內容摘要:設置數據有效性 * @param sheet excel sheet內容 * @param textList 下拉列表 * @param firstRow 單元格範圍 * @param firstCol * @param endRow * @param endCol */ private static HSSFDataValidation setDataValidation(HSSFSheet sheet,String[] textList,short firstRow,short firstCol, short endRow, short endCol) { //加載下拉列表內容 DVConstraint constraint = DVConstraint.createExplicitListConstraint(textList); //設置數據有效性加載在哪一個單元格上。 //四個參數分別是:起始行、終止行、起始列、終止列 CellRangeAddressList regions = new CellRangeAddressList(firstRow,endRow, firstCol, endCol); //數據有效性對象 HSSFDataValidation data_validation = new HSSFDataValidation(regions, constraint); sheet.addValidationData(data_validation); return data_validation; }
/** * 設置列寬 * @author David * @param sheet * @param colgroup */ private static void setColumnWidth(HSSFSheet sheet, Element colgroup) { List<Element> cols = colgroup.getChildren("col"); for (int i = 0; i < cols.size(); i++) { Element col = cols.get(i); Attribute width = col.getAttribute("width"); String unit = width.getValue().replaceAll("[0-9,\\.]", "");//截取單位 String value = width.getValue().replaceAll(unit, "");//擦除單位 int v=0; //單位轉化 if(StringUtils.isBlank(unit) || "px".endsWith(unit)){//若是單位爲空或等於px v = Math.round(Float.parseFloat(value) * 37F); }else if ("em".endsWith(unit)){//若是單位爲em v = Math.round(Float.parseFloat(value) * 267.5F); } sheet.setColumnWidth(i, v);//設置第i列寬度爲v } }
完整代碼apache
package com.imooc.excel; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.CellRangeAddressList; import org.jdom.Attribute; import org.jdom.Document; import org.jdom.Element; import org.jdom.input.SAXBuilder; import java.io.File; import java.io.FileOutputStream; import java.util.List; /** * Created by chenld1 on 2015/10/6. */ public class CreateTemplate { /** * 建立模板文件 * @author David * @param args */ public static void main(String[] args) { //獲取解析xml文件路徑 String path = System.getProperty("user.dir") + "/student2.xml"; File file = new File(path); SAXBuilder builder = new SAXBuilder(); try { //解析xml文件 Document parse = builder.build(file); //建立Excel HSSFWorkbook wb = new HSSFWorkbook(); //建立sheet HSSFSheet sheet = wb.createSheet("Sheet0"); //獲取xml文件跟節點 Element root = parse.getRootElement(); //獲取模板名稱 String templateName = root.getAttribute("name").getValue(); int rownum = 0; int column = 0; //設置列寬 Element colgroup = root.getChild("colgroup"); setColumnWidth(sheet,colgroup); //設置標題 Element title = root.getChild("title"); List<Element> trs = title.getChildren("tr"); for (int i = 0; i < trs.size(); i++) { Element tr = trs.get(i); List<Element> tds = tr.getChildren("td"); HSSFRow row = sheet.createRow(rownum); HSSFCellStyle cellStyle = wb.createCellStyle();//建立單元格樣式 cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);//設置單元格對齊方式 for(column = 0;column <tds.size();column ++){ Element td = tds.get(column); HSSFCell cell = row.createCell(column); Attribute rowSpan = td.getAttribute("rowspan"); Attribute colSpan = td.getAttribute("colspan"); Attribute value = td.getAttribute("value"); if(value !=null){ String val = value.getValue(); cell.setCellValue(val); int rspan = rowSpan.getIntValue() - 1;//execel的行以0開頭 int cspan = colSpan.getIntValue() -1; //設置字體 HSSFFont font = wb.createFont(); font.setFontName("仿宋_GB2312"); font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//字體加粗 // font.setFontHeight((short)12); font.setFontHeightInPoints((short)12); cellStyle.setFont(font); cell.setCellStyle(cellStyle); //合併單元格居中 sheet.addMergedRegion(new CellRangeAddress(rspan, rspan, 0, cspan)); } } rownum ++; } //設置表頭 Element thead = root.getChild("thead"); trs = thead.getChildren("tr"); for (int i = 0; i < trs.size(); i++) { Element tr = trs.get(i); HSSFRow row = sheet.createRow(rownum); List<Element> ths = tr.getChildren("th"); for(column = 0;column < ths.size();column++){ Element th = ths.get(column); Attribute valueAttr = th.getAttribute("value"); HSSFCell cell = row.createCell(column); if(valueAttr != null){ String value =valueAttr.getValue(); cell.setCellValue(value); } } rownum++; } //設置數據區域樣式 Element tbody = root.getChild("tbody"); Element tr = tbody.getChild("tr"); int repeat = tr.getAttribute("repeat").getIntValue(); List<Element> tds = tr.getChildren("td"); for (int i = 0; i < repeat; i++) { HSSFRow row = sheet.createRow(rownum); for(column =0 ;column < tds.size();column++){ Element td = tds.get(column); HSSFCell cell = row.createCell(column); setType(wb,cell,td); } rownum++; } //生成Excel導入模板 File tempFile = new File("e:/" + templateName + ".xls"); tempFile.delete(); tempFile.createNewFile(); FileOutputStream stream = FileUtils.openOutputStream(tempFile); wb.write(stream); stream.close(); } catch (Exception e) { e.printStackTrace(); } } /** * 設置單元格數據類型 * @author David * @param wb * @param cell * @param td */ private static void setType(HSSFWorkbook wb, HSSFCell cell, Element td) { Attribute typeAttr = td.getAttribute("type"); String type = typeAttr.getValue(); //HSSFDataformat HSSFDataFormat format = wb.createDataFormat(); HSSFCellStyle cellStyle = wb.createCellStyle(); if("NUMERIC".equalsIgnoreCase(type)){ cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC); Attribute formatAttr = td.getAttribute("format"); String formatValue = formatAttr.getValue(); formatValue = StringUtils.isNotBlank(formatValue)? formatValue : "#,##0.00"; cellStyle.setDataFormat(format.getFormat(formatValue)); }else if("STRING".equalsIgnoreCase(type)){ cell.setCellValue(""); cell.setCellType(HSSFCell.CELL_TYPE_STRING); cellStyle.setDataFormat(format.getFormat("@")); }else if("DATE".equalsIgnoreCase(type)){ cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC); cellStyle.setDataFormat(format.getFormat("yyyy-m-d")); }else if("ENUM".equalsIgnoreCase(type)){ CellRangeAddressList regions = new CellRangeAddressList(cell.getRowIndex(), cell.getRowIndex(), cell.getColumnIndex(), cell.getColumnIndex()); Attribute enumAttr = td.getAttribute("format"); String enumValue = enumAttr.getValue(); //加載下拉列表內容 DVConstraint constraint = DVConstraint.createExplicitListConstraint(enumValue.split(",")); //數據有效性對象 HSSFDataValidation dataValidation = new HSSFDataValidation(regions, constraint); wb.getSheetAt(0).addValidationData(dataValidation); } cell.setCellStyle(cellStyle); } /** * 設置列寬 * @author David * @param sheet * @param colgroup */ private static void setColumnWidth(HSSFSheet sheet, Element colgroup) { List<Element> cols = colgroup.getChildren("col"); for (int i = 0; i < cols.size(); i++) { Element col = cols.get(i); Attribute width = col.getAttribute("width"); String unit = width.getValue().replaceAll("[0-9,\\.]", "");//截取單位 String value = width.getValue().replaceAll(unit, "");//擦除單位 int v=0; //單位轉化 if(StringUtils.isBlank(unit) || "px".endsWith(unit)){//若是單位爲空或等於px v = Math.round(Float.parseFloat(value) * 37F); }else if ("em".endsWith(unit)){//若是單位爲em v = Math.round(Float.parseFloat(value) * 267.5F); } sheet.setColumnWidth(i, v);//設置第i列寬度爲v } } /** * 方法名稱:SetDataValidation * 內容摘要:設置數據有效性 * @param sheet excel sheet內容 * @param textList 下拉列表 * @param firstRow 單元格範圍 * @param firstCol * @param endRow * @param endCol */ private static HSSFDataValidation setDataValidation(HSSFSheet sheet,String[] textList,short firstRow,short firstCol, short endRow, short endCol) { //加載下拉列表內容 DVConstraint constraint = DVConstraint.createExplicitListConstraint(textList); //設置數據有效性加載在哪一個單元格上。 //四個參數分別是:起始行、終止行、起始列、終止列 CellRangeAddressList regions = new CellRangeAddressList(firstRow,endRow, firstCol, endCol); //數據有效性對象 HSSFDataValidation data_validation = new HSSFDataValidation(regions, constraint); sheet.addValidationData(data_validation); return data_validation; } }
百度雲盤外鏈dom