本文主要叙述定制导入模板——利用XML解析技术,确定模板样式。

1.确定模板列

2.定义标题(合并单元格)

3.定义列名

4.定义数据区域单元格样式

引入jar包:

一、预期格式类型

二、XML模板格式

 <?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>
<tile>
<tr height="16px">
<td rowspan="1" colspan="6" value="学生信息导入"></td>
</tr>
</tile>
<thead>
<tr height="16px">
<th value="编号"></th>
<th value="姓名"></th>
<th value="年龄"></th>
<th value="性别"></th>
<th value="出生日期"></th>
<th value="爱好"></th>
</tr>
</thead>
<tbody>
<tr height="16px" firstrow="2" firstcol="0" repeat="5" >
<td type="string" isnullable="false" maxlength="30"></td><!-- 用户编号 -->
<td type="string" isnullable="false" maxlength="50"></td><!-- 姓名 -->
<td type="numeric" format="##0" isnullable="false"></td><!-- 年龄 -->
<td type="enum" format="男,女" isnullable="true"></td><!-- 性别 -->
<td type="date" isnullable="false" maxlength="30"></td><!-- 出生日期 -->
<td type="enum" format="足球,篮球,兵乓球" isnullable="true" ></td><!-- 爱好 -->
</tr>
</tbody>
</excel>

二、Java解析XML模板

 import java.io.File;
import java.io.FileOutputStream;
import java.util.List; import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.DVConstraint;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFDataValidation;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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; public class CreateTemplate { /**
* 创建模板文件
*
* @author
* @param args
*/
public static void main(String[] args) {
// 获取解析XML路径
String path = System.getProperty("user.dir") + "/bin/Student.xml";
File file = new File(path);
SAXBuilder builder = new SAXBuilder();
try {
Document parse = builder.build(file);
// 创建工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.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 = workbook.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;
int cspan = colSpan.getIntValue() - 1;
// 设置字体
HSSFFont font = workbook.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(workbook, cell, td);
}
rownum++;
}
// 生成Excel导入模板
File tempFile = new File("e:/" + templateName + ".xls");
tempFile.delete();
tempFile.createNewFile();
FileOutputStream stream = FileUtils.openOutputStream(tempFile);
workbook.write(stream);
stream.close(); } catch (Exception e) {
e.printStackTrace();
} } /**
* 设置列宽
*
* @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)) {
v = Math.round(Float.parseFloat(value) * 37F);
} else if ("em".endsWith(unit)) {
v = Math.round(Float.parseFloat(value) * 267.5F);
}
sheet.setColumnWidth(i, v);
}
} /**
* 设置单元格样式
*
* @param workbook
* @param cell
* @param td
*/
private static void setType(HSSFWorkbook workbook, HSSFCell cell, Element td) {
// TODO Auto-generated method stub
Attribute typeAttr = td.getAttribute("type");
String type = typeAttr.getValue();
HSSFDataFormat format = workbook.createDataFormat();
HSSFCellStyle cellStyle = workbook.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);
workbook.getSheetAt(0).addValidationData(dataValidation);
}
cell.setCellStyle(cellStyle);
} }

二、Java解析XML模板,实现效果

