package org.ctzk.jcpc.utils;
import org.apache.poi.hssf.usermodel.HSSFCell;
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.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;
/**
* org.ctzk.jcpc.utils
*
* @author luozhen
* @version V1.0
* @date 2020-2-5 11:28
* @description
*/
public class ExcelUtil {
private String srcXlsPath = "";// // 导入excel模板路径
private String desXlsPath = "";
private String sheetName = "";
CellStyle cellStyle = null;
POIFSFileSystem fs = null;
HSSFWorkbook wb = null;
HSSFSheet sheet = null;
/**
* 第一步、设置excel模板路径
*
* @param srcXlsPath
*/
public void setSrcPath(String srcXlsPath) {
this.srcXlsPath = srcXlsPath;
}
/**
* 第二步、设置要生成excel文件路径
*
* @param desXlsPath
*/
public void setDesPath(String desXlsPath) {
this.desXlsPath = desXlsPath;
}
/**
* 第三步、设置模板中哪个Sheet列
*
* @param sheetName
*/
public void setSheetName(String sheetName) {
this.sheetName = sheetName;
}
/**
* 第四步、获取所读取excel模板的对象
*/
public void getSheet() {
try {
File fi = new File(srcXlsPath);
if (!fi.exists()) {
System.out.println("模板文件:" + srcXlsPath + "不存在!");
return;
}
fs = new POIFSFileSystem(new FileInputStream(fi));
wb = new HSSFWorkbook(fs);
cellStyle = getStyle(wb);
sheet = wb.getSheet(sheetName);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 第五步、设置字符串类型的数据
*
* @param rowIndex --行值
* @param cellnum --列值
* @param value --字符串类型的数据
*/
public void setCellStrValue(int rowIndex, int cellnum, String value) {
HSSFRow row = sheet.getRow(rowIndex);
if (null == row) {
row = sheet.createRow(rowIndex);
}
HSSFCell cell = row.getCell(cellnum);
if (null == row.getCell(cellnum)) {
cell = row.createCell(cellnum);
}
cell.setCellValue(value);
cell.setCellStyle(cellStyle);
}
/**
* 第五步、设置日期/时间类型的数据
*
* @param rowIndex --行值
* @param cellnum --列值
* @param value --日期/时间类型的数据
*/
public void setCellDateValue(int rowIndex, int cellnum, Date value) {
Cell cell = sheet.getRow(rowIndex).getCell(cellnum);
if (null != value) {
cell.setCellValue(value);
}
}
/**
* 第五步、设置浮点类型的数据
*
* @param rowIndex --行值
* @param cellnum --列值
* @param value --浮点类型的数据
*/
public void setCellDoubleValue(int rowIndex, int cellnum, double value) {
Cell cell = sheet.getRow(rowIndex).getCell(cellnum);
cell.setCellValue(value);
}
/**
* 第五步、设置Bool类型的数据
*
* @param rowIndex --行值
* @param cellnum --列值
* @param value --Bool类型的数据
*/
public void setCellBoolValue(int rowIndex, int cellnum, boolean value) {
Cell cell = sheet.getRow(rowIndex).getCell(cellnum);
cell.setCellValue(value);
}
/**
* 第五步、设置日历类型的数据
*
* @param rowIndex --行值
* @param cellnum --列值
* @param value --日历类型的数据
*/
public void setCellCalendarValue(int rowIndex, int cellnum, Calendar value) {
Cell cell = sheet.getRow(rowIndex).getCell(cellnum);
if (null != value) {
cell.setCellValue(value);
}
}
/**
* 第五步、设置富文本字符串类型的数据。可以为同一个单元格内的字符串的不同部分设置不同的字体、颜色、下划线
*
* @param rowIndex --行值
* @param cellnum --列值
* @param value --富文本字符串类型的数据
*/
public void setCellRichTextStrValue(int rowIndex, int cellnum, RichTextString value) {
Cell cell = sheet.getRow(rowIndex).getCell(cellnum);
cell.setCellValue(value);
}
/**
* 第六步、完成导出 type=0,不会修改表格名 type=1,修改表格名依次为当日日期,明日日期,后天日期,递增
*/
public void exportToWeb(HttpServletResponse response, String fileName) {
OutputStream out = null;
String encodedfileName = "";
try {
if (fileName.toLowerCase().endsWith(".xls")) {
encodedfileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
} else {
encodedfileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1") + ".xls";
}
response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedfileName + "\"");
response.setContentType("application/vnd.ms-excel");
out = response.getOutputStream();
out.flush();
wb.write(out);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//关闭流
out.close();
wb.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 根据模版导出Excel(2007及以上版本)
*
* @param response 响应对象
* @param tempFileName 模版文件名
* @param outFileName 输出文件名
* @param sheetIndex Sheet页签索引,从0开始
* @param startRow 开始行,从0开始
* @param startCell 开始列,从0开始
* @param dataList 数据集合,不能为空
*/
public static void exportExcelByTemp07(HttpServletResponse response, String tempFileName, String outFileName, Integer sheetIndex, Integer startRow, Integer startCell, List<LinkedHashMap<String, Object>> dataList) {
Workbook wb = null;
InputStream is = null;
try {
is = new FileInputStream(getFilePath(tempFileName));
// 第一步:创建工作空间,对应Excel文件
wb = new XSSFWorkbook(is);
// 第二步:向工作工作空间中写入内容
exportExcelByTemp(wb, sheetIndex, startRow, startCell, dataList);
// 第三步:将文件输出到客户端浏览器
outExcelToClient(response, wb, outFileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static String getFilePath(String fileName) throws UnsupportedEncodingException {
String root = ExcelUtil.class.getResource("/").getPath();
if (root.indexOf("target") >= 0) {
root = root.substring(1, root.indexOf("target"));
root = root.replaceAll("/", "\\\\");
root = root + "src\\main\\webapp" + File.separator + "excle_model" + File.separator + fileName;
} else {
root = root.substring(1, root.indexOf("WEB-INF"));
root = root.replaceAll("/", "\\\\");
root = root + "excle_model" + File.separator + fileName;
}
return URLDecoder.decode(root, "GBK");
}
/**
* 根据模版导出Excel
*
* @param wb 工作空间,对应Excel文件
* @param sheetIndex Sheet页签索引,从0开始
* @param startRow 开始行,从0开始
* @param startCell 开始列,从0开始
* @param dataList 数据集合,不能为空
*/
private static void exportExcelByTemp(Workbook wb, Integer sheetIndex, Integer startRow, Integer startCell, List<LinkedHashMap<String, Object>> dataList) {
// Sheet页签,从0开始
sheetIndex = (sheetIndex != null && sheetIndex > 0) ? sheetIndex : 0;
// 第一步:获取Sheet页签
Sheet sheet = wb.getSheetAt(sheetIndex);
// 如果页签不存在,则创建页签
sheet = sheet != null ? sheet : wb.createSheet();
if (dataList != null && dataList.size() > 0) {
// 开始行
startRow = (startRow != null && startRow > 0) ? startRow : 0;
// 开始列
startCell = (startCell != null && startCell > 0) ? startCell : 0;
// 样式(画笔)
CellStyle cellStyle = getStyle(wb);
for (int i = 0, size = dataList.size(); i < size; i++) {
// 第二步:获取行
// Row row = sheet.getRow(startRow + i);
Row row = sheet.createRow(startRow + i);
// 设置行高
row.setHeightInPoints(20);
LinkedHashMap<String, Object> dataMap = dataList.get(0);
int j = 0;
for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
// 第三步: 获取单元格
Cell cell = row.createCell(startCell + j);
// Cell cell = row.getCell(startRow + j);
// 设置单元格类型为字符串
cell.setCellType(CellType.STRING);
cell.setCellValue(String.valueOf(entry.getValue()));
cell.setCellStyle(cellStyle);
j++;
entry = null;
}
dataList.remove(0);
}
}
}
/**
* 输入Excel文件到客户端
*
* @param response 响应对象
* @param wb 工作空间,对应一个Excel文件
* @param fileName Excel文件名
*/
private static void outExcelToClient(HttpServletResponse response, Workbook wb, String fileName) {
OutputStream out = null;
try {
response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
response.setContentType("application/vnd.ms-excel; charset=UTF-8");
out = response.getOutputStream();
wb.write(out);
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
wb.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 获取样式
*
* @param wb 工作空间
* @return
*/
private static CellStyle getStyle(Workbook wb) {
// 设置字体;
Font font = wb.createFont();
// 设置字体大小;
font.setFontHeightInPoints((short) 12);
// 设置字体名字;
font.setFontName("宋体");
// font.setItalic(true); // 斜体
// font.setStrikeout(true); // 删除线
// 设置样式;
CellStyle style = wb.createCellStyle();
// 设置底边框;
style.setBorderBottom(BorderStyle.THIN);
// 设置底边框颜色;
style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
// 设置左边框;
style.setBorderLeft(BorderStyle.THIN);
// 设置左边框颜色;
style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
// 设置右边框;
style.setBorderRight(BorderStyle.THIN);
// 设置右边框颜色;
style.setRightBorderColor(IndexedColors.BLACK.getIndex());
// 设置顶边框;
style.setBorderTop(BorderStyle.THIN);
// 设置顶边框颜色;
style.setTopBorderColor(IndexedColors.BLACK.getIndex());
// 在样式用应用设置的字体;
style.setFont(font);
// 设置自动换行;
style.setWrapText(false);
// 设置水平对齐的样式为居中对齐;
style.setAlignment(HorizontalAlignment.CENTER);
// 设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(VerticalAlignment.CENTER);
return style;
}
}
原生POI导出-进阶版
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 03版用HSSFWorkbook最多只能导入六万五行的数据,07版excel用SXSSFWorkbook 可以导出...
- 解决哪些问题 开发中偶尔会有固定模板导出word的需求,常见的导出通常通过直接修改xml或者通过工具库代码调整样式...
- 前面讲完概述、原理以及helloworld,现在就讲下怎样的POI的EXCEL导出工具可以适用于各种情况吧。后面再...
- 生成XLSX格式Excel文档大数据量导出 使用Apache POI导出Excel小结--导出XLS格式文档 使用...