JAVA生成EXCEL模板
JAVA生成excel模板,支持
1、必填字段前加 红色 *
2、定义可选值下拉列表 valList
3、定义名称并通过名称设置可选值 refName(名称在sheet2,sheet2自动隐藏)
4、支持设置多字段联动 indirectTitle
5、自定义隐藏列,自定义列宽,自定义标题行高度 效果如图:
代码如下:
1、引入依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
2、ExcelTemp.java
package com.excel; import com.lix.common.StringUtil;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.*; import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional; /**
* @author svice
* @date 2020/3/12 16:38
*/
public class ExcelTemp { private final int EXCEL_MAX_LINE_NUM = 1000000; private int titleHeight = 0; private List<ExcelTempName> names = new ArrayList<>(); private List<ExcelTempField> fields = new ArrayList<>(); public List<ExcelTempName> getNames() {
return names;
} public List<ExcelTempField> getFields() {
return fields;
} public void setTitleHeight(int titleHeight) throws Exception {
if (titleHeight > 1000) {
throw new Exception("titleHeight不能超过1000");
} else {
this.titleHeight = titleHeight;
}
} public void save(String fileName) throws Exception {
if (fields.size() == 0) {
throw new Exception("字段列表为空");
} XSSFWorkbook workBook = new XSSFWorkbook();
XSSFSheet sheet1 = workBook.createSheet("sheet1");
XSSFRow row0 = sheet1.createRow(0); if (titleHeight > 0) {
row0.setHeight((short) (titleHeight * 20));
} XSSFCellStyle cellStyle = workBook.createCellStyle();
DataFormat format = workBook.createDataFormat();
// 单元格文本格式
cellStyle.setDataFormat(format.getFormat("@"));
cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
cellStyle.setBorderTop((short) 1);
cellStyle.setBorderRight((short) 1);
cellStyle.setBorderBottom((short) 1);
cellStyle.setBorderLeft((short) 1);
// 垂直居中
cellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
// 水平居中
cellStyle.setAlignment(HorizontalAlignment.CENTER); Font fontRed = workBook.createFont();
fontRed.setColor(IndexedColors.RED.getIndex()); Font fontBlack = workBook.createFont();
fontBlack.setColor(IndexedColors.BLACK.getIndex()); for (int colIndex = 0; colIndex < fields.size(); colIndex++) {
ExcelTempField field = fields.get(colIndex);
XSSFCell cell = row0.createCell(colIndex);
cell.setCellStyle(cellStyle); if (field.isHidden()) {
sheet1.setColumnWidth(colIndex, 0);
} else if (field.getWidth() > 0) {
sheet1.setColumnWidth(colIndex, field.getWidth() * 256);
} // 标题文本
if (field.isRequire()) {
XSSFRichTextString richTextString = new XSSFRichTextString("*" + field.getTitle());
richTextString.applyFont(0, 1, fontRed);
richTextString.applyFont(1, field.getTitle().length(), fontBlack);
cell.setCellValue(richTextString);
} else {
cell.setCellValue(field.getTitle());
} // 设置数据有效性下拉列表
if (field.getValList().size() > 0) {
CellRangeAddressList addressList = new CellRangeAddressList(1, EXCEL_MAX_LINE_NUM, colIndex, colIndex);
String[] values = field.getValList().toArray(new String[]{});
XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet1);
XSSFDataValidationConstraint col2 = (XSSFDataValidationConstraint) dvHelper.createExplicitListConstraint(values);
XSSFDataValidation dv2 = (XSSFDataValidation) dvHelper.createValidation(col2, addressList);
sheet1.addValidationData(dv2);
} else if (StringUtil.isNotEmpty(field.getRefName())) {
if (this.names.stream().anyMatch(n -> n.getName().equals(field.getRefName()))) {
XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet1);
DataValidationConstraint dvc3 = dvHelper.createFormulaListConstraint(field.getRefName());
CellRangeAddressList col3 = new CellRangeAddressList(1, EXCEL_MAX_LINE_NUM, colIndex, colIndex);
XSSFDataValidation dv3 = (XSSFDataValidation) dvHelper.createValidation(dvc3, col3);
sheet1.addValidationData(dv3);
} else {
throw new Exception("名称:" + field.getRefName() + "无效");
}
} else if (StringUtil.isNotEmpty(field.getIndirectTitle())) {
List<String> fieldNames = new ArrayList<>();
for (ExcelTempField excelTempField : this.fields) {
fieldNames.add(excelTempField.getTitle());
}
int indirectColIndex = fieldNames.indexOf(field.getIndirectTitle());
if (indirectColIndex != -1) {
String indirectColName = ColNameUtil.getColName(indirectColIndex);
XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet1);
CellRangeAddressList col4 = new CellRangeAddressList(1, EXCEL_MAX_LINE_NUM, colIndex, colIndex);
DataValidationConstraint dvc4 = dvHelper.createFormulaListConstraint("INDIRECT($" + indirectColName + "2)");
XSSFDataValidation dv4 = (XSSFDataValidation) dvHelper.createValidation(dvc4, col4);
sheet1.addValidationData(dv4);
} else {
throw new Exception("列名称:" + field.getIndirectTitle() + "无效");
}
} } if (names.size() > 0) {
XSSFSheet sheet2 = workBook.createSheet("sheet2");
workBook.setSheetHidden(1, true);
for (int colIndex = 0; colIndex < names.size(); colIndex++) {
ExcelTempName excelName = names.get(colIndex);
String title = excelName.getName();
List<String> valList = excelName.getValList(); XSSFRow titleRow = colIndex == 0 ? sheet2.createRow(0) : sheet2.getRow(0);
XSSFCell nameTitle = Optional.ofNullable(titleRow.getCell(colIndex)).orElse(titleRow.createCell(colIndex));
nameTitle.setCellValue(title);
nameTitle.setCellStyle(cellStyle);
String colName = ColNameUtil.getColName(colIndex);
for (int i = 0; i < valList.size(); i++) {
String val = valList.get(i);
int rowNum = i + 1;
XSSFRow row = sheet2.getRow(rowNum);
if (null == row) {
row = sheet2.createRow(rowNum);
}
row.createCell(colIndex).setCellValue(val);
}
XSSFName dicRangea = workBook.createName();
dicRangea.setRefersToFormula("sheet2!$" + colName + "$2:$" + colName + "$" + (valList.size() + 1));
dicRangea.setNameName(title);
}
} File file = new File(fileName);
if (!file.exists()) {
boolean newFile = file.createNewFile();
}
OutputStream os = new FileOutputStream(file);
workBook.write(os);
os.close();
} public static void main(String[] args) throws Exception {
ExcelTemp excelTemp = new ExcelTemp();
excelTemp.setTitleHeight(50); ExcelTempField col1 = new ExcelTempField("姓名");
col1.setRequire(true);
excelTemp.getFields().add(col1); ExcelTempField col2 = new ExcelTempField("性别");
col2.setRequire(true);
col2.setValList(Arrays.asList("男", "女"));
excelTemp.getFields().add(col2); ExcelTempField col3 = new ExcelTempField("服装");
col3.setIndirectTitle("性别");
excelTemp.getFields().add(col3); ExcelTempField col4 = new ExcelTempField("年龄段");
col4.setRefName("年龄段");
excelTemp.getFields().add(col4); ExcelTempField col5 = new ExcelTempField("隐藏列");
col5.setHidden(true);
excelTemp.getFields().add(col5); ExcelTempField col6 = new ExcelTempField("宽度80");
col6.setWidth(80);
excelTemp.getFields().add(col6); ExcelTempName name1 = new ExcelTempName();
name1.setName("男");
name1.getValList().add("男装一号");
name1.getValList().add("男装二号");
name1.getValList().add("男装三号");
excelTemp.getNames().add(name1); ExcelTempName name2 = new ExcelTempName();
name2.setName("女");
name2.getValList().add("女装一号");
name2.getValList().add("女装二号");
name2.getValList().add("女装三号");
name2.getValList().add("女装四号");
name2.getValList().add("女装五号");
excelTemp.getNames().add(name2); ExcelTempName name3 = new ExcelTempName();
name3.setName("年龄段");
name3.getValList().add("幼年");
name3.getValList().add("童年");
name3.getValList().add("青年");
name3.getValList().add("中年");
name3.getValList().add("老年");
excelTemp.getNames().add(name3); excelTemp.save("D://temp/excel_temp_test_" + System.currentTimeMillis() + ".xlsx");
}
}
3、ExcelTempName.java
package com.excel; import java.util.ArrayList;
import java.util.List; /**
* @author svice
* @date 2020/3/12 16:38
*/
public class ExcelTempName { private String name; private List<String> valList = new ArrayList<>(); public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public List<String> getValList() {
return valList;
} public void setValList(List<String> valList) {
this.valList = valList;
}
}
4、ExcelTempField .java
package com.excel; import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; /**
* @author svice
* @date 2020/3/12 16:38
*/
public class ExcelTempField { private String title; private boolean require = false; private List<String> valList = new ArrayList<>(); private String refName; private String indirectTitle; private int width; private boolean hidden = false; public ExcelTempField(String title) {
this.title = title;
} public String getTitle() {
return title;
} public void setTitle(String title) {
this.title = title;
} public boolean isRequire() {
return require;
} public void setRequire(boolean require) {
this.require = require;
} public List<String> getValList() {
return valList;
} public void setValList(List<String> valList) {
this.valList = valList;
} public String getRefName() {
return refName;
} public void setRefName(String refName) {
this.refName = refName;
} public String getIndirectTitle() {
return indirectTitle;
} public void setIndirectTitle(String indirectTitle) {
this.indirectTitle = indirectTitle;
} public int getWidth() {
return width;
} public void setWidth(int width) {
this.width = width;
} public boolean isHidden() {
return hidden;
} public void setHidden(boolean hidden) {
this.hidden = hidden;
}
}
5、ColNameUtil.java
package com.excel; /**
* @author svice
* @date 2020/3/13 0:03
*/
public class ColNameUtil {
public static String getColName(int colIndex) throws Exception {
switch (colIndex) {
case 0:
return "A";
case 1:
return "B";
case 2:
return "C";
case 3:
return "D";
case 4:
return "E";
case 5:
return "F";
case 6:
return "G";
case 7:
return "H";
case 8:
return "I";
case 9:
return "J";
case 10:
return "K";
case 11:
return "L";
case 12:
return "M";
case 13:
return "N";
case 14:
return "O";
case 15:
return "P";
case 16:
return "Q";
case 17:
return "R";
case 18:
return "S";
case 19:
return "T";
case 20:
return "U";
case 21:
return "V";
case 22:
return "W";
case 23:
return "X";
case 24:
return "Y";
case 25:
return "Z";
case 26:
return "AA";
case 27:
return "AB";
case 28:
return "AC";
case 29:
return "AD";
case 30:
return "AE";
case 31:
return "AF";
case 32:
return "AG";
case 33:
return "AH";
case 34:
return "AI";
case 35:
return "AJ";
case 36:
return "AK";
case 37:
return "AL";
case 38:
return "AM";
case 39:
return "AN";
case 40:
return "AO";
case 41:
return "AP";
case 42:
return "AQ";
case 43:
return "AR";
case 44:
return "AS";
case 45:
return "AT";
case 46:
return "AU";
case 47:
return "AV";
case 48:
return "AW";
case 49:
return "AX";
case 50:
return "AY";
case 51:
return "AZ";
case 52:
return "BA";
case 53:
return "BB";
case 54:
return "BC";
case 55:
return "BD";
case 56:
return "BE";
case 57:
return "BF";
case 58:
return "BG";
case 59:
return "BH";
case 60:
return "BI";
case 61:
return "BJ";
case 62:
return "BK";
case 63:
return "BL";
case 64:
return "BM";
case 65:
return "BN";
case 66:
return "BO";
case 67:
return "BP";
case 68:
return "BQ";
case 69:
return "BR";
case 70:
return "BS";
case 71:
return "BT";
case 72:
return "BU";
case 73:
return "BV";
case 74:
return "BW";
case 75:
return "BX";
case 76:
return "BY";
case 77:
return "BZ";
case 78:
return "CA";
case 79:
return "CB";
case 80:
return "CC";
case 81:
return "CD";
case 82:
return "CE";
case 83:
return "CF";
case 84:
return "CG";
case 85:
return "CH";
case 86:
return "CI";
case 87:
return "CJ";
case 88:
return "CK";
case 89:
return "CL";
case 90:
return "CM";
case 91:
return "CN";
case 92:
return "CO";
case 93:
return "CP";
case 94:
return "CQ";
case 95:
return "CR";
case 96:
return "CS";
case 97:
return "CT";
case 98:
return "CU";
case 99:
return "CV";
case 100:
return "CW";
case 101:
return "CX";
case 102:
return "CY";
case 103:
return "CZ";
case 104:
return "DA";
case 105:
return "DB";
case 106:
return "DC";
case 107:
return "DD";
case 108:
return "DE";
case 109:
return "DF";
case 110:
return "DG";
case 111:
return "DH";
case 112:
return "DI";
case 113:
return "DJ";
case 114:
return "DK";
case 115:
return "DL";
case 116:
return "DM";
case 117:
return "DN";
case 118:
return "DO";
case 119:
return "DP";
case 120:
return "DQ";
case 121:
return "DR";
case 122:
return "DS";
case 123:
return "DT";
case 124:
return "DU";
case 125:
return "DV";
case 126:
return "DW";
case 127:
return "DX";
case 128:
return "DY";
case 129:
return "DZ";
case 130:
return "EA";
case 131:
return "EB";
case 132:
return "EC";
case 133:
return "ED";
case 134:
return "EE";
case 135:
return "EF";
case 136:
return "EG";
case 137:
return "EH";
case 138:
return "EI";
case 139:
return "EJ";
case 140:
return "EK";
case 141:
return "EL";
case 142:
return "EM";
case 143:
return "EN";
case 144:
return "EO";
case 145:
return "EP";
case 146:
return "EQ";
case 147:
return "ER";
case 148:
return "ES";
case 149:
return "ET";
case 150:
return "EU";
case 151:
return "EV";
case 152:
return "EW";
case 153:
return "EX";
case 154:
return "EY";
case 155:
return "EZ";
case 156:
return "FA";
case 157:
return "FB";
case 158:
return "FC";
case 159:
return "FD";
case 160:
return "FE";
case 161:
return "FF";
case 162:
return "FG";
case 163:
return "FH";
case 164:
return "FI";
case 165:
return "FJ";
case 166:
return "FK";
case 167:
return "FL";
case 168:
return "FM";
case 169:
return "FN";
case 170:
return "FO";
case 171:
return "FP";
case 172:
return "FQ";
case 173:
return "FR";
case 174:
return "FS";
case 175:
return "FT";
case 176:
return "FU";
case 177:
return "FV";
case 178:
return "FW";
case 179:
return "FX";
case 180:
return "FY";
case 181:
return "FZ";
case 182:
return "GA";
case 183:
return "GB";
case 184:
return "GC";
case 185:
return "GD";
case 186:
return "GE";
case 187:
return "GF";
case 188:
return "GG";
case 189:
return "GH";
case 190:
return "GI";
case 191:
return "GJ";
case 192:
return "GK";
case 193:
return "GL";
case 194:
return "GM";
case 195:
return "GN";
case 196:
return "GO";
case 197:
return "GP";
case 198:
return "GQ";
case 199:
return "GR";
case 200:
return "GS";
case 201:
return "GT";
case 202:
return "GU";
case 203:
return "GV";
case 204:
return "GW";
case 205:
return "GX";
case 206:
return "GY";
case 207:
return "GZ";
default:
throw new Exception("超过最大限制");
}
}
}
JAVA生成EXCEL模板的更多相关文章
- java 生成Excel开门篇
本随笔的Excel所用的poi jar包(3.17版本)链接: https://pan.baidu.com/s/1gaa3dJueja8IraUDYCSLIQ 提取密码: 9xr7 简单实现:两个类: ...
- oracle PL/SQL调用Java生成Excel
现在有个需求, 要求编写oracle存储过程生成Excel文件到指定目录, 但是oracle自己的API貌似不太给力, 所以只能通过另一种更强大的语言来实现了 ——Java.有一个Java框架 ...
- Chimm.Excel —— 使用Java 操作 excel 模板文件生成 excel 文档
Chimm.Excel -- 设置模板,填充数据,就完事儿了~ _____ _ _ _____ _ / __ \ | (_) | ___| | | | / \/ |__ _ _ __ ___ _ __ ...
- 两种方式实现java生成Excel
Web应用中难免会遇到需要将数据导出并生成excel文件的需求.同样,对于本博客中的总结,也是建立在为了完成这样的一个需求,才开始去了解其实现形式,并且顺利完成需求的开发,先将实现过程总结于此.本博文 ...
- java实现excel模板导出
一. 准备工作 1. 点击此下载相关开发工具 2. 将poi-3.8.jxls-core-1.0两个jar包放到工程中,并引用 3. 将excel模板runRecord.xls放到RunRecordB ...
- Java生成excel导出文件(使用poi+JXL)
1.使用poi生成文件 package com.mi.entity; import java.util.Date; public class Student { private int id; pri ...
- java生成excel,word文件
第一部分: 在网站开发中,用户可能需要打印word或者excel表,这种需求是非常多的. java语言生成excel表格和python的方式有点像,使用Apache POI的组件,一通全通.开发过程通 ...
- java导出excel模板数据
Java导出excel数据模板,这里直接贴代码开发,流程性的走下去就是步骤: String[] colName=new String[]{"期间","科目代码" ...
- [转]java生成 excel 并导出文件
原文:https://blog.csdn.net/xunwei0303/article/details/53213130 目前,比较常用的实现Java导入.导出Excel的技术有两种Jakarta P ...
随机推荐
- Cow Routing(最短路spfa)
题:https://www.luogu.org/problem/P3115 题意:给出起点A,终点B,N条路线,下面没俩行一个路线,第一行是俩个数,第一个为这条路线的花费,第二个为这条路线经过的点数n ...
- mysql首次使用过程以及彻底卸载过程
安装过程: 步骤一: 安装mysql服务,使用命令行: yum install mysql-server 步骤二: 启动mysql服务: service mysqld start 确认msyql是否启 ...
- nodejs 模块变量 应用
exports.allcodeandname=(function(){ var fs = require('fs'); var data = fs.readFileSync(__dirname+'/a ...
- Derby数据库的使用
一. Derby数据库平台的搭建 ● JDK 1.6版本及之后的版本为Java平台提供了一个数据库管理系统,简称Derby数据库. ● 连接Derby数据库需要有关的类,这些类以jar文件的形 ...
- 题解:线性规划与网络流24题 T2 太空飞行计划问题
太空飞行计划问题 问题描述 W教授正在为国家航天中心计划一系列的太空飞行.每次太空飞行可进行一系列商业性实验而获取利润.现已确定了一个可供选择的实验集合E={E1,E2,-,Em},和进行这些实验需要 ...
- 千万不要在module里扩展较多逻辑,很容易引起项目异常。
NOP项目 为保持紧跟NOP更新,项目组坚持不改NOP源码. 以触发器,插件化开发为拓展模式 NOP自定义好的接口或完全独立的新拓展功能很容易插件化. 但部分功能要在NOP原项目上扩展修改在不改源码的 ...
- Memcached笔记——(四)应对高并发攻击
近半个月过得很痛苦,主要是产品上线后,引来无数机器用户恶意攻击,不停的刷新产品各个服务入口,制造垃圾数据,消耗资源.他们的最好成绩,1秒钟可以并发6次,赶在Database入库前,Cache进行Mis ...
- 16各种设计LOGO标准尺寸
继续抄写文章 网页设计标准尺寸: 1.800*600下,网页宽度保持在778以内, 2.1024*768下,网页宽度保持在1002以内, 3.在ps里面做网页可以在800*600状态下显 4.在PS里 ...
- spring boot 创建定时任务
@Scheduled默认创建的线程是单线程,任务的执行会受到上一个任务的影响,创建定时任务也比较简单 123456789101112 @Component@Configuration //1.主要用于 ...
- Selenium的Web自动化测试(送源码)
8.1 Selenium自动化测试准备 1.Selenium介绍 Selenium是一个Web开源自动化测试框架,页面级操作,模拟用户真实操作,API从系统层面触发事件. Selenium 1.0 ...