在工作中有很多场景需要读取excel,导出excel
搜了是这位大佬写的excel工具类,
https://blog.csdn.net/l1028386804/article/details/79659605
在工作中遇到了一点问题进行了优化,
主要包括
读取excel:统一返回二位数组,(日期,数字格式的处理)
导出excel:自适应宽度,科学计数法优化(2003),导出这里只优化了2003,因为导出xls格式都可以打开
先看效果
测试读取
/**
* 测试读取excel
*
* @throws IOException
* @throws InvalidFormatException
*/
@Test
public void readExcel() throws IOException, InvalidFormatException {
String excel = "C:\\Users\\chenggaowei\\Desktop\\新建 XLSX 工作表.xlsx";
String[][] datas = ExcelUtil.readExcel(new File(excel));
for (String[] data : datas) {
System.out.println(JSON.toJSONString(data));
}
}
/**
* 测试导出excel
*
* @throws IOException
*/
@Test
public void exportExcel() throws IOException {
List<UserDO> users = new ArrayList<>();
for (int i = 0; i < 10; i++) {
UserDO userDO = new UserDO();
userDO.setId(IdUtil.nextId());
userDO.setUid(IdUtil.uuid());
userDO.setUserName("测试Excel" + (i + 1));
users.add(userDO);
}
UserDO userDO1 = new UserDO();
userDO1.setId(IdUtil.nextId());
userDO1.setUid(IdUtil.uuid());
users.add(userDO1);
for (int i = 0; i < 10; i++) {
UserDO userDO = new UserDO();
userDO.setId(IdUtil.nextId());
userDO.setUid(IdUtil.uuid());
userDO.setUserName("测试Excel" + (i + 1));
users.add(userDO);
}
File file = new File("C:\\Users\\chenggaowei\\Desktop\\测试excel.xls");
String[] header = new String[]{"编号", "用户Id", "用户名"};
new ExcelUtil().exportExcel("用户数据", header, users, new FileOutputStream(file));
}
效果
原文链接
https://blog.csdn.net/l1028386804/article/details/79659605
package com.test.utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.apache.poi.ss.usermodel.FillPatternType.SOLID_FOREGROUND;
import static org.apache.poi.ss.usermodel.IndexedColors.BLACK;
import static org.apache.poi.ss.usermodel.IndexedColors.LIGHT_CORNFLOWER_BLUE;
/**
* 导出Excel
*
* @param <T>
* @author liuyazhuang
*/
@Slf4j
public class ExcelUtil<T> {
// 2007 版本以上 最大支持1048576行
public final static String EXCEl_FILE_2007 = "2007";
// 2003 版本 最大支持65536 行
public final static String EXCEL_FILE_2003 = "2003";
private static final String NUMBER_REGEX = "^\\d+(\\.\\d+)?$";
private static final String DATE_FORMAT = "yyyy-MM-dd hh:mm:ss";
private static final SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
private static final String pattern = "\\d{4}\\.";
/**
* <p>
* 导出带有头部标题行的Excel <br>
* 时间格式默认:yyyy-MM-dd hh:mm:ss <br>
* </p>
*
* @param title 表格标题
* @param headers 头部标题集合
* @param dataset 数据集合
* @param out 输出流
*/
public void exportExcel(String title, String[] headers, Collection<T> dataset, OutputStream out) {
exportExcel2003(title, headers, dataset, out, DATE_FORMAT);
}
/**
* <p>
* 导出带有头部标题行的Excel <br>
* 时间格式默认:yyyy-MM-dd hh:mm:ss <br>
* </p>
*
* @param title 表格标题
* @param headers 头部标题集合
* @param dataset 数据集合
* @param out 输出流
* @param version 2003 或者 2007,不传时默认生成2003版本
*/
public void exportExcel(String title, String[] headers, Collection<T> dataset, OutputStream
out, String version) {
if (StringUtils.isBlank(version) || EXCEL_FILE_2003.equals(version.trim())) {
exportExcel2003(title, headers, dataset, out, DATE_FORMAT);
} else {
exportExcel2007(title, headers, dataset, out, DATE_FORMAT);
}
}
/**
* <p>
* 通用Excel导出方法,利用反射机制遍历对象的所有字段,将数据写入Excel文件中 <br>
* 此版本生成2007以上版本的文件 (文件后缀:xlsx)
* </p>
*
* @param title 表格标题名
* @param headers 表格头部标题集合
* @param dataset 需要显示的数据集合,集合中一定要放置符合JavaBean风格的类的对象。此方法支持的
* JavaBean属性的数据类型有基本数据类型及String,Date
* @param out 与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
* @param pattern 如果有时间数据,设定输出格式。默认为"yyyy-MM-dd hh:mm:ss"
*/
@SuppressWarnings({"unchecked", "rawtypes"})
private void exportExcel2007(String title, String[] headers, Collection<T> dataset,
OutputStream out, String pattern) {
// 声明一个工作薄
XSSFWorkbook workbook = new XSSFWorkbook();
// 生成一个表格
XSSFSheet sheet = workbook.createSheet(title);
// 设置表格默认列宽度为15个字节
sheet.setDefaultColumnWidth(20);
// 生成一个样式
XSSFCellStyle style = workbook.createCellStyle();
// 设置这些样式
style.setFillForegroundColor(new XSSFColor(java.awt.Color.gray));
style.setFillPattern(SOLID_FOREGROUND);
style.setBorderBottom(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
style.setBorderTop(BorderStyle.THIN);
style.setAlignment(HorizontalAlignment.CENTER);
// 生成一个字体
XSSFFont font = workbook.createFont();
font.setBold(true);
font.setFontName("宋体");
font.setColor(new XSSFColor(java.awt.Color.BLACK));
font.setFontHeightInPoints((short) 11);
// 把字体应用到当前的样式
style.setFont(font);
// 生成并设置另一个样式
XSSFCellStyle style2 = workbook.createCellStyle();
style2.setFillForegroundColor(new XSSFColor(java.awt.Color.WHITE));
style2.setFillPattern(SOLID_FOREGROUND);
style2.setBorderBottom(BorderStyle.THIN);
style2.setBorderLeft(BorderStyle.THIN);
style2.setBorderRight(BorderStyle.THIN);
style2.setBorderTop(BorderStyle.THIN);
style2.setAlignment(HorizontalAlignment.CENTER);
style2.setVerticalAlignment(VerticalAlignment.CENTER);
// 生成另一个字体
// XSSFFont font2 = workbook.createFont();
// font2.setBold(true);
// 把字体应用到当前的样式
// style2.setFont(font2);
// 产生表格标题行
XSSFRow row = sheet.createRow(0);
XSSFCell cellHeader;
for (int i = 0; i < headers.length; i++) {
cellHeader = row.createCell(i);
cellHeader.setCellStyle(style);
cellHeader.setCellValue(new XSSFRichTextString(headers[i]));
}
// 遍历集合数据,产生数据行
Iterator<T> it = dataset.iterator();
int index = 0;
T t;
Field[] fields;
Field field;
XSSFRichTextString richString;
Pattern p = Pattern.compile(NUMBER_REGEX);
Matcher matcher;
String fieldName;
String getMethodName;
XSSFCell cell;
Class tCls;
Method getMethod;
Object value;
String textValue;
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
while (it.hasNext()) {
index++;
row = sheet.createRow(index);
t = (T) it.next();
// 利用反射,根据JavaBean属性的先后顺序,动态调用getXxx()方法得到属性值
fields = t.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
cell = row.createCell(i);
cell.setCellStyle(style2);
field = fields[i];
fieldName = field.getName();
getMethodName = "get" + fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1);
try {
tCls = t.getClass();
getMethod = tCls.getMethod(getMethodName, new Class[]{});
value = getMethod.invoke(t, new Object[]{});
// 判断值的类型后进行强制类型转换
textValue = null;
if (value instanceof Integer) {
cell.setCellValue((Integer) value);
} else if (value instanceof Float) {
textValue = String.valueOf((Float) value);
cell.setCellValue(textValue);
} else if (value instanceof Double) {
textValue = String.valueOf((Double) value);
cell.setCellValue(textValue);
} else if (value instanceof Long) {
cell.setCellValue((Long) value);
}
if (value instanceof Boolean) {
textValue = "是";
if (!(Boolean) value) {
textValue = "否";
}
} else if (value instanceof Date) {
textValue = sdf.format((Date) value);
} else {
// 其它数据类型都当作字符串简单处理
if (value != null) {
textValue = value.toString();
}
}
if (textValue != null) {
matcher = p.matcher(textValue);
if (matcher.matches()) {
// 是数字当作double处理
cell.setCellValue(Double.parseDouble(textValue));
} else {
richString = new XSSFRichTextString(textValue);
cell.setCellValue(richString);
}
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} finally {
// 清理资源
}
}
}
try {
workbook.write(out);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* <p>
* 通用Excel导出方法,利用反射机制遍历对象的所有字段,将数据写入Excel文件中 <br>
* 此方法生成2003版本的excel,文件名后缀:xls <br>
* </p>
*
* @param title 表格标题名
* @param headers 表格头部标题集合
* @param dataset 需要显示的数据集合,集合中一定要放置符合JavaBean风格的类的对象。此方法支持的
* JavaBean属性的数据类型有基本数据类型及String,Date
* @param out 与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
* @param pattern 如果有时间数据,设定输出格式。默认为"yyyy-MM-dd hh:mm:ss"
*/
@SuppressWarnings({"unchecked", "rawtypes"})
private void exportExcel2003(String title, String[] headers, Collection<T> dataset,
OutputStream out, String pattern) {
try (HSSFWorkbook workbook = new HSSFWorkbook()) {// 声明一个工作薄
// 生成一个表格
HSSFSheet sheet = workbook.createSheet(title);
// 生成一个样式
HSSFCellStyle style = workbook.createCellStyle();
// 设置这些样式
style.setFillForegroundColor(LIGHT_CORNFLOWER_BLUE.index);
style.setFillPattern(SOLID_FOREGROUND);
// style.setBorderBottom(BorderStyle.THIN);
// style.setBorderLeft(BorderStyle.THIN);
// style.setBorderRight(BorderStyle.THIN);
// style.setBorderTop(BorderStyle.THIN);
style.setAlignment(HorizontalAlignment.CENTER);
// 生成一个字体
HSSFFont font = workbook.createFont();
// font.setBold(true);
//font.setFontName("宋体");
font.setColor(BLACK.index);
font.setFontHeightInPoints((short) 12);
// 把字体应用到当前的样式
style.setFont(font);
// 生成并设置另一个样式
HSSFCellStyle style2 = workbook.createCellStyle();
HSSFDataFormat format = workbook.createDataFormat();
style2.setDataFormat(format.getFormat("@"));
// 生成另一个字体
// HSSFFont font2 = workbook.createFont();
// font2.setBold(true);
// 把字体应用到当前的样式
// style2.setFont(font2);
// 产生表格标题行
HSSFRow row = sheet.createRow(0);
HSSFCell cellHeader;
for (int i = 0; i < headers.length; i++) {
cellHeader = row.createCell(i);
cellHeader.setCellStyle(style);
cellHeader.setCellValue(new HSSFRichTextString(headers[i]));
}
// 遍历集合数据,产生数据行
Iterator<T> it = dataset.iterator();
int index = 0;
T t;
Field[] fields;
Field field;
HSSFRichTextString richString;
Pattern p = Pattern.compile(NUMBER_REGEX);
Matcher matcher;
String fieldName;
String getMethodName;
HSSFCell cell;
Class tCls;
Method getMethod;
Object value;
String textValue;
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
while (it.hasNext()) {
index++;
row = sheet.createRow(index);
t = it.next();
// 利用反射,根据JavaBean属性的先后顺序,动态调用getXxx()方法得到属性值
fields = t.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
cell = row.createCell(i);
cell.setCellStyle(style2);
field = fields[i];
fieldName = field.getName();
getMethodName = "get" + fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1);
try {
tCls = t.getClass();
getMethod = tCls.getMethod(getMethodName, new Class[]{});
value = getMethod.invoke(t, new Object[]{});
if (value instanceof LocalDateTime) {
textValue = DateUtil.format((LocalDateTime) value, DATE_FORMAT);
} else {
if (Objects.isNull(value)) {
value = "";
}
textValue = value.toString();
}
cell.setCellValue(textValue);
sheet.setColumnWidth(i, (value.toString().length() + 2) * 256);
} catch (SecurityException e) {
log.error("SecurityException {}", e);
} catch (NoSuchMethodException e) {
log.error("NoSuchMethodException {}", e);
} catch (IllegalArgumentException e) {
log.error("IllegalArgumentException {}", e);
} catch (IllegalAccessException e) {
log.error("IllegalAccessException {}", e);
} catch (InvocationTargetException e) {
log.error("InvocationTargetException {}", e);
} finally {
// 清理资源
}
}
}
workbook.write(out);
} catch (Exception e) {
log.error("Exception {}", e);
}
}
/**
* 读取excel的数据,返回二维数组,未进行单元格合并处理
*
* @param excel
* @return
* @throws IOException
* @throws InvalidFormatException
*/
public static String[][] readExcel(File excel) throws IOException, InvalidFormatException {
if (null == excel || !excel.isFile() || !excel.exists()) {
throw new RuntimeException("excel文件不存在");
}
String ext = FilenameUtils.getExtension(excel.getName());
Workbook wb;
// 根据文件后缀(xls/xlsx)进行判断
if ("xls".equals(ext)) {
FileInputStream fis = new FileInputStream(excel);
wb = new HSSFWorkbook(fis);
} else if ("xlsx".equals(ext)) {
wb = new XSSFWorkbook(excel);
} else {
throw new RuntimeException("excel文件类型错误");
}
//开始解析
Sheet sheet = wb.getSheetAt(0); // 读取sheet 0
int firstRowIndex = sheet.getFirstRowNum() + 1; // 第一行是列名,所以不读
int lastRowIndex = sheet.getLastRowNum();
log.info("读取 {} 从第 {} 行到第 {} 行", excel.getName(), firstRowIndex + 1, lastRowIndex + 1);
Row firstRow = sheet.getRow(0);
int width = firstRow.getLastCellNum();
for (Row row : sheet) {
if (width < row.getLastCellNum()) {
width = row.getLastCellNum();
}
}
String[][] datas = new String[lastRowIndex][];
boolean containsFormula = false;
for (int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) { //遍历行
Row row = sheet.getRow(rIndex);
if (!isAllRowEmpty(row)) {
int firstCellIndex = row.getFirstCellNum();
// 这里应该以第一列的宽度为宽度
int lastCellIndex = width;
datas[rIndex - 1] = new String[lastCellIndex];
for (int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex++) { //遍历列
Cell cell = row.getCell(cIndex);
String key = "";
NumberFormat numberFormat = NumberFormat.getNumberInstance();
numberFormat.setMaximumFractionDigits(0);
if (null != cell) {
switch (cell.getCellType()) {
// todo 这里的格式需要根据给定的调整,可以作为参数传递
case NUMERIC:
if (HSSFDateUtil.isCellDateFormatted(cell)) {
Date date = cell.getDateCellValue();
key = DateFormatUtils.format(date, "yyyy-MM-dd");
break;
}
// // 2015/8/21 这种类型的日期
// if (Pattern.matches("\\d{5}\\.0", cell.toString())) {
// Date date = cell.getDateCellValue();
// key = DateFormatUtils.format(date, "yyyy-MM-dd");
// break;
// }
double d = cell.getNumericCellValue();
String s = numberFormat.format(d);
if (s.indexOf(",") >= 0) {
// 这种方法对于自动加".0"的数字可直接解决
// 但如果是科学计数法的数字就转换成了带逗号的
// 例如:12345678912345的科学计数法是1.23457E+13
// 经过这个格式化后就变成了字符串“12,345,678,912,345”
// 这也并不是想要的结果,所以要将逗号去掉
s = s.replace(",", "");
}
key = s;
break;
case FORMULA: // 对于计算的日期列,无法和数字区分,只能用复制,粘贴为数值来读取
containsFormula = true;
// if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
// Date temp = cell.getDateCellValue();
// key = new SimpleDateFormat("yyyy-MM-dd").format(temp);
// } else {
// key = numberFormat.format(cell.getNumericCellValue());
// }
key = ((XSSFCell) cell).getRawValue();
break;
default:
key = cell.getStringCellValue().trim();
}
}
datas[rIndex - 1][cIndex] = key;
}
}
}
if (containsFormula) {
log.warn("excel包含计算列,返回数据可能存在差异");
}
return datas;
}
/**
* 判断整行是否为空
*
* @param row
* @return
*/
private static boolean isAllRowEmpty(Row row) {
if (Objects.isNull(row)) {
return true;
}
// 总共多少列
int count = 0;
// 判断多少个单元格为空
for (int index = 0; index < row.getLastCellNum(); index++) {
Cell cell = row.getCell(index);
if (cell == null || cell.getCellType() == CellType.BLANK || StringUtils.isEmpty
((cell + "").trim())) {
count++;
}
}
if (count == row.getLastCellNum()) {
return true;
}
return false;
}
}