报表导出

This commit is contained in:
jing's 2023-12-06 18:09:34 +08:00
parent eaeee81dff
commit ee5f977825
12 changed files with 1371 additions and 131 deletions

View File

@ -2,11 +2,17 @@ package com.nflg.product.bomnew.api.user;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.nflg.product.base.core.conmon.util.SessionUtil;
import com.nflg.product.base.core.exception.NflgBusinessException;
import com.nflg.product.bomnew.constant.OptionalBomConstant;
import com.nflg.product.bomnew.excel.EasyExcelUtil;
import com.nflg.product.bomnew.excel.ExportDeviceHelper;
import com.nflg.product.bomnew.excel.PreviewProduceExcelExportHelper;
import com.nflg.product.bomnew.excel.PreviewTmpExcelExportHelper;
import com.nflg.product.bomnew.pojo.dto.*;
import com.nflg.product.bomnew.pojo.query.OptionalEbomConfigListQuery;
import com.nflg.product.bomnew.pojo.query.OptionalEbomImportChildQuery;
@ -28,9 +34,13 @@ import com.nflg.product.base.core.api.BaseApi;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.Objects;
/**
*
@ -175,27 +185,27 @@ public class OptionalEbomApi extends BaseApi {
if (dto == null) {
return ResultVO.error("添加数据空");
}
if (dto.getPartType() != OptionalBomConstant.PartTypeEnum.PART_TYPE_RADIO.getValue() && dto.getPartType() != OptionalBomConstant.PartTypeEnum.PART_TYPE_CHECBOX.getValue()) {
if ( !Objects.equals(dto.getPartType(), OptionalBomConstant.PartTypeEnum.PART_TYPE_RADIO.getValue()) && !Objects.equals(dto.getPartType() , OptionalBomConstant.PartTypeEnum.PART_TYPE_CHECBOX.getValue())) {
return ResultVO.error("数据{partType}类型错误");
}
if(dto.getRootRowId()==null ){
return ResultVO.error("rootRowId不能为空");
}
if(dto.getPartType() == OptionalBomConstant.PartTypeEnum.PART_TYPE_RADIO.getValue() &&( dto.getParentRowId()==null || dto.getParentRowId()==0)){
if( Objects.equals(dto.getPartType() , OptionalBomConstant.PartTypeEnum.PART_TYPE_RADIO.getValue()) &&( dto.getParentRowId()==null )){
return ResultVO.error("标配件parentRowId不能为空");
}
if(dto.getPartType() == OptionalBomConstant.PartTypeEnum.PART_TYPE_CHECBOX.getValue()){
if(Objects.equals(dto.getPartType() , OptionalBomConstant.PartTypeEnum.PART_TYPE_CHECBOX.getValue())){
dto.setParentRowId(null);
}
if(this.optionalEbomImportChildService.insertOption(dto)){
return ResultVO.success(true);
}else{
return ResultVO.error(STATE.Error,"添加失败");
return ResultVO.error(STATE.Error,"添加配置失败");
}
}
@ -220,14 +230,6 @@ public class OptionalEbomApi extends BaseApi {
@PostMapping("getTmpListPage")
@ApiOperation("暂存方案分页数据")
public ResultVO<IPage<OptionalEbomConfigVO>> getTmpListPage(@RequestBody OptionalEbomConfigListQuery query) {
@ -319,7 +321,75 @@ public class OptionalEbomApi extends BaseApi {
}
@GetMapping("exportPreview")
@ApiOperation("预览导出")
public void exportPreview(HttpServletResponse response,@ApiParam("暂存id") @RequestParam("rowId") Long rowId) throws Exception {
OptionalEbomConfigTmpAggregVO voObj= aggregOptionConfigService.publishPreviewTree(rowId);
String fileName= StrUtil.format("{}预览导出{}",voObj.getDeviceInfo().getDeviceName(),System.currentTimeMillis());
if(voObj!=null){
EasyExcelUtil.setExportHeader(response,fileName);
PreviewTmpExcelExportHelper helper=new PreviewTmpExcelExportHelper();
helper.export(response.getOutputStream(),voObj);
}
}
@GetMapping("exportProducePreview")
@ApiOperation("生产预览导出")
public void exportProducePreview(HttpServletResponse response,@ApiParam("暂存id") @RequestParam("rowId") Long rowId) throws Exception {
OptionalEbomConfigTmpAggregVO voObj= aggregOptionConfigService.publishPreviewTree(rowId);
String fileName= StrUtil.format("{}生产预览导出{}",voObj.getDeviceInfo().getDeviceName(),System.currentTimeMillis());
if(voObj!=null){
EasyExcelUtil.setExportHeader(response,fileName);
PreviewProduceExcelExportHelper helper=new PreviewProduceExcelExportHelper();
helper.export(response.getOutputStream(),voObj);
}
}
@GetMapping("exportDeviceMaterial")
@ApiOperation("设备物料导出")
public void exportDeviceMaterial(HttpServletResponse response,@ApiParam("设备id") @RequestParam("rowId") Long rowId) throws Exception {
OptionalEbomImportChildQuery query=new OptionalEbomImportChildQuery();
query.setRootRowId(rowId);
OptionalEbomConfigAggregVO voObj= aggregOptionConfigService.ebomEditTree(query);
String fileName= StrUtil.format("{}{}",voObj.getDeviceInfo().getDeviceNo(),voObj.getDeviceInfo().getDeviceName());
if(voObj!=null){
EasyExcelUtil.setExportHeader(response,fileName);
ExportDeviceHelper helper=new ExportDeviceHelper();
OutputStream outputStream= response.getOutputStream();
helper.export(outputStream,voObj);
outputStream.flush();
}
}
@GetMapping("downDeviceExcelTemplate")
@ApiOperation("导入数据模版下载")
public void downImportExcelTemplate(HttpServletResponse response ) throws Exception {
try {
//获取要下载的模板名称
String fileName = "importDataTemplate.xlsx";
EasyExcelUtil.setExportHeader(response,"移动破数据导入模版");
//模板文件存放路径
String filePath = getClass().getResource("/template/"+fileName).getPath();
//IO流处理模板
FileInputStream input = new FileInputStream(filePath);
OutputStream out = response.getOutputStream();
byte[] b = new byte[2048];
int len;
while ((len = input.read(b)) != -1) {
out.write(b,0,len);
}
//返回请求访问的结果
response.setHeader("Content-Length", String.valueOf(input.getChannel().size()));
input.close();
} catch (Exception e) {
}
}

View File

@ -31,7 +31,7 @@ public class OptionalBomConstant {
@AllArgsConstructor
@Getter
public enum SourceTypeEnum implements ValueEnum<Integer> {
SOURCE_EXCEL(0, "excel"),
SOURCE_EXCEL(0, "template"),
SOURCE_INPUT(1, "手动录入");
private final Integer value;
private final String description;

View File

@ -0,0 +1,151 @@
package com.nflg.product.bomnew.excel;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
public class EasyExcelUtil {
/**
* 默认头样式
*
* @return WriteCellStyle
*/
public static WriteCellStyle getHeadStyle() {
// 头的策略
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
// 背景色, 设置为白色也是默认颜色
headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
// 字体
WriteFont headWriteFont = new WriteFont();
//设置字体名字
headWriteFont.setFontName("宋体");
//设置字体大小
headWriteFont.setFontHeightInPoints((short) 11);
//字体加粗
headWriteFont.setBold(false);
//在样式用应用设置的字体;
headWriteCellStyle.setWriteFont(headWriteFont);
//设置底边框;
headWriteCellStyle.setBorderBottom(BorderStyle.THIN);
//设置底边框颜色;
headWriteCellStyle.setBottomBorderColor((short) 0);
//设置左边框;
headWriteCellStyle.setBorderLeft(BorderStyle.THIN);
//设置左边框颜色;
headWriteCellStyle.setLeftBorderColor((short) 0);
//设置右边框;
headWriteCellStyle.setBorderRight(BorderStyle.THIN);
//设置右边框颜色;
headWriteCellStyle.setRightBorderColor((short) 0);
//设置顶边框;
headWriteCellStyle.setBorderTop(BorderStyle.THIN);
//设置顶边框颜色;
headWriteCellStyle.setTopBorderColor((short) 0);
//设置自动换行;
headWriteCellStyle.setWrapped(false);
//设置水平对齐的样式为居中对齐;
headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
//设置垂直对齐的样式为居中对齐;
headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
return headWriteCellStyle;
}
/**
* 默认行样式
*
* @return WriteCellStyle
*/
public static WriteCellStyle getBodyStyle() {
WriteCellStyle bodyWriteCellStyle = new WriteCellStyle();
//设置底边框;
bodyWriteCellStyle.setBorderBottom(BorderStyle.THIN);
//设置底边框颜色;
bodyWriteCellStyle.setBottomBorderColor((short) 0);
//设置左边框;
bodyWriteCellStyle.setBorderLeft(BorderStyle.THIN);
//设置左边框颜色;
bodyWriteCellStyle.setLeftBorderColor((short) 0);
//设置右边框;
bodyWriteCellStyle.setBorderRight(BorderStyle.THIN);
//设置右边框颜色;
bodyWriteCellStyle.setRightBorderColor((short) 0);
//设置顶边框;
bodyWriteCellStyle.setBorderTop(BorderStyle.THIN);
//设置顶边框颜色;
bodyWriteCellStyle.setTopBorderColor((short) 0);
// 字体
WriteFont font = new WriteFont();
//设置字体名字
font.setFontName("宋体");
//设置字体大小
font.setFontHeightInPoints((short) 11);
//字体加粗
font.setBold(false);
bodyWriteCellStyle.setWriteFont(font);
//设置自动换行;
bodyWriteCellStyle.setWrapped(true);
//设置水平对齐的样式为居中对齐;
bodyWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
//设置垂直对齐的样式为居中对齐;
bodyWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
return bodyWriteCellStyle;
}
/**
* 获取头行默认样式
*
* @return HorizontalCellStyleStrategy
*/
public static HorizontalCellStyleStrategy getDefaultStyle() {
return new HorizontalCellStyleStrategy(EasyExcelUtil.getHeadStyle(), EasyExcelUtil.getBodyStyle());
}
public static <T> void write(List<List<String>> header, List<T> data, OutputStream filePath, String sheetName, List<CellWriteHandler> handlers) {
ExcelWriter excelWriter = EasyExcel.write(filePath)
// 表头内容样式设置
.autoCloseStream(Boolean.FALSE)
.build();
ExcelWriterSheetBuilder excelWriterSheetBuilder = EasyExcel.writerSheet(0, sheetName).head(header);
for (CellWriteHandler handler :
handlers) {
excelWriterSheetBuilder.registerWriteHandler(handler);
}
excelWriter.write(data, excelWriterSheetBuilder.build());
excelWriter.finish();
}
public static void setExportHeader(HttpServletResponse response, String fileName) throws Exception {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
}
}