Java Excel 导入导出(二)的更多相关文章

  1. JAVA Excel导入导出

    --------------------------------------------方式一(新)-------------------------------------------------- ...

  2. Java Excel 导入导出(一)

    本文主要描述通过java实现Excel导入导出 一.读写Excel三种常用方式 1.JXL——Java Excel开放源码项目:读取,创建,更新 2.POI——Apache POI ,提供API给Ja ...

  3. Java Excel导入导出(实战)

    一.批量导入(将excel文件转成list) 1. 前台代码逻辑 1)首先在html页面加入下面的代码(可以忽略界面的样式) <label for="uploadFile" ...

  4. java Excel导入导出工具类

    本文章,导入导出依赖提前定义好的模板 package com.shareworx.yjwy.utils; import java.io.File; import java.io.FileInputSt ...

  5. Java——excel导入导出demo

    1. java导入 package xx; import org.apache.poi.hssf.usermodel.HSSFCell;import org.apache.poi.hssf.userm ...

  6. java简易excel导入导出工具(封装POI)

    Octopus 如何导入excel 如何导出excel github项目地址 Octopus Octopus 是一个简单的java excel导入导出工具. 如何导入excel 下面是一个excel文 ...

  7. java jxl excel 导入导出的 总结(建立超链接,以及目录sheet的索引)

    最近项目要一个批量导出功能,而且要生成一个单独的sheet页,最后后面所有sheet的索引,并且可以点击进入连接.网上搜索了一下,找到一个方法,同时把相关的excel导入导出操作记录一下!以便以后使用 ...

  8. Java之POI的excel导入导出

    一.Apache POI是一种流行的API,它允许程序员使用Java程序创建,修改和显示MS Office文件.这由Apache软件基金会开发使用Java分布式设计或修改Microsoft Offic ...

  9. Java中导入导出Excel -- POI技术

    一.介绍: 当前B/S模式已成为应用开发的主流,而在企业办公系统中,常常有客户这样子要求:你要把我们的报表直接用Excel打开(电信系统.银行系统).或者是:我们已经习惯用Excel打印.这样在我们实 ...

随机推荐

  1. mysql explain亲测

    mysql explain亲测 1 where后面字段加索引:数据库类型如果是字符串类型 查询where的时候必须要用 字符串 类型必须一致 否则不用索引 type还是会是all的 ps:如果wher ...

  2. 注解@Slf4j的使用

    注解@Slf4j的使用 声明:如果不想每次都写private  final Logger logger = LoggerFactory.getLogger(当前类名.class); 可以用注解@Slf ...

  3. 关于C语言指针的讨论

    C语言指针的讨论 1.指整的概念辨析 2.指针与一维数组 3.指针与二维数组 4.指针与动态数组 5.指针数组 6. 指整与函数,形参,返回值 先熟悉一下概念,使劲把他们记下了 变量定义 类型表示 含 ...

  4. Linux中常用命令pipe

    大多数linux命令处理数据后都会输出到标准输出,但是如果数据要经过系列列的步骤处理后,才是需要的数据个数,这种需求就需要管道来帮助完成. 管道命令使用"|"作为界定符,将界定符前 ...

  5. IIS 7.5绑定中文域名转码启动站点报“值不在预期的范围内”

    问题现象 IIS 7.5在绑定中文域名转码后,启动站点会出现[值不在预期的范围内]: 解决方案 此问题是由于中文域名绑定错误导致的,IIS 7.5针对中文域名会自动转换为punycode码,所以不需要 ...

  6. 【转载】socket通信-C#实现tcp收发字符串文本数据

    在日常碰到的项目中,有些场景需要发送文本数据,也就是字符串,比如简单的聊天文字,JSON字符串等场景.那么如何如何使用SharpSocket来收发此类数据呢?其中要掌握的关键点是什么呢? 点击查看原博 ...

  7. 2019 东方网java面试笔试题 (含面试题解析)

      本人5年开发经验.18年年底开始跑路找工作,在互联网寒冬下成功拿到阿里巴巴.今日头条.东方网等公司offer,岗位是Java后端开发,因为发展原因最终选择去了东方网,入职一年时间了,也成为了面试官 ...

  8. js中 !==和 !=的区别是什么

    1.比较结果上的区别 !=返回同类型值比较结果. !== 不同类型不比较,且无结果,同类型才比较. 2.比较过程上的区别 != 比较时,若类型不同,会偿试转换类型. !== 只有相同类型才会比较. 3 ...

  9. 浅谈Object.prototype.toString.call()方法

    在JavaScript里使用typeof判断数据类型,只能区分基本类型,即:number.string.undefined.boolean.object.对于null.array.function.o ...

  10. YUV详解

    YUV格式解析2 又确认了一下H264的视频格式——H264支持4:2:0的连续或隔行视频的编码和解码   YUV(亦称YCrCb)是被欧洲电视系统所采用的一种颜色编码方法(属于PAL).YUV主要用 ...