EasyExcel动态导出数据

EasyExcel动态导出数据
头的数据格式设置为 List<List<String>>  并且具体的数据格式也设置为List<List<String>>具体的数据和表头⼀⼀对应
public <T> void exportTerminalnew(ExportHandlerDS handler, List<String> excelHeaders, String  staffCode, FastFileStorageClient fastFileClient, String fdfsUrl, IReportService reportExportDetailService, Long id) {        ......
//根据前端选择的字段⽣成表头
List<List<String>> head = head(excelHeaders);
WriteSheet writeSheet = EasyExcel.writerSheet().head(head).
//设置样式
registerWriteHandler(setExcelStyle()).
//⾃定义列宽
registerWriteHandler(new Custemhandler()).
//registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).
//固定表头
registerWriteHandler(new CustomSheetWriteHandler()).
//动态合并单元格
registerWriteHandler(new ExcelCellMergeStrategy()).
build();
//设置列宽?
// writeSheet.setColumnWidthMap();
ExcelWriter excelWriter = EasyExcel.write(baos).excelType(ExcelTypeEnum.XLSX).build();
WriteTable build = EasyExcel.writerTable(0).needHead(false).build();
.
....
//根据传⼊的字段筛选导出哪些数据
List<List<String>> body = getBody(list, excelHeaders);
excelWriter.write(body,writeSheet,build);
excelWriter.finish();
StorePath storePath=null;
if(!selImage){
final ByteArrayInputStream byteIs = new ByteArray());
//⽣成的⽂件上传到fast DFS系统上福克斯熄火门
storePath = fastFileClient.uploadFile(byteIs, byteIs.available(), Value().substring(1), null);
}else {
StringBuilder fileNewPath=new StringBuilder();
final ByteArrayInputStream byteIs = new ByteArrayInputStream(getFile(baos,fileNewPath,list,staffCode));
//⽣成的⽂件上传到fast DFS系统上
storePath = fastFileClient.uploadFile(byteIs, byteIs.available(), "zip", null);
// 删除⽂件夹及⽂件
path.String());
}
String fullPath = FullPath();
filePath = fdfsUrl + "/" + fullPath;
// 1: 执⾏成功 -1: 执⾏失败
if (StringUtils.isNotBlank(fullPath)) {
reportExportDetailDTO.setStatus(1);
reportExportDetailDTO.setFilePath(filePath);
} else {
reportExportDetailDTO.setStatus(-1);
}
} catch (Exception e) {
reportExportDetailDTO.setStatus(-1);
<("导出Excel报表⽂件出错",e);
} finally {
if(CollectionUtils.isNotEmpty(path)){
//删除⽂件
delFile(path);
<("要删除的⽬录地址:"+path);
}
reportExportDetailDTO.setId(id);
reportExportDetailService.updateExport(reportExportDetailDTO);
}
}
**
* 设置excel样式
* @return
*/
private HorizontalCellStyleStrategy setExcelStyle(){
// 表头策略
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
WriteFont writeFont=new WriteFont();
writeFont.setFontName("宋体");
writeFont.setFontHeightInPoints((short) 11);
分享的价值和意义
//加粗
writeFont.setBold(true);
headWriteCellStyle.setWriteFont(writeFont);
//内容样式策略
WriteCellStyle contextWriteeCellStyle=new WriteCellStyle();
/
/设置⽔平居中
contextWriteeCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
// 这个策略是头是头的样式内容是内容的样式其他的策略可以⾃⼰实现
HorizontalCellStyleStrategy horizontalCellStyleStrategy =
new HorizontalCellStyleStrategy(headWriteCellStyle,contextWriteeCellStyle);
return horizontalCellStyleStrategy;
}
/**
easyexcel提供的⾃动列宽不能满⾜需求,只能⾃⼰根据业务要求重写
* @description: EasyExcel设置列宽
* @author: qiuqingxin
* @create: 2020-08-07 15:49
**/
public class Custemhandler extends AbstractColumnWidthStyleStrategy {
private static final int MAX_COLUMN_WIDTH = 50;
public Custemhandler() {
}
@Override
protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<CellData> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
int columnWidth=20;
if (isHead ) {
if (StringCellValue().equals("照⽚类型")){
columnWidth=20;
}
if (StringCellValue().equals("当前位置")){
columnWidth=50;
}
if (StringCellValue().equals("备注")){
columnWidth=30;
}
......
}
}
}
/**
* @description: easyExcel
* @author: qiuqingxin
* @create: 2020-06-16 11:29
**/
public class CustomSheetWriteHandler implements SheetWriteHandler {
@Override
public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
}
@Override
public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
//固定表头
}
}
/**
* @description: ⾃定义合并单元格
* @author: qiuqingxin
* @create: 2020-08-07 16:38
**/
public class ExcelCellMergeStrategy implements CellWriteHandler {
private int fileColumnIndex = -1;
private int imageColumnIndex = -1;
private String  regEx="[^0-9]";
@Override
public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead) {
}
@Override
public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
}
/**
每在excel中写⼊⼀个单元格数据都会调⽤次⽅法
**/
@Override
public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<CellData> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) { if (isHead) {
if ("附件".StringCellValue())) {
fileColumnIndex = ColumnIndex();
return;
}
if ("现场照⽚".StringCellValue())) {
imageColumnIndex = ColumnIndex();
return;
}
} else {
if (imageColumnIndex != -1) {
//到附件所在的列
if (ColumnIndex() == imageColumnIndex + 1) {
// Sheet sheet = Sheet();
Row row = Row();
Cell cell1 = Cell(imageColumnIndex);
Cell cell2 = Cell(imageColumnIndex + 1);
String imageUrl = StringCellValue();
String imageName = StringCellValue();
if (!isZero(imageName)) {
cell1.setCellFormula( "HYPERLINK(\"" + imageUrl + "\",\"" + imageName + "\")");
}else {
cell1.setCellValue("");
}
}
}
if (fileColumnIndex != -1) {
if (null == Row().getCell(fileColumnIndex)) {
//到附件所在的列
if (ColumnIndex() == fileColumnIndex + 2) {
// Sheet sheet = Sheet();
Row row = Row();
Cell cell3 = ateCell(fileColumnIndex);
Cell cell1 = Cell(fileColumnIndex + 1);
Cell cell2 = Cell(fileColumnIndex + 2);
String fileUrl = StringCellValue();
cell3.setCellFormula("HYPERLINK(\"" + fileUrl + "\",\"" + StringCellValue() + "\")");
}
if (ColumnIndex() == fileColumnIndex + 1) {
// Sheet sheet = Sheet();
Row row = Row();
Cell cell1 = Cell(fileColumnIndex );
Cell cell2 = Cell(fileColumnIndex + 1);
String fileUrl = StringCellValue();
cell1.setCellFormula("HYPERLINK(\"" + fileUrl + "\",\"" + StringCellValue() + "\")");
}
}
}
}
移位寄存器及其应用
}
private boolean isZero(String value){
Pattern p = Patternpile(regEx);
Matcher m = p.matcher(value);
String trim = m.replaceAll("").trim();
return trim.equals("0")?true:false;
}
}
private List<List<String>> getBody(List<DsTerminalUploadExcel> list3,List<String> excelHeaders )throws Exception{
Map<Integer,String> map=new HashMap<>();
List<List<String>> lists=new ArrayList<>();
Integer index=1;
for (String excelHeader : excelHeaders) {
map.put(index++,excelHeader);
}
int size = map.size();
for (DsTerminalUploadExcel dsTerminalUploadExcel : list3) {
List<String> data=new ArrayList<>();
for (int i =0;i<size;i++){
if ((i+1).equals("image")){
String ImagePaths()!=ImagePaths().size()+"张)":"0张)";
value2="点击查看图⽚("+value2;
data.add(value2);
value2=null==StaffName()?
"/"+ReportDate().substring(0,10)+"_"+Id():
小辰"/"+StaffName()+"_"+ReportDate().substring(0,10)+"_"+Id();            value2="images/"+value2;
data.add(value2);
}else {
String value=(String)getValue((i+1));
data.add(value);
if ((i+1).equals("fileName")){
String value2=(String)getValue(dsTerminalUploadExcel,"filePath");
data.add(value2);
}
}
}
lists.add(data);
}
return lists;
}
//反射调⽤get⽅法
public static Object getValue(Object dto,String name) throws Exception {
String s = name.substring(0, 1).toUpperCase();
String substring = name.substring(1);
Method method = Class().getMethod("get" + s + substring);
return  method.invoke(dto);
}
//将数据⽣成字节数组
private byte[] getFile(ByteArrayOutputStream baos,StringBuilder fileNewPath,List<DsTerminalUploadExcel> list3,
String staffCode) throws Exception {
// String path = "D:\\sss\\"+staffCode+"_"+(new SimpleDateFormat("yyMMddHHmmss").format(new Date()))+"\\";
String path = "/data/file/"+staffCode+"_"+(new SimpleDateFormat("yyMMddHHmmss").format(new Date()))+"/";
<("获取的路径:"+path);
String fileName=""+System.currentTimeMillis();
String  filePath=path+fileName;
fileNewPath.append(path);
File file = new File(filePath);
if (!ists()){
file.mkdirs();
}
FileOutputStream fileOutputStream=new FileOutputStream(filePath+"/"+System.currentTimeMillis()+Value());
fileOutputStream.ByteArray());
fileOutputStream.close();
genImages(list3,filePath);
<("filePath"+filePath);
return setZip(filePath,path,fileName);
}
private void genImages(List<DsTerminalUploadExcel> list3,String filePath) throws Exception {
File file = new File(filePath + "/images");
if (!ists()){
file.mkdirs();
}
for (DsTerminalUploadExcel dsTerminalUploadExcel : list3) {
List<String> imagePaths = ImagePaths();
if (null==imagePaths||imagePaths.size()==0){
}
String imagepath=null==StaffName()?
"/"+ReportDate().substring(0,10)+"_"+Id():
"/"+StaffName()+"_"+ReportDate().substring(0,10)+"_"+Id();        Path()+imagepath;
File file1 = new File(imagepath);
if (!ists()) file1.mkdirs();
for (String imagePath : imagePaths) {
String ext = imagePath.substring(imagePath.lastIndexOf("/") + 1);
File file2 = new Path() + "/" + ext);
FileOutputStream fileOutputStream = new FileOutputStream(file2);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
//发送HTTP请求并指定返回的数据为byte数组
RestTemplate restTemplate = new RestTemplate();
byte[] forObject = ForObject(imagePath, byte[].class);
bufferedOutputStream.write(forObject);
bufferedOutputStream.flush();
fileOutputStream.close();
bufferedOutputStream.close();
}
}
}
private byte[] setZip(String allPath, String path, String fileName) throws Exception {
String newzipPath = path + fileName + ".zip";
File file = new File(newzipPath);
FileOutputStream fileOutputStream = new FileOutputStream(file);
   //压缩⼯具类
byte[] aByte = Byte(allPath, fileOutputStream, true, file);
fileOutputStream.close();
格兰杰因果关系检验return aByte;
千代富士}

本文发布于:2024-09-22 16:53:12,感谢您对本站的认可!

本文链接:https://www.17tex.com/xueshu/292738.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:数据   样式   导出
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2024 Comsenz Inc.Powered by © 易纺专利技术学习网 豫ICP备2022007602号 豫公网安备41160202000603 站长QQ:729038198 关于我们 投诉建议