View File

@ -0,0 +1,18 @@
package com.nflg.product.bomnew.excel;
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
@Data
public class ExcelExportField extends ImportExcelField {
@ExcelProperty(value="",index = 3)
private String cellFourth;
}

View File

@ -1,11 +1,16 @@
package com.nflg.product.bomnew.excel;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.util.StyleUtil;
import com.alibaba.excel.write.handler.AbstractCellWriteHandler;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
@ -13,154 +18,336 @@ import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.nflg.product.bomnew.pojo.vo.OptionalEbomConfigAggregVO;
import com.nflg.product.bomnew.pojo.vo.OptionalEbomImportChildVO;
import com.nflg.product.bomnew.pojo.vo.OptionalEbomImportVO;
import com.nflg.product.bomnew.pojo.vo.OptionalEbomMainVO;
import com.nflg.product.bomnew.pojo.vo.*;
import org.apache.poi.ss.usermodel.*;
import com.alibaba.excel.write.merge.OnceAbsoluteMergeStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Vector;
import java.io.OutputStream;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
public class ExportDeviceHelper {
public void buildHeader(int maxColumn, OptionalEbomMainVO header, WriteSheet sheet, ExcelWriter writer, AtomicInteger tableNoCounting) {
public void export(OutputStream filePath, OptionalEbomConfigAggregVO voObj) {
//使用一个计数器记录当前已经写了几个表格
AtomicInteger tableNoCounting = new AtomicInteger(0);
ExcelWriter writer = EasyExcel.write(filePath)//指定写入的流
.excelType(ExcelTypeEnum.XLSX)//指定Excel文件类型如xlsxxls
.autoCloseStream(Boolean.FALSE)
.build();
WriteSheet sheet = EasyExcel
.writerSheet("EBOM导出")//指定写入的sheet
.needHead(false)//是否需要head
.build();
buildHeader(2, voObj.getDeviceInfo(), sheet, writer, tableNoCounting);
buildList(voObj.getSingleList(), sheet, writer, tableNoCounting);
writer.finish();
}
public static class ColumnMergeStrategy implements CellWriteHandler {
private int[] mergeColumnIndex;
private int mergeRowIndex;
public ColumnMergeStrategy(int mergeRowIndex, int[] mergeColumnIndex) {
this.mergeRowIndex = mergeRowIndex;
this.mergeColumnIndex = mergeColumnIndex;
}
@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) {
}
@Override
public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
if (!isHead) {
//当前行
int curRowIndex = cell.getRowIndex();
//当前列
int curColIndex = cell.getColumnIndex();
// System.out.println(StrUtil.format("curRowIndex {} curColIndex {}",curRowIndex,curColIndex));
if (curRowIndex > mergeRowIndex) {
for (int i = 0; i < mergeColumnIndex.length; i++) {
if (curColIndex == mergeColumnIndex[i]) {
mergeWithPrevRow(writeSheetHolder, cell, curRowIndex, curColIndex);
break;
}
}
}
}
}
/**
* 当前单元格向上合并
*
* @param writeSheetHolder
* @param cell 当前单元格
* @param curRowIndex 当前行
* @param curColIndex 当前列
*/
private void mergeWithPrevRow(WriteSheetHolder writeSheetHolder, Cell cell, int curRowIndex, int curColIndex) {
Object curData = cell.getCellTypeEnum() == CellType.STRING ? cell.getStringCellValue() : cell.getNumericCellValue();
Cell preCell = cell.getSheet().getRow(curRowIndex - 1).getCell(curColIndex);
Object preData = preCell.getCellTypeEnum() == CellType.STRING ? preCell.getStringCellValue() : preCell.getNumericCellValue();
// 将当前单元格数据与上一个单元格数据比较
Boolean dataBool = preData.equals(curData);
if (dataBool) {
Sheet sheet = writeSheetHolder.getSheet();
List<CellRangeAddress> mergeRegions = sheet.getMergedRegions();
boolean isMerged = false;
for (int i = 0; i < mergeRegions.size() && !isMerged; i++) {
CellRangeAddress cellRangeAddr = mergeRegions.get(i);
// 若上一个单元格已经被合并则先移出原有的合并单元再重新添加合并单元
if (cellRangeAddr.isInRange(curRowIndex - 1, curColIndex)) {
sheet.removeMergedRegion(i);
cellRangeAddr.setLastRow(curRowIndex);
sheet.addMergedRegion(cellRangeAddr);
isMerged = true;
}
}
// 若上一个单元格未被合并则新增合并单元
if (!isMerged) {
CellRangeAddress cellRangeAddress = new CellRangeAddress(curRowIndex - 1, curRowIndex, curColIndex, curColIndex);
sheet.addMergedRegion(cellRangeAddress);
}
}
}
}
public class HeaderStyleCustomCellWriteHandler extends AbstractCellWriteHandler {
@Override
public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
Row row, Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead) {
// 设置行高
int rowIndex = row.getRowNum();
short height = 400;
row.setHeight(height);
}
private CellStyle initCellStyle(Workbook workbook) {
WriteCellStyle contentWriteCellStyle = EasyExcelUtil.getHeadStyle();
CellStyle headWriteCellStyle = StyleUtil.buildCellStyle(workbook, null, contentWriteCellStyle);
return headWriteCellStyle;
}
@Override
public void afterCellDispose(CellWriteHandlerContext context) {
Cell cell = context.getCell();
int rowIndex = cell.getRowIndex();
int cellIndex = cell.getColumnIndex();
// 自定义宽度处理
if (!context.getHead()) {
int columnWidth = cell.getStringCellValue().getBytes().length;
switch (cellIndex) {
case 0:
columnWidth = 30;
break;
case 1:
columnWidth = 40;
break;
case 2:
columnWidth = 80;
break;
default:
break;
}
if (columnWidth > 255) {
columnWidth = 255;
}
context.getWriteSheetHolder().getSheet().setColumnWidth(cellIndex, columnWidth * 256);
}
// 自定义表头样式处理
if (context.getHead() != null && context.getHead().booleanValue()) {
WriteSheetHolder writeSheetHolder = context.getWriteSheetHolder();
Workbook workbook = writeSheetHolder.getSheet().getWorkbook();
CellStyle cellStyle = initCellStyle(workbook);
XSSFCellStyle xssfCellStyle = (XSSFCellStyle) workbook.createCellStyle();
xssfCellStyle.cloneStyleFrom(cellStyle);
xssfCellStyle.getFont().setBold(true);
xssfCellStyle.setAlignment(HorizontalAlignment.LEFT);
xssfCellStyle.setFillForegroundColor(new XSSFColor(new java.awt.Color(255, 255, 0)));
xssfCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cell.setCellStyle(xssfCellStyle);
context.getFirstCellData().setWriteCellStyle(null); //必须
}
if (context.getHead() == null || !context.getHead().booleanValue()) {
if (cellIndex == 1 || cellIndex == 2) {
WriteSheetHolder writeSheetHolder = context.getWriteSheetHolder();
Workbook workbook = writeSheetHolder.getSheet().getWorkbook();
// WriteCellStyle contentWriteCellStyle = EasyExcelUtil.getBodyStyle();
// CellStyle cellStyle = StyleUtil.buildCellStyle(workbook, null, contentWriteCellStyle);
//
// XSSFCellStyle xssfCellStyle = (XSSFCellStyle) workbook.createCellStyle();
// xssfCellStyle.cloneStyleFrom(cellStyle);
// xssfCellStyle.setAlignment(HorizontalAlignment.LEFT);
// xssfCellStyle.setFont(new XSSFFont());
// xssfCellStyle.getFont().setBold(false);
// xssfCellStyle.getFont().setFontName("宋体");
// xssfCellStyle.getFont().setFontHeightInPoints((short) 11);
//
// context.getFirstCellData().setWriteCellStyle(null); //必须
// cell.setCellStyle(xssfCellStyle);
WriteCellData<?> writeCellData = context.getFirstCellData();
WriteCellStyle customCellStyle = EasyExcelUtil.getBodyStyle();
WriteFont customFont = new WriteFont();
customFont.setFontName("宋体");
customFont.setFontHeightInPoints((short) 11);
customFont.setBold(false);
customCellStyle.setWriteFont(customFont);
customCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
WriteCellStyle.merge(customCellStyle, writeCellData.getOrCreateStyle());
}
}
}
}
public List<List<String>> getHeader(String headStr) {
String customer = headStr;
List<List<String>> list = new ArrayList<List<String>>();
List<String> head0 = new ArrayList<String>();
head0.add(customer);
List<String> head1 = new ArrayList<String>();
head1.add(customer);
List<String> head2 = new ArrayList<String>();
head2.add(customer);
list.add(head0);
list.add(head1);
list.add(head2);
return list;
}
public void buildHeader(int maxColumn, OptionalEbomMainVO header, WriteSheet sheet, ExcelWriter writer, AtomicInteger tableNoCounting) {
if (header == null) {
return;
}
WriteCellStyle body = EasyExcelUtil.getBodyStyle();
if (body.getWriteFont() != null) {
body.getWriteFont().setBold(true);
}
//自定义到处样式
WriteCellStyle cellStyle = new WriteCellStyle();
//水平居中
cellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
WriteFont writeFont = new WriteFont();
//加粗
writeFont.setBold(Boolean.TRUE);
//字体大小
writeFont.setFontHeightInPoints((short) 14);
cellStyle.setWriteFont(writeFont);
WriteTable table = EasyExcel
.writerTable(tableNoCounting.get())
.needHead(Boolean.FALSE)
// .registerWriteHandler(
// new OnceAbsoluteMergeStrategy(tableNoCounting.get() - 1, tableNoCounting.getAndIncrement() - 1, 0, maxColumn)
// )
.registerWriteHandler(new HorizontalCellStyleStrategy(cellStyle, cellStyle))
.registerWriteHandler(
new OnceAbsoluteMergeStrategy(tableNoCounting.get(), tableNoCounting.get(), 0, maxColumn)
)
.registerWriteHandler(new CellWriteHandler() {
@Override
public void afterCellDispose(CellWriteHandlerContext context) {
Cell cell = context.getCell();
int rowIndex = cell.getRowIndex();
int cellIndex = cell.getColumnIndex();
if (rowIndex == 0) {
short height = 500;
context.getRow().setHeight(height);
}
}
})
.registerWriteHandler(new HorizontalCellStyleStrategy(EasyExcelUtil.getHeadStyle(), body))
.build();
List<String> cellList = new ArrayList<>();
cellList.add(String.format("%s %s", header.getDeviceNo(), header.getDeviceName()));
List<List<String>> rowList = new ArrayList<>();
rowList.add(cellList);
//写入表格
writer.write(rowList, sheet, table);
}
/**
* 构建列表部分
*/
public void buildList( List<OptionalEbomImportVO > listTable, WriteSheet sheet, ExcelWriter writer, AtomicInteger tableNoCounting) {
//自定义样式
WriteCellStyle headStyle = new WriteCellStyle();
//设置header背景颜色为透明
// headStyle.setFillForegroundColor(IndexedColors.AUTOMATIC.getIndex());
//水平居中
headStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
//上下左右四个边框
headStyle.setBorderBottom(BorderStyle.THIN);
headStyle.setBorderTop(BorderStyle.THIN);
headStyle.setBorderLeft(BorderStyle.THIN);
headStyle.setBorderRight(BorderStyle.THIN);
WriteFont writeFont = new WriteFont();
//字体加粗
writeFont.setBold(Boolean.TRUE);
//字号
writeFont.setFontHeightInPoints((short) 12);
headStyle.setWriteFont(writeFont);
WriteCellStyle contentStyle = new WriteCellStyle();
//内容上下左右四个边框
contentStyle.setBorderBottom(BorderStyle.THIN);
contentStyle.setBorderTop(BorderStyle.THIN);
contentStyle.setBorderLeft(BorderStyle.THIN);
contentStyle.setBorderRight(BorderStyle.THIN);
//水平居中
contentStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
public void buildList(List<OptionalEbomImportVO> listTable, WriteSheet sheet, ExcelWriter writer, AtomicInteger tableNoCounting) {
List<ImportExcelField> items=new Vector<>();
int row=0;
for(OptionalEbomImportVO item1:listTable){
String opParentName=item1.getOptionName();
String optionParentDrawingNoName=item1.getOptionDrawingNo();
if (CollectionUtil.isEmpty(listTable)) {
return;
}
List<OptionalEbomImportVO> list2=item1.getChild();
List<String> cellList = new ArrayList<>();
cellList.add( opParentName);
List<ImportExcelField> items = new ArrayList<>();
for (OptionalEbomImportVO item1 : listTable) {
String opParentName = item1.getOptionName();
String optionParentDrawingNoName = item1.getOptionDrawingNo();
List<OptionalEbomImportVO> list2 = item1.getChild();
List<String> cellList = new ArrayList<>();
cellList.add(opParentName);
List<List<String>> rowList = new ArrayList<>();
rowList.add(cellList);
WriteTable table0 = EasyExcel
.writerTable(tableNoCounting.getAndIncrement())
.needHead(Boolean.FALSE)
.registerWriteHandler(new HorizontalCellStyleStrategy(headStyle, contentStyle))
.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
// .head(rowList)
// .registerWriteHandler(new HorizontalCellStyleStrategy(cellStyle, cellStyle))
// .registerWriteHandler(new PreviewExcelExportHelper.CellColorSheetWriteHandler())
// .registerWriteHandler(
// new OnceAbsoluteMergeStrategy(tableNoCounting.get()-1, tableNoCounting.get(), 0, 2)
// )
if (CollectionUtil.isNotEmpty(items)) {
tableNoCounting.getAndIncrement();
WriteTable table = EasyExcel.writerTable(tableNoCounting.get())
.head(getHeader(opParentName))
.needHead(Boolean.TRUE)//需要Header
.registerWriteHandler(EasyExcelUtil.getDefaultStyle())//传入自定义样式
.registerWriteHandler(new HeaderStyleCustomCellWriteHandler())
.registerWriteHandler(new ColumnMergeStrategy(0, new int[]{0, 1}))
.build();
writer.write(rowList, sheet, table0);
if(CollectionUtil.isNotEmpty(items)){
WriteTable table = EasyExcel.writerTable(tableNoCounting.getAndIncrement())
.needHead(Boolean.FALSE)//需要Header
// .head(rowList)
//添加自适应列宽策略
.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
.registerWriteHandler(new HorizontalCellStyleStrategy(headStyle, contentStyle))//传入自定义样式
// .includeColumnFiledNames(fields)//选择需要哪些属性
.build();
writer.write(items, sheet, table);
}
writer.write(items, sheet, table);
items.clear();
for(OptionalEbomImportVO item2:list2){{
String opChildName=item2.getOptionName();
String optionChildDrawingNoName=item2.getOptionDrawingNo();
List<OptionalEbomImportChildVO > list3=item2.getChild();
for(OptionalEbomImportChildVO item3:list3){
ImportExcelField excelField=new ImportExcelField();
excelField.setCellFirst(optionParentDrawingNoName);
excelField.setCellSecond(String.format("%s %s",optionChildDrawingNoName,opChildName));
excelField.setCellThird(String.format("%s %s%s",item3.getDrawingNo(),item3.getMaterialName(),item3.getChooseStatus()==1?"标配":"可选"));
items.add(excelField);
row++;
}
}
}
}
for (OptionalEbomImportVO item2 : list2) {
{
String opChildName = item2.getOptionName();
String optionChildDrawingNoName = item2.getOptionDrawingNo();
List<OptionalEbomImportChildVO> list3 = item2.getChild();
for (OptionalEbomImportChildVO item3 : list3) {
ImportExcelField excelField = new ImportExcelField();
excelField.setCellFirst(optionParentDrawingNoName);
excelField.setCellSecond(String.format("%s %s", optionChildDrawingNoName, opChildName));
excelField.setCellThird(String.format("%s %s%s", item3.getDrawingNo(), item3.getMaterialName(), item3.getChooseStatus() == 1 ? "标配" : "可选"));
items.add(excelField);
}
}
}
}
}
}

View File

@ -93,6 +93,7 @@ public class PreviewExcelExportHelper {
rowList.clear();
writer.write(rowList, sheet, table);
}

View File

@ -0,0 +1,318 @@
package com.nflg.product.bomnew.excel;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.util.StyleUtil;
import com.alibaba.excel.write.handler.AbstractCellWriteHandler;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.merge.AbstractMergeStrategy;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.nflg.product.bomnew.constant.OptionalBomConstant;
import com.nflg.product.bomnew.pojo.vo.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 生产导出
*/
public class PreviewProduceExcelExportHelper {
public static class HeaderStyleCustomCellWriteHandler extends AbstractCellWriteHandler {
@Override
public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
Row row, Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead) {
// 设置行高
int rowIndex = row.getRowNum();
short height = 600;
row.setHeight(height);
}
private CellStyle initCellStyle(Workbook workbook) {
WriteCellStyle contentWriteCellStyle = EasyExcelUtil.getHeadStyle();
CellStyle headWriteCellStyle = StyleUtil.buildCellStyle(workbook, null, contentWriteCellStyle);
return headWriteCellStyle;
}
@Override
public void afterCellDispose(CellWriteHandlerContext context) {
Cell cell = context.getCell();
int rowIndex = cell.getRowIndex();
int cellIndex = cell.getColumnIndex();
// 自定义宽度处理
// if (context.getHead() && cell.getRowIndex() == 0) {
// int columnWidth = cell.getStringCellValue().getBytes().length;
// switch (cellIndex) {
// case 0:
// case 2:
// case 3:
// case 1:
// columnWidth = 40;
// break;
// default:
// break;
// }
//
// if (columnWidth > 255) {
// columnWidth = 255;
// }
// context.getWriteSheetHolder().getSheet().setColumnWidth(cellIndex, columnWidth * 256);
// }
// 自定义样式处理
if (context.getHead()) {
WriteSheetHolder writeSheetHolder = context.getWriteSheetHolder();
Workbook workbook = writeSheetHolder.getSheet().getWorkbook();
CellStyle cellStyle = initCellStyle(workbook);
XSSFCellStyle xssfCellStyle = (XSSFCellStyle) workbook.createCellStyle();
xssfCellStyle.cloneStyleFrom(cellStyle);
xssfCellStyle.setFillForegroundColor(new XSSFColor(new java.awt.Color(255, 243, 202)));
xssfCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cell.setCellStyle(xssfCellStyle);
context.getFirstCellData().setWriteCellStyle(null); //必须
}
}
}
public List<List<String>> getHeader1() {
String customer = "选配";
List<List<String>> list = new ArrayList<List<String>>();
List<String> head0 = new ArrayList<String>();
head0.add(customer);
List<String> head1 = new ArrayList<String>();
head1.add(customer);
List<String> head2 = new ArrayList<String>();
head2.add(customer);
List<String> head3 = new ArrayList<String>();
head3.add(customer);
list.add(head0);
list.add(head1);
list.add(head2);
list.add(head3);
return list;
}
public List<List<String>> getHeader0(OptionalEbomConfigVO main) {
/**
* 选配清单
* |机型编号 机型名称
* | 合并单元格 空行
* |机型名称|选项名称|物料编码|物料描述
*/
String customer = StrUtil.format("{}选配清单", main.getDeviceName());
List<List<String>> list = new ArrayList<List<String>>();
List<String> head0 = new ArrayList<String>();
head0.add(customer);
head0.add("机型编号:");
head0.add("");
head0.add("机型名称");
head0.add("标配");
List<String> head1 = new ArrayList<String>();
head1.add(customer);
head1.add(main.getDeviceNo());
head1.add("");
head1.add("选项名称");
head1.add("标配");
List<String> head2 = new ArrayList<String>();
head2.add(customer);
head2.add("机型名称:");
head2.add("");
head2.add("物料编码");
head2.add("标配");
List<String> head3 = new ArrayList<String>();
head3.add(customer);
head3.add(main.getDeviceName());
head3.add("");
head3.add("物料描述");
head3.add("标配");
list.add(head0);
list.add(head1);
list.add(head2);
list.add(head3);
return list;
}
public void export(OutputStream filePath, OptionalEbomConfigTmpAggregVO voObj) {
//使用一个计数器记录当前已经写了几个表格
AtomicInteger tableNoCounting = new AtomicInteger(0);
ExcelWriter writer = EasyExcel.write(filePath)//指定写入的流以及需要EasyExcel自带动态生成的类的类对象
.excelType(ExcelTypeEnum.XLSX)//指定Excel文件类型如xlsxxls等
.autoCloseStream(Boolean.FALSE)
.build();
WriteSheet sheet = EasyExcel
.writerSheet("生产预览导出")//指定写入的sheet
.needHead(false)//是否需要head也就是每一个字段对应的字段名这里不需要 需要EasyExcel去生成字段名的地方只有列表数据部分
.build();
buildList0(voObj, sheet, writer, tableNoCounting);
buildList1(voObj, sheet, writer, tableNoCounting);
writer.finish();
}
public void buildList0(OptionalEbomConfigTmpAggregVO header, WriteSheet sheet, ExcelWriter writer, AtomicInteger tableNoCounting) {
WriteTable table = EasyExcel
.writerTable(tableNoCounting.get())
.head(getHeader0(header.getDeviceInfo()))
.needHead(Boolean.TRUE)
.registerWriteHandler(EasyExcelUtil.getDefaultStyle())
// .registerWriteHandler(new PreviewTmpExcelExportHelper.MultiColumnMergeStrategy())
.registerWriteHandler(new ExportDeviceHelper.ColumnMergeStrategy(0,new int[]{0}) )
.registerWriteHandler(new PreviewTmpExcelExportHelper.HeaderStyleCustomCellWriteHandler()) //顶部表头样式通用
.build();
List list = getStandList(header.getSingleList(), header.getMulList());
writer.write(list, sheet, table);
}
public void buildList1(OptionalEbomConfigTmpAggregVO header, WriteSheet sheet, ExcelWriter writer, AtomicInteger tableNoCounting) {
tableNoCounting.getAndIncrement();
List<List<String>> tbHeader = getHeader1();
WriteTable table = EasyExcel
.writerTable(tableNoCounting.get())
.head(tbHeader)
.needHead(Boolean.TRUE)
.registerWriteHandler(EasyExcelUtil.getDefaultStyle())
// .registerWriteHandler(new PreviewTmpExcelExportHelper.MultiColumnMergeStrategy())
.registerWriteHandler(new ExportDeviceHelper.ColumnMergeStrategy(0,new int[]{0}) )
.registerWriteHandler(new HeaderStyleCustomCellWriteHandler()) //单独处理表头样式
.build();
List list = getNonList(header.getSingleList(), header.getMulList());
writer.write(list, sheet, table);
}
public void download(HttpServletResponse response, OptionalEbomConfigTmpAggregVO voObj) throws Exception {
String fileName = StrUtil.format("{}-{}-生产导出", voObj.getDeviceInfo().getDeviceName(), System.currentTimeMillis());
EasyExcelUtil.setExportHeader(response, fileName);
// List<ExcelExportField> list = getList(voObj.getSingleList(), voObj.getMulList());
// EasyExcel.write(response.getOutputStream()).head(getHeader(voObj.getDeviceInfo()))
// .autoCloseStream(Boolean.FALSE)
// .registerWriteHandler(new MultiColumnMergeStrategy())
// .registerWriteHandler(EasyExcelUtil.getDefaultStyle())
// .registerWriteHandler(new CustomCellWriteHandler())
// // .registerWriteHandler(new CustomCellWriteHandler2())
// .sheet("预览导出")
// .doWrite(list);
}
private List<ExcelExportField> getNonList(List<OptionalEbomImportVO> singleList, List<OptionalEbomImportChildVO> mulList) {
List<ExcelExportField> items = new ArrayList<>();
for (OptionalEbomImportVO item1 : singleList) {
String opParentName = item1.getOptionName();
String optionParentDrawingNoName = item1.getOptionDrawingNo();
List<OptionalEbomImportVO> list2 = item1.getChild();
for (OptionalEbomImportVO item2 : list2) {
String opChildName = item2.getOptionName();
String optionChildDrawingNoName = item2.getOptionDrawingNo();
List<OptionalEbomImportChildVO> list3 = item2.getChild();
if (CollectionUtil.isNotEmpty(list3)) {
for (OptionalEbomImportChildVO item3 : list3) {
if (Objects.equals(item3.getChooseStatus(), OptionalBomConstant.ChooseStatusEnum.CHOOSE_STATUS_NO.getValue())) {
ExcelExportField excelField = new ExcelExportField();
excelField.setCellFirst(StrUtil.format("{}\n{}", opParentName, optionParentDrawingNoName));
excelField.setCellSecond(StrUtil.format("{}\n{}", opChildName, optionChildDrawingNoName));
excelField.setCellThird(StrUtil.format("{}", item3.getMaterialNo()));
excelField.setCellFourth(StrUtil.format("{}\n{}", item3.getMaterialName(), item3.getDrawingNo()));
items.add(excelField);
}
}
}
}
}
if (CollectionUtil.isNotEmpty(mulList)) {
//添加配置
for (OptionalEbomImportChildVO item1 : mulList) {
ExcelExportField excelField = new ExcelExportField();
excelField.setCellFirst("附加配件");
excelField.setCellSecond(StrUtil.format("{}\n{}", item1.getMaterialName(), item1.getMaterialNo()));
excelField.setCellThird(StrUtil.format("{}", item1.getMaterialNo()));
excelField.setCellFourth(item1.getMaterialDesc());
items.add(excelField);
}
}
return items;
}
private List<ExcelExportField> getStandList(List<OptionalEbomImportVO> singleList, List<OptionalEbomImportChildVO> mulList) {
List<ExcelExportField> items = new ArrayList<>();
for (OptionalEbomImportVO item1 : singleList) {
String opParentName = item1.getOptionName();
String optionParentDrawingNoName = item1.getOptionDrawingNo();
List<OptionalEbomImportVO> list2 = item1.getChild();
for (OptionalEbomImportVO item2 : list2) {
String opChildName = item2.getOptionName();
String optionChildDrawingNoName = item2.getOptionDrawingNo();
List<OptionalEbomImportChildVO> list3 = item2.getChild();
if (CollectionUtil.isNotEmpty(list3)) {
for (OptionalEbomImportChildVO item3 : list3) {
if (item3.getChooseStatus().equals(OptionalBomConstant.ChooseStatusEnum.CHOOSE_STATUS_YES.getValue())) {
ExcelExportField excelField = new ExcelExportField();
excelField.setCellFirst(StrUtil.format("{}\n{}", opParentName, optionParentDrawingNoName));
excelField.setCellSecond(StrUtil.format("{}\n{}", opChildName, optionChildDrawingNoName));
excelField.setCellThird(StrUtil.format("{}", item3.getMaterialNo()));
excelField.setCellFourth(StrUtil.format("{}\n{}", item3.getMaterialName(), item3.getDrawingNo()));
items.add(excelField);
}
}
}
}
}
return items;
}
}

