Java根据模板创建excel文件

来源:互联网 发布:淘宝达人淘在哪里看 编辑:程序博客网 时间:2024/05/17 23:00

1.首先导入xml文件,src下建包xml,将student.xml文件放入此文件夹中


[html] view plain copy
  1. <excel id="student" code="student" name="学生信息导入">  
  2.     <colgroup>  
  3.         <col index="A" width='17em'></col>  
  4.         <col index="B" width='17em'></col>  
  5.         <col index="C" width='17em'></col>  
  6.         <col index="D" width='17em'></col>  
  7.         <col index="E" width='17em'></col>  
  8.         <col index="F" width='17em'></col>          
  9.     </colgroup>  
  10.     <title>  
  11.         <tr height="16px">  
  12.             <td rowspan="1" colspan="6" value="学生信息导入" />  
  13.         </tr>  
  14.     </title>  
  15.     <thead>  
  16.         <tr height="16px">  
  17.             <th value="编号" />  
  18.             <th value="姓名" />  
  19.             <th value="年龄" />  
  20.             <th value="性别" />  
  21.             <th value="出生日期" />  
  22.             <th value=" 爱好" />              
  23.         </tr>  
  24.     </thead>  
  25.     <tbody>  
  26.         <tr height="16px" firstrow="2" firstcol="0" repeat="5">  
  27.             <td type="string" isnullable="false" maxlength="30" /><!--用户编号 -->  
  28.             <td type="string" isnullable="false" maxlength="50" /><!--姓名 -->  
  29.             <td type="numeric" format="##0" isnullable="false" /><!--年龄 -->  
  30.             <td type="enum" format="男,女" isnullable="true" /><!--性别 -->  
  31.             <td type="date" isnullable="false" maxlength="30" /><!--出生日期 -->  
  32.             <td type="enum" format="足球,篮球,乒乓球" isnullable="true" /><!--爱好 -->  
  33.         </tr>  
  34.     </tbody>  

2.导入架包

1)commons-lang3-3.1.jar

2)jdom.jar

3)commons-io-2.2.jar

4)poi-3.11-20141221.jar


3.创建测试类

1)sax解析xml文件

[java] view plain copy
  1. //获取解析xml文件路径  
  2.         String path = System.getProperty("user.dir") + "/xml/student.xml";  
  3.         File file = new File(path);  
  4.         SAXBuilder builder = new SAXBuilder();  
  5.         //解析xml文件  
  6.         Document parse = builder.build(file);  


2)创建excel

[java] view plain copy
  1. //创建Excel  
  2.         HSSFWorkbook wb = new HSSFWorkbook();  
  3.         //创建sheet  
  4.         HSSFSheet sheet = wb.createSheet("Sheet0");  


3)从xml文件中取值

[java] view plain copy
  1. //获取xml文件跟节点  
  2.         Element root = parse.getRootElement();  
  3.         //获取模板名称  
  4.         String templateName = root.getAttribute("name").getValue();  

4)设置excel列宽

[java] view plain copy
  1. int rownum = 0;  
  2.         int column = 0;  
  3.         //设置列宽  
  4.         Element colgroup = root.getChild("colgroup");  
  5.         setColumnWidth(sheet,colgroup);  
  6.         此处设置列宽,将其封装成一个方法  
  7.     private static void setColumnWidth(HSSFSheet sheet, Element colgroup) {  
  8.         List<Element> cols = colgroup.getChildren("col");  
  9.         for (int i = 0; i < cols.size(); i++) {  
  10.             Element col = cols.get(i);  
  11.             //获取col的设置  
  12.             Attribute width = col.getAttribute("width");  
  13.             //正则表达式截取字符串,获取xml中列的单位  
  14.             String unit = width.getValue().replaceAll("[0-9,\\.]""");  
  15.             //获取宽度值  
  16.             String value = width.getValue().replaceAll(unit, "");  
  17.             int v=0;  
  18.             //poi宽度转化为excel宽度  
  19.             if(StringUtils.isBlank(unit) || "px".endsWith(unit)){  
  20.                 //空或者px单位的宽度转换为excel宽度  
  21.                 v = Math.round(Float.parseFloat(value) * 37F);  
  22.                 //em单位的宽度转换为excel宽度  
  23.             }else if ("em".endsWith(unit)){  
  24.                 v = Math.round(Float.parseFloat(value) * 267.5F);  
  25.             }  
  26.             sheet.setColumnWidth(i, v);  
  27.         }  
  28.     }  

5)设置标题
[java] view plain copy
  1. Element title = root.getChild("title");  
  2.             List<Element> trs = title.getChildren("tr");  
  3.             for (int i = 0; i < trs.size(); i++) {  
  4.                 Element tr = trs.get(i);  
  5.                 List<Element> tds = tr.getChildren("td");  
  6.                 HSSFRow row = sheet.createRow(rownum);  
  7.                 for(column = 0;column <tds.size();column ++){  
  8.                     Element td = tds.get(column);  
  9.                     //创建单元格  
  10.                     HSSFCell cell = row.createCell(column);  
  11.                     Attribute rowSpan = td.getAttribute("rowspan");  
  12.                     Attribute colSpan = td.getAttribute("colspan");  
  13.                     Attribute value = td.getAttribute("value");  
  14.                     if(value !=){  
  15.                         String val = value.getValue();  
  16.                         cell.setCellValue(val);  
  17.                         int rspan = rowSpan.getIntValue() - 1;  
  18.                         int cspan = colSpan.getIntValue() -1;  
  19.                         //合并单元格居中   (开始行,结束行,开始列,结束列)                         
  20.                         sheet.addMergedRegion(new CellRangeAddress(rspan, rspan, 0, cspan));  
  21.                     }  
  22.                 }  
  23.                 rownum ++;  
  24.             }  

