hutool导出excel支持下拉框数据超255字符
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.excel.StyleSet;
import com.ibmp.common.annotation.Excel;
import com.ibmp.common.constant.ExcelConsts;
import com.ibmp.common.exception.CustomException;
import com.ibmp.common.utils.file.FileTypeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Slf4j
public class ExcelUtils {
public static void export(int mergeColumn, String mergeText, List<Map<Object, Object>> maps, List<?> list, String excelName, Class clazz, HttpServletResponse response) {
try {
if (!list.isEmpty()) {
if (!list.get(0).getClass().equals(clazz)) {
log.error("数据类型与传入的集合数据类型不一致!数据类型:{}; 集合数据类型:{}", clazz, list.get(0).getClass());
throw new Exception("数据类型与传入的集合数据类型不一致!");
} else {
ExcelWriter writer = ExcelUtil.getBigWriter();
Field[] fields = clazz.getDeclaredFields();
List<String> fieldNames = new ArrayList<>();
List<String> cnNames = new ArrayList<>();
for (Field field : fields) {
if (!field.isAccessible()) {
field.setAccessible(true);
}
String fieldName = field.getName();
if (!"sid".equals(fieldName) && !"serialVersionUID".equals(fieldName) && !"ordernum".equals(fieldName)) {
fieldNames.add(fieldName);
}
boolean annotationPresent = field.isAnnotationPresent(Excel.class);
if (annotationPresent && !"sid".equals(fieldName)) {
String name = field.getAnnotation(Excel.class).name();
cnNames.add(name);
}
}
String[] fs = fieldNames.toArray(new String[0]);
String[] ns = cnNames.toArray(new String[0]);
for (int i = 0; i < ns.length; i++) {
writer.addHeaderAlias(fs[i], ns[i]);
}
Workbook workbook = writer.getWorkbook();
if (CollectionUtils.isNotEmpty(maps)) {
int index = 0;
for (Map<Object, Object> map : maps) {
Integer cellNo = (int) map.get("cellNo");
List<Object> cellList = (List<Object>) map.get("cellList");
index = index + 1;
selectListMore("sheet00" + cellNo, index, workbook, cellNo, cellNo, cellList.toArray(new String[cellList.size()]));
}
}
if (mergeColumn != -1) {
writer.merge(mergeColumn, mergeText);
}
CellStyle headCellStyle = writer.getCellStyle();
Font font = writer.createFont();
font.setFontName("宋体");
font.setFontHeightInPoints((short) 15);
headCellStyle.setFont(font);
StyleSet styleSet = new StyleSet(workbook);
styleSet.setWrapText();
writer.setStyleSet(styleSet);
writer.write(list, true);
writer.autoSizeColumnAll();
writer.setFreezePane(2);
ServletOutputStream out = response.getOutputStream();
try {
for (int i = 0; i < fieldNames.size(); i++) {
writer.setColumnWidth(i, 23);
}
response.setContentType(ExcelConsts.CONTENT_TYPE);
String ecodeFileName = URLEncoder.encode(excelName, "UTF-8");
response.setHeader(ExcelConsts.HEADER_S, ExcelConsts.RESPONSE_HEADER + ecodeFileName + ".xlsx");
writer.flush(out, true);
writer.close();
IoUtil.close(out);
} catch (IOException e) {
log.error(e.getMessage());
e.printStackTrace();
}
}
} else {
log.error("数据集合为空");
throw new Exception("数据集合为空");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void selectListMore(String sheetName, Integer index, Workbook workbook, int firstCol, int lastCol, String[] dataArray) {
Sheet hidden = workbook.createSheet(sheetName);
Cell cell = null;
for (int i = 0, length = dataArray.length; i < length; i++) {
String name = dataArray[i];
Row row = hidden.createRow(i);
cell = row.createCell(0);
cell.setCellValue(name);
}
Name namedCell = workbook.createName();
namedCell.setNameName(sheetName);
namedCell.setRefersToFormula(sheetName + "!$A$1:$A$" + dataArray.length);
String range = sheetName + "!$A$1:$A$" + dataArray.length;
CellRangeAddressList regions = new CellRangeAddressList(0, 1000000, firstCol, lastCol);
DataValidationHelper dataValidationHelper = hidden.getDataValidationHelper();
if (dataArray.length < 100 ) {
DataValidationConstraint constraint = dataValidationHelper.createExplicitListConstraint(dataArray);
DataValidation dataValidation = dataValidationHelper.createValidation(constraint, regions);
workbook.getSheetAt(0).addValidationData(dataValidation);
}else {
DataValidationConstraint dvConstraint = dataValidationHelper.createFormulaListConstraint(range);
DataValidation dataValidation = dataValidationHelper.createValidation(dvConstraint, regions);
workbook.getSheetAt(0).addValidationData(dataValidation);
}
workbook.setSheetHidden(index, true);
}
public static ExcelReader read(MultipartFile file, Integer sheet, Class clazz) {
return readCommon(file, sheet, clazz);
}
public static ExcelReader read(MultipartFile file, Class clazz) {
return readCommon(file, 0, clazz);
}
public static ExcelReader readCommon(MultipartFile file, Integer sheet, Class clazz) {
try {
InputStream inputStream = file.getInputStream();
if (!isExcelFile(file)) {
throw new CustomException("文件名格式不正确, 请使用后缀名为.xlsx的文件");
}
ExcelReader reader = ExcelUtil.getReader(inputStream, sheet);
Field[] fields = clazz.getDeclaredFields();
List<String> fieldNames = new ArrayList<>();
List<String> cnNames = new ArrayList<>();
for (Field field : fields) {
if (!field.isAccessible()) {
field.setAccessible(true);
}
String fieldName = field.getName();
if (!"sid".equals(fieldName) && !"serialVersionUID".equals(fieldName) && !"ordernum".equals(fieldName)) {
fieldNames.add(fieldName);
}
boolean annotationPresent = field.isAnnotationPresent(Excel.class);
if (annotationPresent && !"sid".equals(fieldName)) {
String name = field.getAnnotation(Excel.class).name();
cnNames.add(name);
}
}
String[] fs = fieldNames.toArray(new String[0]);
String[] ns = cnNames.toArray(new String[0]);
for (int i = 0; i < fs.length; i++) {
reader.addHeaderAlias(ns[i], fs[i]);
}
return reader;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static Workbook readExcelSheet(MultipartFile file) {
try {
InputStream inputStream = file.getInputStream();
if (!isExcelFile(file)) {
throw new CustomException("文件名格式不正确, 请使用后缀名为.xlsx的文件");
}
ExcelReader reader = ExcelUtil.getReader(inputStream);
return reader.getWorkbook();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static boolean isExcelFile(MultipartFile file) throws IOException {
if (file.isEmpty()) {
throw new CustomException("文件不能为空");
}
String filename = file.getOriginalFilename();
String header = FileTypeUtils.getFileHeader(file.getInputStream());
return (filename.endsWith(ExcelConsts.EXCEL_VERSION_XLSX) || filename.endsWith(ExcelConsts.EXCEL_VERSION_XLS)) &&
(header.contains(ExcelConsts.XLS_HEADER) || header.contains(ExcelConsts.XLSX_HEADER));
}
public static Workbook getXSSFWorkbook(String sheetName, String[] title, String[][] values, Workbook wb) {
return getXSSFWorkbook(sheetName, title, null, values, wb);
}
public static Workbook getXSSFWorkbook(String sheetName, String[] title, int[] width, String[][] values, Workbook wb) {
if (wb == null) {
wb = new XSSFWorkbook();
}
Sheet sheet = wb.createSheet(sheetName);
sheet.createFreezePane(0, 1, 0, 1);
Row row = sheet.createRow(0);
CellStyle style = wb.createCellStyle();
Font font = wb.createFont();
font.setBold(true);
style.setFont(font);
Cell cell;
for (int i = 0; i < title.length; i++) {
cell = row.createCell(i);
cell.setCellValue(title[i]);
cell.setCellStyle(style);
if (width != null) {
sheet.setColumnWidth(i, width[i]);
}
}
String s;
for (int i = 0; i < values.length; i++) {
row = sheet.createRow(i + 1);
for (int j = 0; j < values[i].length; j++) {
s = values[i][j];
s = StringUtils.isBlank(s) ? "" : (StringUtils.equals("null", s) ? "" : s);
row.createCell(j).setCellValue(s);
}
}
return wb;
}
public static void margeCell(Sheet sheet, int startRow, int colNum) {
String content = "";
int index = startRow;
for (int i = startRow; i <= sheet.getLastRowNum(); i++) {
String value = sheet.getRow(i).getCell(colNum).getStringCellValue();
if (!StringUtils.equals(content, value)) {
if (i - index > 1) {
CellRangeAddress region = new CellRangeAddress(index, i - 1, colNum, colNum);
sheet.addMergedRegion(region);
}
index = i;
content = value;
} else {
if (i == sheet.getLastRowNum() && i - index > 1) {
CellRangeAddress region = new CellRangeAddress(index, i, colNum, colNum);
sheet.addMergedRegion(region);
}
}
}
}
public static void setResponse(HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
String _filaName = new String((fileName + ".xlsx").getBytes("gb2312"), "iso8859-1");
response.setHeader("Content-disposition", "attachment;filename=" + _filaName);
}
}