package com.xxx.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class ExcelTemplate {
/**
* 数据行标识
*/
public final static String DATA_LINE = "datas";
/**
* 默认样式标识
*/
public final static String DEFAULT_STYLE = "defaultStyles";
/**
* 行样式标识
*/
public final static String STYLE = "styles";
/**
* 插入序号样式标识
*/
public final static String SER_NUM = "sernums";
public static ExcelTemplate et = new ExcelTemplate();
public Workbook wb;
public Sheet sheet;
/**
* 数据的初始化列数
*/
public int initColIndex;
/**
* 数据的初始化行数
*/
public int initRowIndex;
/**
* 当前列数
*/
public int curColIndex;
/**
* 当前行数
*/
public int curRowIndex;
/**
* 当前行对象
*/
public Row curRow;
/**
* 最后一行的数据
*/
public int lastRowIndex;
/**
* 默认样式
*/
public CellStyle defaultStyle;
/**
* 默认行高
*/
public float rowHeight;
/**
* 存储某一方所对应的样式
*/
public Map<Integer, CellStyle> styles;
/**
* 序号的列
*/
public int serColIndex;
public ExcelTemplate() {
}
public static ExcelTemplate getInstance() {
return et;
}
/**
* 1、读取相应的模板文档
*/
public ExcelTemplate readTemplateByClasspath(String path) {
try {
wb = WorkbookFactory.create(ExcelTemplate.class.getResourceAsStream(path));
initTemplate();
} catch (InvalidFormatException e) {
e.printStackTrace();
throw new RuntimeException("InvalidFormatException, please check.");
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("The template is not exist, please check.");
}
return this;
}
public ExcelTemplate readTemplateByPath(String path) {
try {
wb = WorkbookFactory.create(new File(path));
initTemplate();
} catch (InvalidFormatException e) {
e.printStackTrace();
throw new RuntimeException("InvalidFormatException, please check.");
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("The template is not exist, please check.");
}
return this;
}
public void initTemplate() {
sheet = wb.getSheetAt(0);
initConfigData();
lastRowIndex = sheet.getLastRowNum();
curRow = sheet.getRow(curRowIndex);
}
/**
* 循环遍历,找到有datas字符的那个单元,记录initColIndex,initRowIndex,curColIndex,curRowIndex
* 调用initStyles()方法
* 在寻找datas字符的时候会顺便找一下sernums,如果有则记录其列号serColIndex;如果没有则调用initSer()方法,重新循环查找
*/
public void initConfigData() {
boolean findData = false;
boolean findSer = false;
for (Row row : sheet) {
if (findData)
break;
for (Cell c : row) {
if (c.getCellType() != Cell.CELL_TYPE_STRING)
continue;
String str = c.getStringCellValue().trim();
if (str.equals(SER_NUM)) {
serColIndex = c.getColumnIndex();
findSer = true;
}
if (str.equals(DATA_LINE)) {
initColIndex = c.getColumnIndex();
initRowIndex = row.getRowNum();
curColIndex = initColIndex;
curRowIndex = initRowIndex;
findData = true;
}
}
}
if (!findSer) {
initSer();
}
initStyles();
}
/**
* 初始化序号位置
*/
public void initSer() {
for (Row row : sheet) {
for (Cell c : row) {
if (c.getCellType() != Cell.CELL_TYPE_STRING)
continue;
String str = c.getStringCellValue().trim();
if (str.equals(SER_NUM)) {
serColIndex = c.getColumnIndex();
}
}
}
}
/**
* 初始化样式信息
*/
public void initStyles() {
styles = new HashMap<Integer, CellStyle>();
for (Row row : sheet) {
for (Cell c : row) {
if (c.getCellType() != Cell.CELL_TYPE_STRING)
continue;
String str = c.getStringCellValue().trim();
if (str.equals(DEFAULT_STYLE)) {
defaultStyle = c.getCellStyle();
rowHeight = row.getHeightInPoints();
}
if (str.equals(STYLE) || str.equals(SER_NUM)) {
styles.put(c.getColumnIndex(), c.getCellStyle());
}
}
}
}
/**
* 下载文件的操作
* @param request
* @param response
* @param filePath 文件全路径
* @param fileName 指定客户端下载时显示的文件名
* @throws IOException
* @author liuyy
* @date 2022-04-14
*/
public void downloadFile(HttpServletRequest request, HttpServletResponse response, String filePath, String fileName)
throws IOException {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
bis = new BufferedInputStream(new FileInputStream(filePath));
bos = new BufferedOutputStream(response.getOutputStream());
long fileLength = new File(filePath).length();
solveGarbled(request, response, fileName, bis, bos, fileLength);
bis.close();
bos.close();
}
/**
* 解决下载的时候针对不同浏览器乱码的操作
* @param request
* @param response
* @param fileName
* @param bis
* @param bos
* @param fileLength
* @throws UnsupportedEncodingException
* @throws IOException
* @author liuyy
* @date 2022-04-14
*/
public void solveGarbled(HttpServletRequest request, HttpServletResponse response, String fileName, BufferedInputStream bis,
BufferedOutputStream bos, long fileLength) throws UnsupportedEncodingException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("multipart/form-data");
//解决各浏览器的中文乱码问题
String userAgent = request.getHeader("User-Agent");
byte[] bytes = userAgent.contains("MSIE") ? fileName.getBytes() : fileName.getBytes("UTF-8");
fileName = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName));
response.setHeader("Content-Length", String.valueOf(fileLength));
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
}
public void writeToFile(String filepath) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(filepath);
wb.write(fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new RuntimeException("写入的文件不存在" + e.getMessage());
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("写入数据失败" + e.getMessage());
} finally {
if (fos != null)
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*public void createCell(String value) {
Cell c = curRow.createCell(curColIndex);
setCellStyle(c);
c.setCellValue(value);
curColIndex++;
}*/
public void createCell(String value) {
if (curColIndex == 17) {
curRowIndex++;
curColIndex = initColIndex;
Cell c = sheet.getRow(curRowIndex).getCell(curColIndex);
setCellStyle(c);
c.setCellValue(value);
curColIndex++;
}else {
Cell c = sheet.getRow(curRowIndex).getCell(curColIndex);
setCellStyle(c);
c.setCellValue(value);
curColIndex++;
}
}
public void createCell(int value) {
Cell c = curRow.createCell(curColIndex);
setCellStyle(c);
c.setCellValue((int) value);
curColIndex++;
}
public void createCell(Date value) {
Cell c = curRow.createCell(curColIndex);
setCellStyle(c);
c.setCellValue(value);
curColIndex++;
}
public void createCell(double value) {
Cell c = curRow.createCell(curColIndex);
setCellStyle(c);
c.setCellValue(value);
curColIndex++;
}
public void createCell(boolean value) {
Cell c = curRow.createCell(curColIndex);
setCellStyle(c);
c.setCellValue(value);
curColIndex++;
}
public void createCell(Calendar value) {
Cell c = curRow.createCell(curColIndex);
setCellStyle(c);
c.setCellValue(value);
curColIndex++;
}
/**
* 设置某个单元格的样式
*
* @param c
*/
public void setCellStyle(Cell c) {
if (styles.containsKey(c.getColumnIndex())) {
c.setCellStyle(styles.get(c.getColumnIndex()));
} else {
c.setCellStyle(defaultStyle);
}
}
public void createNewRow() {
if (lastRowIndex > curRowIndex && curRowIndex != initRowIndex) {
sheet.shiftRows(curRowIndex, lastRowIndex, 1, true, true);
lastRowIndex++;
}
curRow = sheet.createRow(curRowIndex);
curRow.setHeightInPoints(rowHeight);
curRowIndex++;
curColIndex = initColIndex;
}
/**
* 插入序号,会自动找相应的序号标示的位置完成插入
*/
public void insertSer() {
int index = 1;
Row row = null;
Cell c = null;
for (int i = initRowIndex; i < curRowIndex; i++) {
row = sheet.getRow(i);
c = row.createCell(serColIndex);
setCellStyle(c);
c.setCellValue(index++);
}
}
/**
* 根据map替换相应的常量,通过Map中的值来替换#开头的值
*
* @param datas
*/
public void replaceFinalData(Map<String, Object> datas) {
if (datas == null)
return;
for (Row row : sheet) {
for (Cell c : row) {
if (c.getCellType() != Cell.CELL_TYPE_STRING)
continue;
String str = c.getStringCellValue().trim();
if (str.startsWith("#")) {
if (datas.containsKey(str.substring(1))) {
c.setCellValue(datas.get(str.substring(1)).toString());
}
}
}
}
}
public static void main(String[] args) {
ExcelTemplate et = ExcelTemplate.getInstance().readTemplateByPath("D:/stanRiskAssessment.xlsx");
et.createCell("1111111");
et.createCell("aaaaaaaaaaaa");
et.createCell("a1");
et.createCell("a2a2");
et.createCell("1111111");
et.createCell("aaaaaaaaaaaa");
et.createCell("a1");
et.createCell("a2a2");
et.createCell("a2a2");
et.createCell("2111111");
et.createCell("baaaaaaaaaaa");
et.createCell("b1");
et.createCell("b2a2");
et.createCell("2111111");
et.createCell("baaaaaaaaaaa");
et.createCell("b1");
et.createCell("b2a2");
et.createCell("b2a2");
et.createCell("1111111");
et.createCell("aaaaaaaaaaaa");
et.createCell("a1");
et.createCell("a2a2");
et.createCell("1111111");
et.createCell("aaaaaaaaaaaa");
et.createCell("a1");
et.createCell("a2a2");
et.createCell("a2a2");
et.createCell("2111111");
et.createCell("baaaaaaaaaaa");
et.createCell("b1");
et.createCell("b2a2");
et.createCell("2111111");
et.createCell("baaaaaaaaaaa");
et.createCell("b1");
et.createCell("b2a2");
et.createCell("b2a2");
et.createCell("1111111");
et.createCell("aaaaaaaaaaaa");
et.createCell("a1");
et.createCell("a2a2");
et.createCell("1111111");
et.createCell("aaaaaaaaaaaa");
et.createCell("a1");
et.createCell("a2a2");
et.createCell("a2a2");
et.createCell("2111111");
et.createCell("baaaaaaaaaaa");
et.createCell("b1");
et.createCell("b2a2");
et.createCell("2111111");
et.createCell("baaaaaaaaaaa");
et.createCell("b1");
et.createCell("b2a2");
et.createCell("b2a2");
et.createCell("1111111");
et.createCell("aaaaaaaaaaaa");
et.createCell("a1");
et.createCell("a2a2");
et.createCell("1111111");
et.createCell("aaaaaaaaaaaa");
et.createCell("a1");
et.createCell("a2a2");
et.createCell("a2a2");
et.createCell("2111111");
et.createCell("baaaaaaaaaaa");
et.createCell("b1");
et.createCell("b2a2");
et.createCell("2111111");
et.createCell("baaaaaaaaaaa");
et.createCell("b1");
et.createCell("b2a2");
et.createCell("b2a2");
et.createCell("1111111");
et.createCell("aaaaaaaaaaaa");
et.createCell("a1");
et.createCell("a2a2");
et.createCell("1111111");
et.createCell("aaaaaaaaaaaa");
et.createCell("a1");
et.createCell("a2a2");
et.createCell("a2a2");
et.createCell("2111111");
et.createCell("baaaaaaaaaaa");
et.createCell("b1");
et.createCell("b2a2");
et.createCell("2111111");
et.createCell("baaaaaaaaaaa");
et.createCell("b1");
et.createCell("b2a2");
et.createCell("b2a2");
et.createCell("1111111");
et.createCell("aaaaaaaaaaaa");
et.createCell("a1");
et.createCell("a2a2");
et.createCell("1111111");
et.createCell("aaaaaaaaaaaa");
et.createCell("a1");
et.createCell("a2a2");
et.createCell("a2a2");
et.createCell("2111111");
et.createCell("baaaaaaaaaaa");
et.createCell("b1");
et.createCell("b2a2");
et.createCell("2111111");
et.createCell("baaaaaaaaaaa");
et.createCell("b1");
et.createCell("b2a2");
et.createCell("b2a2");
et.createCell("1111111");
et.createCell("aaaaaaaaaaaa");
et.createCell("a1");
et.createCell("a2a2");
et.createCell("1111111");
et.createCell("aaaaaaaaaaaa");
et.createCell("a1");
et.createCell("a2a2");
et.createCell("a2a2");
et.createCell("2111111");
et.createCell("baaaaaaaaaaa");
et.createCell("b1");
et.createCell("b2a2");
et.createCell("2111111");
et.createCell("baaaaaaaaaaa");
et.createCell("b1");
et.createCell("b2a2");
et.createCell("b2a2");
et.createCell("1111111");
et.createCell("aaaaaaaaaaaa");
et.createCell("a1");
et.createCell("a2a2");
et.createCell("1111111");
et.createCell("aaaaaaaaaaaa");
et.createCell("a1");
et.createCell("a2a2");
et.createCell("a2a2");
et.createCell("2111111");
et.createCell("baaaaaaaaaaa");
et.createCell("b1");
et.createCell("b2a2");
et.createCell("2111111");
et.createCell("baaaaaaaaaaa");
et.createCell("b1");
et.createCell("b2a2");
et.createCell("b2a2");
et.createCell("1111111");
et.createCell("aaaaaaaaaaaa");
et.createCell("a1");
et.createCell("a2a2");
et.createCell("1111111");
et.createCell("aaaaaaaaaaaa");
et.createCell("a1");
et.createCell("a2a2");
et.createCell("a2a2");
et.createCell("2111111");
et.createCell("baaaaaaaaaaa");
et.createCell("b1");
et.createCell("b2a2");
et.createCell("2111111");
et.createCell("baaaaaaaaaaa");
et.createCell("b1");
et.createCell("b2a2");
et.createCell("b2a2");
et.createCell("1111111");
et.createCell("aaaaaaaaaaaa");
et.createCell("a1");
et.createCell("a2a2");
et.createCell("1111111");
et.createCell("aaaaaaaaaaaa");
et.createCell("a1");
et.createCell("a2a2");
et.createCell("a2a2");
et.createCell("2111111");
et.createCell("baaaaaaaaaaa");
et.createCell("b1");
et.createCell("b2a2");
et.createCell("2111111");
et.createCell("baaaaaaaaaaa");
et.createCell("b1");
et.createCell("b2a2");
et.createCell("b2a2");
et.createCell("1111111");
et.createCell("aaaaaaaaaaaa");
et.createCell("a1");
et.createCell("a2a2");
et.createCell("1111111");
et.createCell("aaaaaaaaaaaa");
et.createCell("a1");
et.createCell("a2a2");
et.createCell("a2a2");
et.createCell("2111111");
et.createCell("baaaaaaaaaaa");
et.createCell("b1");
et.createCell("b2a2");
et.createCell("2111111");
et.createCell("baaaaaaaaaaa");
et.createCell("b1");
et.createCell("b2a2");
et.createCell("b2a2");
et.createCell("1111111");
et.createCell("aaaaaaaaaaaa");
et.createCell("a1");
et.createCell("a2a2");
et.createCell("1111111");
et.createCell("aaaaaaaaaaaa");
et.createCell("a1");
et.createCell("a2a2");
et.createCell("a2a2");
et.createCell("2111111");
et.createCell("baaaaaaaaaaa");
et.createCell("b1");
et.createCell("b2a2");
et.createCell("2111111");
et.createCell("baaaaaaaaaaa");
et.createCell("b1");
et.createCell("b2a2");
et.createCell("b2a2");
et.createCell("1111111");
et.createCell("aaaaaaaaaaaa");
et.createCell("a1");
et.createCell("a2a2");
et.createCell("1111111");
et.createCell("aaaaaaaaaaaa");
et.createCell("a1");
et.createCell("a2a2");
et.createCell("a2a2");
et.writeToFile("D:/test02.xlsx");
}
}