View File

@ -0,0 +1,479 @@
package com.nflg.product.bomnew.excel;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.util.BooleanUtils;
import com.alibaba.excel.util.StyleUtil;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.handler.AbstractCellWriteHandler;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.merge.AbstractMergeStrategy;
import com.alibaba.excel.write.merge.OnceAbsoluteMergeStrategy;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.nflg.product.bomnew.pojo.vo.*;
import io.swagger.annotations.ApiModelProperty;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 预览导出
*/
public class PreviewTmpExcelExportHelper {
public static class HeaderStyleCustomCellWriteHandler extends AbstractCellWriteHandler {
@Override
public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
Row row, Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead) {
// 设置行高
int rowIndex = row.getRowNum();
// System.out.println("当前行: " + rowIndex);
short height = 600;
row.setHeight(height);
}
private CellStyle initCellStyle(Workbook workbook) {
// CellStyle headWriteCellStyle = workbook.createCellStyle();
// //设置底边框;
// headWriteCellStyle.setBorderBottom(BorderStyle.THIN);
// //设置底边框颜色;
// headWriteCellStyle.setBottomBorderColor((short) 0);
// //设置左边框;
// headWriteCellStyle.setBorderLeft(BorderStyle.THIN);
// //设置左边框颜色;
// headWriteCellStyle.setLeftBorderColor((short) 0);
// //设置右边框;
// headWriteCellStyle.setBorderRight(BorderStyle.THIN);
// //设置右边框颜色;
// headWriteCellStyle.setRightBorderColor((short) 0);
// //设置顶边框;
// headWriteCellStyle.setBorderTop(BorderStyle.THIN);
// //设置顶边框颜色;
// headWriteCellStyle.setTopBorderColor((short) 0);
//
// //设置水平对齐的样式为居中对齐;
// headWriteCellStyle.setAlignment(HorizontalAlignment.CENTER);
// //设置垂直对齐的样式为居中对齐;
// headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
//
// Font font = workbook.createFont();
// font.setFontName("宋体"); // 字体样式
// font.setBold(false); // 是否加粗
// font.setFontHeightInPoints((short) 11); // 字体大小
// headWriteCellStyle.setFont(font);
WriteCellStyle contentWriteCellStyle = EasyExcelUtil.getHeadStyle();
CellStyle headWriteCellStyle = StyleUtil.buildCellStyle(workbook,null, contentWriteCellStyle);
return headWriteCellStyle;
}
@Override
public void afterCellDispose(CellWriteHandlerContext context) {
Cell cell = context.getCell();
int rowIndex = cell.getRowIndex();
int cellIndex = cell.getColumnIndex();
// 自定义宽度处理
if (context.getHead() && cell.getRowIndex() == 1) {
int columnWidth = cell.getStringCellValue().getBytes().length;
switch (cellIndex) {
case 0:
case 2:
case 3:
case 1:
columnWidth = 40;
break;
default:
break;
}
if (columnWidth > 255) {
columnWidth = 255;
}
context.getWriteSheetHolder().getSheet().setColumnWidth(cellIndex, columnWidth * 256);
}
// 自定义样式处理
//单独处理表头样式 4行表头生产预览
if (context.getHead() && (rowIndex == 4 || rowIndex==3 || rowIndex==1)) {
WriteSheetHolder writeSheetHolder = context.getWriteSheetHolder();
Workbook workbook = writeSheetHolder.getSheet().getWorkbook();
CellStyle cellStyle = initCellStyle(workbook);
XSSFCellStyle xssfCellStyle = (XSSFCellStyle) workbook.createCellStyle();
xssfCellStyle.cloneStyleFrom(cellStyle);
xssfCellStyle.getFont().setBold(false);
switch (rowIndex){
case 1:
xssfCellStyle.setFillForegroundColor(new XSSFColor(new java.awt.Color(217, 217, 217)));
xssfCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
if(cellIndex==0|| cellIndex==2){
xssfCellStyle.setAlignment(HorizontalAlignment.RIGHT);
xssfCellStyle.getFont().setBold(true);
}
break;
case 3:
xssfCellStyle.setFillForegroundColor(new XSSFColor(new java.awt.Color(227, 242, 217)));
xssfCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
break;
case 4:
xssfCellStyle.setFillForegroundColor(new XSSFColor(new java.awt.Color(250, 218, 222)));
xssfCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
break;
}
cell.setCellStyle(xssfCellStyle);
context.getFirstCellData().setWriteCellStyle(null); //必须
}
}
}
// public class CustomCellWriteHandler implements CellWriteHandler {
//
// @Override
// public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead) {
// // 设置行高测试
// int rowIndex = row.getRowNum();
// System.out.println("当前行: " + rowIndex);
// short height = 600;
// row.setHeight(height);
// }
//
// @Override
// public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
// List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
// int rowIndex = cell.getRowIndex();
// int cellIndex = cell.getColumnIndex();
//
//
// // 自定义宽度处理
// if (isHead && cell.getRowIndex() == 1) {
// int columnWidth = cell.getStringCellValue().getBytes().length;
// switch (cellIndex) {
// case 0:
// case 2:
// case 3:
// case 1:
// columnWidth = 40;
// break;
// default:
// break;
// }
//
// if (columnWidth > 255) {
// columnWidth = 255;
// }
// writeSheetHolder.getSheet().setColumnWidth(cellIndex, columnWidth * 256);
//
//
// }
//
//
// }
//
//
// }
//
// public class DetectionSheetWriteHandler implements SheetWriteHandler {
//
// private String dataTime;
// public DetectionSheetWriteHandler(){}
//
// @Override
// public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
//
// }
//
// @Override
// public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
// Workbook workbook = writeWorkbookHolder.getWorkbook();
// Sheet sheet = workbook.getSheetAt(0);
// //设置第一行标题
// Row row1 = sheet.createRow(1);
// row1.setHeight((short) 800);
// Cell row1Cell1 = row1.createCell(0);
// row1Cell1.setCellValue(" 统 计 表");
// CellStyle row1CellStyle = workbook.createCellStyle();
// row1CellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
// row1CellStyle.setAlignment(HorizontalAlignment.CENTER);
// Font row1Font = workbook.createFont();
// row1Font.setBold(true);
// row1Font.setFontName("宋体");
// row1Font.setFontHeightInPoints((short) 18);
// row1CellStyle.setFont(row1Font);
// row1Cell1.setCellStyle(row1CellStyle);
// //合并单元格起始行,结束行,起始列,结束列
// sheet.addMergedRegionUnsafe(new CellRangeAddress(1, 1, 0, 5));
//// sheet.addMergedRegionUnsafe(new CellRangeAddress(1, 1, 22, 23));
//
//// 设置第二行标题
// Row row2 = sheet.createRow(2);
// row2.setHeight((short) 400);
// Cell row2Cell1 = row2.createCell(0);
// row2Cell1.setCellValue("时间范围:"+ dataTime);
// CellStyle row2CellStyle = workbook.createCellStyle();
// row2CellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
// row2CellStyle.setAlignment(HorizontalAlignment.RIGHT);
// Font row2Font = workbook.createFont();
// row2Font.setFontName("宋体");
// row2Font.setFontHeightInPoints((short) 10);
// row2CellStyle.setFont(row2Font);
// row2Cell1.setCellStyle(row2CellStyle);
// sheet.addMergedRegionUnsafe(new CellRangeAddress(2, 2, 0, 5));
//
// }
// }
//
public void export(OutputStream filePath, OptionalEbomConfigTmpAggregVO voObj) {
List<ExcelExportField> list = getList(voObj.getSingleList(), voObj.getMulList());
EasyExcel.write(filePath).head(getHeader(voObj.getDeviceInfo()))
.excelType(ExcelTypeEnum.XLSX)
.autoCloseStream(Boolean.FALSE)
// .registerWriteHandler(new MultiColumnMergeStrategy())
.registerWriteHandler(new ExportDeviceHelper.ColumnMergeStrategy(0,new int[]{0}) )
.registerWriteHandler(EasyExcelUtil.getDefaultStyle())
.registerWriteHandler(new HeaderStyleCustomCellWriteHandler() )
.sheet("预览导出")
.doWrite(list);
}
public void download(HttpServletResponse response, OptionalEbomConfigTmpAggregVO voObj) throws Exception {
String fileName=StrUtil.format("{}-{}-预览导出",voObj.getDeviceInfo().getDeviceName(),System.currentTimeMillis());
EasyExcelUtil.setExportHeader(response, fileName);
List<ExcelExportField> list = getList(voObj.getSingleList(), voObj.getMulList());
EasyExcel.write(response.getOutputStream()).head(getHeader(voObj.getDeviceInfo()))
.autoCloseStream(Boolean.FALSE)
.excelType(ExcelTypeEnum.XLSX)
.registerWriteHandler(new ExportDeviceHelper.ColumnMergeStrategy(0,new int[]{0}) )
.registerWriteHandler(EasyExcelUtil.getDefaultStyle())
.registerWriteHandler(new HeaderStyleCustomCellWriteHandler() )
.sheet("预览导出")
.doWrite(list);
}
public static List<List<String>> getHeader(OptionalEbomConfigVO main) {
/**
* 选配清单
* |机型编号 机型名称
* | 合并单元格 空行
* |机型名称|选项名称|物料编码|物料描述
*/
String customer = StrUtil.format("{}选配清单", main.getDeviceName());
List<List<String>> list = new ArrayList<List<String>>();
List<String> head0 = new ArrayList<String>();
head0.add(customer);
head0.add("机型编号:");
head0.add("");
head0.add("机型名称");
List<String> head1 = new ArrayList<String>();
head1.add(customer);
head1.add(main.getDeviceNo());
head1.add("");
head1.add("选项名称");
List<String> head2 = new ArrayList<String>();
head2.add(customer);
head2.add("机型名称:");
head2.add("");
head2.add("物料编码");
List<String> head3 = new ArrayList<String>();
head3.add(customer);
head3.add(main.getDeviceName());
head3.add("");
head3.add("物料描述");
list.add(head0);
list.add(head1);
list.add(head2);
list.add(head3);
return list;
}
private List<ExcelExportField> getList(List<OptionalEbomImportVO> singleList, List<OptionalEbomImportChildVO> mulList) {
List<ExcelExportField> items = new ArrayList<>();
for (OptionalEbomImportVO item1 : singleList) {
String opParentName = item1.getOptionName();
String optionParentDrawingNoName = item1.getOptionDrawingNo();
List<OptionalEbomImportVO> list2 = item1.getChild();
for (OptionalEbomImportVO item2 : list2) {
String opChildName = item2.getOptionName();
String optionChildDrawingNoName = item2.getOptionDrawingNo();
List<OptionalEbomImportChildVO> list3 = item2.getChild();
if (CollectionUtil.isNotEmpty(list3)) {
for (OptionalEbomImportChildVO item3 : list3) {
ExcelExportField excelField = new ExcelExportField();
excelField.setCellFirst(StrUtil.format("{}\n{}", opParentName, optionParentDrawingNoName));
excelField.setCellSecond(StrUtil.format("{}\n{}", opChildName, optionChildDrawingNoName));
excelField.setCellThird(StrUtil.format("{}", item3.getMaterialNo()));
excelField.setCellFourth(StrUtil.format("{}\n{}", item3.getMaterialName(), item3.getDrawingNo()));
items.add(excelField);
}
}
}
}
//添加配置
for (OptionalEbomImportChildVO item1 : mulList) {
ExcelExportField excelField = new ExcelExportField();
excelField.setCellFirst("附加配件");
excelField.setCellSecond(StrUtil.format("{}\n{}", item1.getMaterialName(), item1.getMaterialNo()));
excelField.setCellThird(StrUtil.format("{}", item1.getMaterialNo()));
excelField.setCellFourth(item1.getMaterialDesc());
items.add(excelField);
}
return items;
}
// public static class MultiColumnMergeStrategy extends AbstractMergeStrategy {
//
//
// private Map<String, List<Integer>> nameRowMap = new HashMap<>();
//
// @Override
// protected void merge(Sheet sheet, Cell cell, Head head, Integer relativeRowIndex) {
// int columnIndex = cell.getColumnIndex();
//
// if (columnIndex == 0) {
// String currentValue = cell.getStringCellValue();
// if (currentValue == null || currentValue.isEmpty()) {
// return;
// }
//
// int currentRowIndex = cell.getRowIndex();
// List<Integer> rowList = nameRowMap.getOrDefault(currentValue, new ArrayList<>());
// rowList.add(currentRowIndex);
// nameRowMap.put(currentValue, rowList);
//
// mergeRows(sheet, currentValue, rowList, columnIndex);
// }
//
// if (columnIndex == 0) {
// String currentValue = cell.getStringCellValue();
// if (currentValue == null || currentValue.isEmpty()) {
// return;
// }
//
// int currentRowIndex = cell.getRowIndex();
// List<Integer> rowList = nameRowMap.getOrDefault(currentValue, new ArrayList<>());
// rowList.add(currentRowIndex);
// nameRowMap.put(currentValue, rowList);
//
// mergeRows(sheet, currentValue, rowList, columnIndex);
// }
// }
//
// private void mergeRows(Sheet sheet, String value, List<Integer> rowList, int columnIndex) {
// if (rowList.size() <= 1) {
// return;
// }
//
// int startRow = rowList.get(0);
// int endRow = rowList.get(rowList.size() - 1);
//
// // 检查是否存在重叠合并区域
// CellRangeAddress existingRegion = findOverlappingRegion(sheet, startRow, endRow, columnIndex);
// if (existingRegion != null) {
// // 扩展现有合并区域以适应新的合并行
// startRow = Math.min(existingRegion.getFirstRow(), startRow);
// endRow = Math.max(existingRegion.getLastRow(), endRow);
//
// // 移除现有合并区域
// removeMergedRegion(sheet, existingRegion);
// }
//
// if (startRow < endRow) {
// CellRangeAddress range = new CellRangeAddress(startRow, endRow, columnIndex, columnIndex);
// sheet.addMergedRegionUnsafe(range);
// }
// }
//
// private CellRangeAddress findOverlappingRegion(Sheet sheet, int startRow, int endRow, int columnIndex) {
// for (CellRangeAddress region : sheet.getMergedRegions()) {
// if (region.getFirstColumn() == columnIndex && region.getLastColumn() == columnIndex) {
// // 只考虑指定列的合并区域
// if (startRow <= region.getLastRow() && endRow >= region.getFirstRow()) {
// return region;
// }
// }
// }
// return null;
// }
//
// private void removeMergedRegion(Sheet sheet, CellRangeAddress region) {
// int index = -1;
// for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
// CellRangeAddress mergedRegion = sheet.getMergedRegion(i);
// if (mergedRegion.equals(region)) {
// index = i;
// break;
// }
// }
// if (index >= 0) {
// sheet.removeMergedRegion(index);
// }
// }
//
//
// }
}