6)设置单元格样式

[java] view plain copy
  1. HSSFCellStyle cellStyle = wb.createCellStyle();  
  2.                 //居中  
  3.                 cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
  4.                 //设置字体  
  5.                         HSSFFont font = wb.createFont();  
  6.                         font.setFontName("仿宋_GB2312");  
  7.                         font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//字体加粗  
  8. //                      font.setFontHeight((short)12);//设置高度  
  9.                         font.setFontHeightInPoints((short)12);  
  10.                         //将字体加入样式中  
  11.                         cellStyle.setFont(font);  
  12.                         //设置单元格样式  
  13.                         cell.setCellStyle(cellStyle);  


7)设置表头

[java] view plain copy
  1. Element thead = root.getChild("thead");  
  2.             trs = thead.getChildren("tr");  
  3.             //循环得到节点信息  
  4.             for (int i = 0; i < trs.size(); i++) {  
  5.                 Element tr = trs.get(i);  
  6.                 //创建excel行  
  7.                 HSSFRow row = sheet.createRow(rownum);  
  8.                 //获取节点信息  
  9.                 List<Element> ths = tr.getChildren("th");  
  10.                 //循环列  
  11.                 for(column = 0;column < ths.size();column++){  
  12.                     //元素  
  13.                     Element th = ths.get(column);  
  14.                     //属性值  
  15.                     Attribute valueAttr = th.getAttribute("value");  
  16.                     HSSFCell cell = row.createCell(column);  
  17.                     if(valueAttr != ){  
  18.                         String value =valueAttr.getValue();  
  19.                         //单元格赋值  
  20.                         cell.setCellValue(value);  
  21.                     }  
  22.                 }  
  23.                 rownum++;  
  24.             }  


8)设置区域样式

[java] view plain copy
  1. //设置数据区域样式  
  2.             Element tbody = root.getChild("tbody");  
  3.             Element tr = tbody.getChild("tr");  
  4.             //repeat:初始化行数  
  5.             int repeat = tr.getAttribute("repeat").getIntValue();  
  6.               
  7.             List<Element> tds = tr.getChildren("td");  
  8.             for (int i = 0; i < repeat; i++) {  
  9.                 HSSFRow row = sheet.createRow(rownum);  
  10.                 for(column =0 ;column < tds.size();column++){  
  11.                     Element td = tds.get(column);  
  12.                     HSSFCell cell = row.createCell(column);  
  13.                     setType(wb,cell,td);  
  14.                 }  
  15.                 rownum++;  
  16.             }  
  17.   
  18.   
  19.             设置属性及样式封装的方法  
  20.     private static void setType(HSSFWorkbook wb, HSSFCell cell, Element td) {  
  21.         Attribute typeAttr = td.getAttribute("type");  
  22.         String type = typeAttr.getValue();  
  23.         HSSFDataFormat format = wb.createDataFormat();  
  24.         HSSFCellStyle cellStyle = wb.createCellStyle();  
  25.         //判断节点类型  
  26.         //数字类型  
  27.         if("NUMERIC".equalsIgnoreCase(type)){  
  28.             cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);  
  29.             Attribute formatAttr = td.getAttribute("format");  
  30.             String formatValue = formatAttr.getValue();  
  31.             //如果不为空赋值,为空赋初始值  
  32.             formatValue = StringUtils.isNotBlank(formatValue)? formatValue : "#,##0.00";  
  33.             cellStyle.setDataFormat(format.getFormat(formatValue));  
  34.         //字符串类型  
  35.         }else if("STRING".equalsIgnoreCase(type)){  
  36.             cell.setCellValue("");  
  37.             cell.setCellType(HSSFCell.CELL_TYPE_STRING);  
  38.             //格式化 @表示文本  
  39.             cellStyle.setDataFormat(format.getFormat("@"));  
  40.         //日期类型  
  41.         }else if("DATE".equalsIgnoreCase(type)){  
  42.             cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);  
  43.             cellStyle.setDataFormat(format.getFormat("yyyy-m-d"));  
  44.         //枚举类型  
  45.         }else if("ENUM".equalsIgnoreCase(type)){  
  46.             CellRangeAddressList regions =   
  47.             //方法参数(开始行,结束行,开始列,结束列)  
  48.                 new CellRangeAddressList(cell.getRowIndex(), cell.getRowIndex(),   
  49.                         cell.getColumnIndex(), cell.getColumnIndex());  
  50.             Attribute enumAttr = td.getAttribute("format");  
  51.             String enumValue = enumAttr.getValue();  
  52.             //加载下拉列表内容  
  53.             DVConstraint constraint =   
  54.             //方法参数(下拉列表数组)  
  55.                 DVConstraint.createExplicitListConstraint(enumValue.split(","));  
  56.             //数据有效性对象  
  57.             HSSFDataValidation dataValidation = new HSSFDataValidation(regions, constraint);  
  58.             wb.getSheetAt(0).addValidationData(dataValidation);  
  59.         }  
  60.         cell.setCellStyle(cellStyle);  
  61.     }  


9)将文件保存到本地

[java] view plain copy
  1. File tempFile = new File("e:/" + templateName + ".xls");  
  2.             tempFile.delete();  
  3.             tempFile.createNewFile();  
  4.             FileOutputStream stream = FileUtils.openOutputStream(tempFile);  
  5.             wb.write(stream);  
  6.             stream.close();  


4.在E盘将找到生成的excel文件,其中年龄初始值为0(xml中赋初始值为0),出生年月1900-1-0(架包默认),性别和爱好为下拉列表