Java根据模板创建excel文件
来源:互联网 发布:淘宝达人淘在哪里看 编辑:程序博客网 时间:2024/05/17 23:00
1.首先导入xml文件,src下建包xml,将student.xml文件放入此文件夹中
[html] view plain copy
- <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>
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
- //获取解析xml文件路径
- String path = System.getProperty("user.dir") + "/xml/student.xml";
- File file = new File(path);
- SAXBuilder builder = new SAXBuilder();
- //解析xml文件
- Document parse = builder.build(file);
2)创建excel
[java] view plain copy
- //创建Excel
- HSSFWorkbook wb = new HSSFWorkbook();
- //创建sheet
- HSSFSheet sheet = wb.createSheet("Sheet0");
3)从xml文件中取值
[java] view plain copy
- //获取xml文件跟节点
- Element root = parse.getRootElement();
- //获取模板名称
- String templateName = root.getAttribute("name").getValue();
4)设置excel列宽
[java] view plain copy
- int rownum = 0;
- int column = 0;
- //设置列宽
- Element colgroup = root.getChild("colgroup");
- setColumnWidth(sheet,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);
- //获取col的设置
- Attribute width = col.getAttribute("width");
- //正则表达式截取字符串,获取xml中列的单位
- String unit = width.getValue().replaceAll("[0-9,\\.]", "");
- //获取宽度值
- String value = width.getValue().replaceAll(unit, "");
- int v=0;
- //poi宽度转化为excel宽度
- if(StringUtils.isBlank(unit) || "px".endsWith(unit)){
- //空或者px单位的宽度转换为excel宽度
- v = Math.round(Float.parseFloat(value) * 37F);
- //em单位的宽度转换为excel宽度
- }else if ("em".endsWith(unit)){
- v = Math.round(Float.parseFloat(value) * 267.5F);
- }
- sheet.setColumnWidth(i, v);
- }
- }
5)设置标题
[java] view plain copy
- 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);
- 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 !=){
- String val = value.getValue();
- cell.setCellValue(val);
- int rspan = rowSpan.getIntValue() - 1;
- int cspan = colSpan.getIntValue() -1;
- //合并单元格居中 (开始行,结束行,开始列,结束列)
- sheet.addMergedRegion(new CellRangeAddress(rspan, rspan, 0, cspan));
- }
- }
- rownum ++;
- }
6)设置单元格样式
[java] view plain copy
- HSSFCellStyle cellStyle = wb.createCellStyle();
- //居中
- cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
- //设置字体
- 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);
7)设置表头
[java] view plain copy
- Element thead = root.getChild("thead");
- trs = thead.getChildren("tr");
- //循环得到节点信息
- for (int i = 0; i < trs.size(); i++) {
- Element tr = trs.get(i);
- //创建excel行
- 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 != ){
- String value =valueAttr.getValue();
- //单元格赋值
- cell.setCellValue(value);
- }
- }
- rownum++;
- }
8)设置区域样式
[java] view plain copy
- //设置数据区域样式
- Element tbody = root.getChild("tbody");
- Element tr = tbody.getChild("tr");
- //repeat:初始化行数
- 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++;
- }
- 设置属性及样式封装的方法
- 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);
- }
9)将文件保存到本地
[java] view plain copy
- File tempFile = new File("e:/" + templateName + ".xls");
- tempFile.delete();
- tempFile.createNewFile();
- FileOutputStream stream = FileUtils.openOutputStream(tempFile);
- wb.write(stream);
- stream.close();
4.在E盘将找到生成的excel文件,其中年龄初始值为0(xml中赋初始值为0),出生年月1900-1-0(架包默认),性别和爱好为下拉列表
阅读全文
0 0
- Java根据模板创建excel文件
- Java根据模板创建excel文件
- java根据模板生成Excel文件
- Java根据html模板创建 html文件
- delphi 根据EXCEL模板创建
- Java根据模板生成excel并下载
- 根据Excel文件创建数据集
- NPOI根据Excel模板生成原生的Excel文件实例
- java创建Excel文件
- java-导入到Excel_POI根据模板(excel表头)导出excel
- java 根据excel模板格式导出指定格式的excel
- 根据模板生成Excel
- excel根据模板导出
- 根据模板导出excel
- 根据Excel模板生成Excel
- 根据excel模板导出excel
- poi根据excel模板文件六步完成替换导出
- java根据模板生成word文件
- Git开源三方库
- 深入了解ThreadLocal
- Intellij IDEA的使用
- **决策树基础以及Python代码实现**
- vue 动态加载图片src的解决办法
- Java根据模板创建excel文件
- 2017-12-12战斗有限状态机FSM -第三天
- Javascript几种跨域方式总结
- 设计模式知识连载(6)---继承_2:创建即继承-构造函数继承
- 是什么诱发了身体炎症
- Python基础‘姿势’7
- openssl 加密文件的完整实现代码
- PHP RSA 算法生成公钥和私钥
- websocket入门案例