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打印.这样在我们实 ...
随机推荐
- 贪心 --- Y2K Accounting Bug
Y2K Accounting Bug Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 9691 Accepted: 483 ...
- 使用springboot mybatis 查询时实体类中的驼峰字段值为null
看到返回结果以后主要分析了一下情况: 实体类的get.set方法确实 mapper.xml文件中的resultMap.resultType等原因导致 数据库中数据存在问题 经过检查与验证发现以上都不存 ...
- Scala 函数基础入门
函数的定义与调用 在Scala中定义函数时,需要定义函数的函数名.参数.函数体. 我们的第一个函数如下所示: def sayHello(name: String, age: Int) = { if ( ...
- SetWindowLong函数GetWindowLong函数
这两个函数具体应用如下:SetWindowLong函数GetWindowLong函数 Delphi窗口化游戏 var Thwnd:HWND;//声明变量 句柄变量 devmodel1:DEVMODE; ...
- 【翻译】nginx初学者指南
nginx初学者指南 本文翻译自nginx官方网站:http://nginx.org/en/docs/beginners_guide.html#control 该指南会对nginx做一个简要的介绍,同 ...
- C# Newtonsoft.Json 你必须知道的一些用法
最近在做接口开发,对方团队开发了一个Web API 的接口,传输数据的格式是 JSON.当时看到这个东西,感觉很简单,也没想什么,没用多久就完成了我的功能,我完成的功能很简单,就是获取数据,然后把数据 ...
- js/jquery键盘事件及keycode大全
js/jquery的键盘事件分为keypress.keydown和keyup事件 一.键盘事件 1.keydown()事件当按钮被按下时,发生 keydown 事件. 2.keypress()事件ke ...
- 配置 Mac Chrome Inspect
安装libimobiledevice : Could not connect to lockdownd. Exiting. 报错解决 brew uninstall --ignore-depende ...
- java中创建线程的3种方法
1.继承Thread类优点:可以直接使用Thread类中的方法,代码比较简单.缺点:继承Thread类之后不能继承其他类. 2.实现Runable接口优点:实现接口,比影响继承其他类或实现接口.缺点: ...
- Django:RestFramework之-------权限
4.restframework-权限 4.1权限: 权限在单个视图应用. class MyPermission(object): """认证类""&q ...