赞
踩
最近在做导出功能,遇到了很多问题,专门记录一下,有其他导出问题的可以自行查看历史文章。
实际开发中会遇到客户的各种需求,今天主要说一下关于隐藏列的实现
如果只需要隐藏的话,直接在字段上面加一个注解:@ExcelIgnore
如果需要自定义隐藏或显示的话使用下面方法
excludeColumnFiledNames(Arrays.asList(“field3”))
案例一:
参考链接:https://blog.csdn.net/qq_24265439/article/details/129378438?fromshare=blogdetail
public static void main(String[] args) { // 生成文件路径 writeExcel("/Users/file/A.xlsx"); } public static void writeExcel(String filePath) { try { // 写入数据 List<DataDemo> dataList = new ArrayList<>(); for (int i = 0; i < 10; i++) { DataDemo data = new DataDemo(); data.setField1("A"+i); data.setField2("B"+i); data.setField3("C"+i); dataList.add(data); } // excludeColumnFiledNames 依据列忽略 // excludeColumnIndexes 指定删除列index // 还支持 includeColumnFiledNames 定义导出列 EasyExcel.write(filePath, DataDemo.class).excludeColumnFiledNames(Arrays.asList("field3")).sheet("用户").doWrite(dataList); } catch (Exception e) { e.printStackTrace(); } } @Data static class DataDemo { @ExcelProperty("标题 1") String field1; @ExcelProperty("标题 2") String field2; @ExcelProperty("标题 3") String field3; }
案例二:
需要导出的实体类,比如现在要隐藏图片那一列
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import com.alibaba.excel.converters.url.UrlImageConverter;
import lombok.Data;
import java.net.URL;
@Data
@ContentRowHeight(40)
@ColumnWidth(25)
public class ExportExcel {
@ExcelProperty(value = "Event Photo", converter = UrlImageConverter.class)
private URL imagePath;
}
导出方法:
public static void export(String exportType, String filename, List<?> dataResult, Class<?> clazz, HttpServletResponse response) { response.setStatus(200); OutputStream outputStream = null; ExcelWriter excelWriter = null; try { if (StringUtils.isBlank(filename)) { throw new RuntimeException("'filename' not null"); } String fileName = filename.concat(".xlsx"); response.setHeader("Content-Disposition", URLEncoder.encode(fileName, "utf-8")); outputStream = response.getOutputStream(); excelWriter = getExportExcelWriter(outputStream); WriteTable writeTable = EasyExcel.writerTable(0).head(clazz).needHead(true).build(); WriteSheet writeSheet = EasyExcel.writerSheet(fileName).build(); // 导出时隐藏图片列 if ("1".equals(exportType)) { String[] str = {"registerPhoto", "realTimePhoto"}; List<String> list = Arrays.asList(str); writeSheet.setExcludeColumnFieldNames(list); } // 写出数据 excelWriter.write(dataResult, writeSheet, writeTable); } catch (Exception e) { log.error("导出excel数据异常:", e); throw new RuntimeException(e); } finally { if (excelWriter != null) { excelWriter.finish(); } if (outputStream != null) { try { outputStream.flush(); outputStream.close(); } catch (IOException e) { log.error("导出数据关闭流异常", e); } } } }
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。