View File

@ -13,7 +13,8 @@ import java.time.LocalDateTime;
import java.time.LocalDate;
import java.util.Date;
@Data
@ApiModel("用户选配比对是否相同")
@ApiModel("com.nflg.product.bomnew.pojo.dto.OptionalMbomCompareDTO")
@Accessors(chain = true)
public class OptionalMbomCompareDTO implements Serializable {
/**主键*/ @ApiModelProperty(value = "主键")

View File

@ -18,7 +18,7 @@ import java.time.LocalDate;
import java.util.Date;
@Data
@ApiModel("ebom选配件表")
@ApiModel("com.nflg.product.bomnew.pojo.queryebom.OptionalEbomImportChildQuery选配件表")
@Accessors(chain = true)
public class OptionalEbomImportChildQuery implements Serializable {
@ -49,4 +49,10 @@ public class OptionalEbomImportChildQuery implements Serializable {
@ApiModelProperty(value = "结束时间")
private String endTime;
@ApiModelProperty(value = "0查询隐藏 1 查询显示 空全部")
private Integer enable;
}

View File

@ -38,6 +38,12 @@ row_id,parent_row_id,root_row_id,material_no,material_name,material_desc,drawing
from t_optional_ebom_import_child
where root_row_id = #{query.rootRowId}
<if test="query.enable != null">
and is_enable=${query.enable}
</if>
<if test="query.materialNo != null and query.materialNo != ''">
and material_no like concat('%', '${query.materialNo}', '%')
</if>
@ -47,7 +53,10 @@ row_id,parent_row_id,root_row_id,material_no,material_name,material_desc,drawing
and drawing_no like concat('%', '${query.drawingNo}', '%')
</if>
<if test="query.startTime != null and query.endTime != null">
<if test="query.startTime != null and query.startTime != '' and query.endTime != null and query.endTime != ''">
<![CDATA[ and created_time >= #{query.startTime} and created_time < #{query.endTime}]]>
</if>