本文主要叙述定制导入模板——利用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. Visual Studio 重命名项目名

    1. 打开VS Studio,重命名项目 2. 重命名对应的项目文件夹,并重命名项目文件夹下的这两个文件名: 3. 用记事本打开解决方案,修改对应的项目名字和路径 未完 ...... 点击访问原文(进 ...

  2. Scala Type Parameters 2

    类型关系 Scala 支持在泛型类上使用型变注释,用来表示复杂类型.组合类型的子类型关系间的相关性 协变 +T,变化方向相同,通常用在生产 假设 A extends T, 对于 Clazz[+T],则 ...

  3. NodeJS 使用内容以及模拟一个接口

    1.结合上一篇 安装完Nodejs之后 通过手动创建一个完整的NodeJs项目 2.https://www.jianshu.com/p/7b0a5d4491ba 创建一个完整的项目之后 3.下面是一个 ...

  4. TCMalloc - 细节

    1,释放速度控制 在将一个Span删除掉的时候,会优先将它加入到normal队列中,这之后会尝试从normal队列中释放一部分同样大小的内存给系统. 释放内存给系统的时候,tcmalloc使用了一个延 ...

  5. Dubbo面试踩坑

    1.Dubbo支持哪些协议,每种协议的应用场景,优缺点? dubbo: 单一长连接和NIO异步通讯,适合大并发小数据量的服务调用,以及消费者远大于提供者.传输协议TCP,异步,Hessian序列化: ...

  6. SQL Server的唯一键和唯一索引会将空值(NULL)也算作重复值

    我们先在SQL Server数据库中,建立一张Students表: CREATE TABLE [dbo].[Students]( ,) NOT NULL, ) NULL, ) NULL, [Age] ...

  7. VS 发布MVC网站缺少视图

    mvc项目发布之后会有一些视图文件缺少,不包含在发布文件中,虽然可以直接从项目文件中直接拷贝过来,但还是想知道是什么原因,发布文件好像没有找到哪里有设置这个的地方 把生成操作:无-改成内容即可 原文

  8. ssh in depth

    前两天写了一篇关于ssh的相对比较入门的文章,重点介绍了ssh在免密登录场景下的应用. 本文试图对ssh更高级的话题做一下探讨,重点探讨一下ssh tunneling https://www.ssh. ...

  9. javascript原型深入解析2--Object和Function,先有鸡先有蛋

    1.提出两个问题: Js 的prototype和__proto__ 是咋回事? 先有function 还是先有object? 2.引用<JavaScript权威指南>的一段描述: 每个JS ...

  10. RabbitMQ的简单模式快速入门与超时异常的处理方法

    本文适合JAVA新人,想了解RabbitMQ又不想去看官网文档的人(英语水看的头疼(◎﹏◎),但建议有能力还是去看官网文档). 消息队列MQ(一) MQ全称为Message Queue,消息队列是应用 ...