Java Excel 导入导出(二)
本文主要叙述定制导入模板——利用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 导入导出(二)的更多相关文章
- JAVA Excel导入导出
--------------------------------------------方式一(新)-------------------------------------------------- ...
- Java Excel 导入导出(一)
本文主要描述通过java实现Excel导入导出 一.读写Excel三种常用方式 1.JXL——Java Excel开放源码项目:读取,创建,更新 2.POI——Apache POI ,提供API给Ja ...
- Java Excel导入导出(实战)
一.批量导入(将excel文件转成list) 1. 前台代码逻辑 1)首先在html页面加入下面的代码(可以忽略界面的样式) <label for="uploadFile" ...
- java Excel导入导出工具类
本文章,导入导出依赖提前定义好的模板 package com.shareworx.yjwy.utils; import java.io.File; import java.io.FileInputSt ...
- Java——excel导入导出demo
1. java导入 package xx; import org.apache.poi.hssf.usermodel.HSSFCell;import org.apache.poi.hssf.userm ...
- java简易excel导入导出工具(封装POI)
Octopus 如何导入excel 如何导出excel github项目地址 Octopus Octopus 是一个简单的java excel导入导出工具. 如何导入excel 下面是一个excel文 ...
- java jxl excel 导入导出的 总结(建立超链接,以及目录sheet的索引)
最近项目要一个批量导出功能,而且要生成一个单独的sheet页,最后后面所有sheet的索引,并且可以点击进入连接.网上搜索了一下,找到一个方法,同时把相关的excel导入导出操作记录一下!以便以后使用 ...
- Java之POI的excel导入导出
一.Apache POI是一种流行的API,它允许程序员使用Java程序创建,修改和显示MS Office文件.这由Apache软件基金会开发使用Java分布式设计或修改Microsoft Offic ...
- Java中导入导出Excel -- POI技术
一.介绍: 当前B/S模式已成为应用开发的主流,而在企业办公系统中,常常有客户这样子要求:你要把我们的报表直接用Excel打开(电信系统.银行系统).或者是:我们已经习惯用Excel打印.这样在我们实 ...
随机推荐
- Java练习——扑克牌发牌器
Java练习——扑克牌发牌器声明:学习自其他博主,感谢分享,这里自己也写了一下.实现思路 - 构建一张扑克牌 - 构建一套扑克牌 - 测试 构建一张扑克牌 /** * @author 冬冬 * 定义 ...
- Java随堂笔记二
变量常量类型转换和命名规范 变量和常量 static double salary = 2500; //属性:变量 //变量作用域: //类变量 static // 局部变量 ...
- MATBLAB学习笔记----基础绘图
整理自台大生机系郭彦甫.MATLAB系列教程,吐血推荐看这个视频,非计算机专业也能看懂,全程干货 MATLAB图形来自于“数据”,MATLAB不能理解函数. MATLAB绘图原理: 1.在特定范围生成 ...
- Java的常用API
Object类 1.toString方法在我们直接使用输出语句输出对象的时候,其实通过该对象调用了其toString()方法. 2.equals方法方法摘要:类默认继承了Object类,所以可以使用O ...
- kafka broker Leader -1引起spark Streaming不能消费的故障解决方法
一.问题描述:Kafka生产集群中有一台机器cdh-003由于物理故障原因挂掉了,并且系统起不来了,使得线上的spark Streaming实时任务不能正常消费,重启实时任务都不行.查看kafka t ...
- 用Java访问带有Kerberos认证的HBase
程序代码实例如下: package com.hbasedemo; import java.io.IOException; import org.apache.hadoop.conf.Config ...
- windows2008 开启SNMP服务
现在很多企业和公司管理服务器时都是通过网络监控软件对服务器的状态进行监控,在监控的时候大多是通过SNMP协议(简单网络管理协议)进行的,那么在我们的服务器端就需要开启此项服务,并进行简单的设置. 以下 ...
- swiper4基础
这段时间在公司实习做前端,感觉前端没学习到很多前端框架,接口那些都是写好的,只需要调用就好,感觉没什么好记的,唯一觉得有必要记的就是swiper轮播了,在前端做网站的时候经常用到swiper做公告,图 ...
- Ubuntu系统下容器化部署gitlab
容器化部署gitlab 获取镜像文件 1. 下载镜像文件 docker pull beginor/gitlab-ce:-ce. 2. 创建GitLab 的配置 (etc) . 日志 (log) .数据 ...
- Ubuntu 挂载硬盘命令介绍
版权声明:本文为博主原创文章,欢迎转载与采用. https://blog.csdn.net/HinstenyHisoka/article/details/71055656 新升级了Ubuntu 从16 ...