导出模板
@GetMapping("/downloadImportTemplate")
public void downloadImportTemplate(ContractRuleDTO contractRuleDTO, HttpServletResponse response) throws Exception{
try {
RegularContractRuleVo regularContractRuleTrendsData = contractRuleService.findRegularContractRuleTrendsData(contractRuleDTO);
List<LinkedHashMap<String, String>> filedMapList = regularContractRuleTrendsData.getFiledMap();
LinkedHashMap<String, String> titleMap = filedMapList.get(0);
if(CollectionUtil.isEmpty(titleMap)){
throw new ServiceException("表头不能为空");
}
Iterator<String> iterator = titleMap.keySet().iterator();
ArrayList<String> titleList = new ArrayList<>();
while (iterator.hasNext()) {
String key = iterator.next();
String value = titleMap.get(key);
titleList.add(value);
}
String fileName = "批量导入模板.xlsx";
fileName = URLEncoder.encode(fileName, "utf-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("application/x-download");
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
final String sheetName = "批量导入XXX";
DynamicExcelUtil.getExcelTitleTemplate(response, sheetName, titleList,null);
} catch (Exception e) {
e.printStackTrace();
}
}
批量导入(原生POI模式)
@PostMapping("/batchImportContractQuotation")
public R batchImportContractQuotation(@RequestParam(name = "file") MultipartFile file,ContractRuleVo contractRuleVo){
try {
String s = basicRatePricingService.batchImportContractQuotation(file, contractRuleVo);
if(!"操作成功".equals(s)){
return R.fail(s);
}
return R.success(s);
}catch (Exception e){
return R.success(e.getMessage());
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public String batchImportContractQuotation(MultipartFile multipartFile,ContractRuleVo contractRuleVo){
Workbook wb = null;
verifyData(contractRuleVo);
Long ruleId = contractRuleVo.getContractRuleDTO().getRuleId();
MmsQuotationRuleInfoVo mmsQuotationRuleInfoVo = mmsQuotationRuleService.selectMmsQuotationRuleById(ruleId.toString());
List<MmsQuotationRuleFactorVo> mmsQuotationRuleFactorVo = mmsQuotationRuleInfoVo.getMmsQuotationRuleFactorVo();
List<MmsQuotationRuleSegmentedVo> mmsQuotationRuleSegmentedVo = mmsQuotationRuleInfoVo.getMmsQuotationRuleSegmentedVo();
List<MmsQuotationRuleDimensionVo> mmsQuotationRuleDimensionVo = mmsQuotationRuleInfoVo.getMmsQuotationRuleDimensionVo();
try {
if (multipartFile != null) {
wb = DynamicExcelUtil.getWorkbook(multipartFile);
Sheet sheet = wb.getSheetAt(0);
int rowCount = sheet.getPhysicalNumberOfRows();
if(rowCount==0){
return "请填写数据";
}
Row titleRow = sheet.getRow(0);
if (titleRow != null) {
LinkedHashMap<Integer,String> headerMap = new LinkedHashMap<>();
int lastCellNum = titleRow.getPhysicalNumberOfCells();
int cellCount = lastCellNum+1;
for (int i = 0; i < cellCount-1; i++) {
String cellValue = DynamicExcelUtil.getCellValue(titleRow.getCell(i));
if(StaticParameter.EFFECTIVE_DATE_LABEL.equals(cellValue)){
headerMap.put(i,StaticParameter.EFFECTIVE_DATE);
}else if(StaticParameter.EXPIRATION_DATE_LABEL.equals(cellValue)){
headerMap.put(i,StaticParameter.EXPIRATION_DATE);
}else if(StaticParameter.REMARKS_LABEL.equals(cellValue)){
headerMap.put(i,StaticParameter.REMARKS);
}
for (MmsQuotationRuleFactorVo quotationRuleFactorVo : mmsQuotationRuleFactorVo){
if(ObjectUtil.equals(cellValue,quotationRuleFactorVo.getColumnName())){
headerMap.put(i,StringUtils.toCamelCase(quotationRuleFactorVo.getField()));
break;
}
}
if(CollectionUtil.isNotEmpty(mmsQuotationRuleSegmentedVo)){
for (MmsQuotationRuleSegmentedVo quotationRuleSegmentedVo : mmsQuotationRuleSegmentedVo) {
if(ObjectUtil.equals(cellValue,quotationRuleSegmentedVo.getColumnName())){
headerMap.put(i,quotationRuleSegmentedVo.getPriceName()+StaticParameter.SPLIT_FLAG+quotationRuleSegmentedVo.getId());
break;
}
}
}
if(CollectionUtil.isNotEmpty(mmsQuotationRuleDimensionVo)){
for (MmsQuotationRuleDimensionVo quotationRuleDimensionVo : mmsQuotationRuleDimensionVo) {
if(ObjectUtil.equals(cellValue,quotationRuleDimensionVo.getColumnName())){
headerMap.put(i,quotationRuleDimensionVo.getPriceName()+StaticParameter.SPLIT_FLAG+quotationRuleDimensionVo.getId());
break;
}
}
}
}
ArrayList<BasicRatePricing> list = new ArrayList<>();
for (int i = 1; i < rowCount; i++) {
Row dataRow = sheet.getRow(i);
BasicRatePricing basicRatePricing = new BasicRatePricing();
Map<String,Object> dataMap = BeanUtil.beanToMap(basicRatePricing);
for(int j=0;j<cellCount-1;j++){
String cellValue = DynamicExcelUtil.getCellValue(dataRow.getCell(j));
String value = headerMap.get(j);
if(value.indexOf(StaticParameter.SPLIT_FLAG) == -1){
if(dataMap.containsKey(value)){
dataMap.put(value,cellValue);
}
}else {
String[] strArr = StringUtils.split(value,StaticParameter.SPLIT_FLAG);
if(dataMap.containsKey(strArr[0])){
dataMap.put(strArr[0],strArr[1]);
}
String valueFile = strArr[0].replace(StaticParameter.RESERVE_FACTOR,StaticParameter.RESERVE_VALUE);
if(dataMap.containsKey(valueFile)){
dataMap.put(valueFile,cellValue);
}
}
}
BasicRatePricing basicRatePricing2 = BeanUtil.mapToBean(dataMap,BasicRatePricing.class,true);
BeanUtil.copyProperties(basicRatePricing2,basicRatePricing);
list.add(basicRatePricing);
}
saveBatch(list);
}
} else {
log.info("++++++++++++传入文件为空+++++++++++++");
return "传入文件为空";
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (wb != null) {
try {
wb.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "操作成功";
}
操作Excel的工具类
public class DynamicExcelUtil {
private static final int DEFAULT_COLUMN_SIZE = 20;
public static void getExcelTitleTemplate(HttpServletResponse response, String sheetName,
ArrayList<String> titleList, String title) throws Exception {
Workbook workBook = new XSSFWorkbook();
Sheet sheet = workBook.getSheet(sheetName);
if (sheet == null) {
sheet = workBook.createSheet(sheetName);
}
int lastRowIndex = sheet.getLastRowNum();
if (lastRowIndex > 0) {
lastRowIndex++;
}
if (!StringUtils.isBlank(title)) {
Row titleRow = sheet.createRow(0);
Cell cellTiltle1 = titleRow.createCell(0);
cellTiltle1.setCellValue(title);
lastRowIndex++;
}
sheet.setDefaultColumnWidth(DEFAULT_COLUMN_SIZE);
Row row = sheet.createRow(0);
for (int i = 0; i < titleList.size(); i++) {
Cell cell = row.createCell(i);
cell.setCellStyle(createCellHeadStyle(workBook));
RichTextString text = new XSSFRichTextString(titleList.get(i));
cell.setCellValue(text);
}
OutputStream outputStream = response.getOutputStream();
workBook.write(outputStream);
outputStream.flush();
outputStream.close();
}
private static CellStyle createCellHeadStyle(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
Font font = workbook.createFont();
font.setColor(IndexedColors.BLACK.index);
font.setBold(true);
font.setFontHeightInPoints((short)12);
style.setFont(font);
return style;
}
public static String getCellValue(Cell cell) {
String value = "";
if (cell != null) {
switch (cell.getCellType()) {
case NUMERIC:
value = cell.getNumericCellValue() + "";
if (DateUtil.isCellDateFormatted(cell)) {
Date date = cell.getDateCellValue();
if (date != null) {
value = new SimpleDateFormat("yyyy-MM-dd").format(date);
} else {
value = "";
}
} else {
value = new DecimalFormat("0.00").format(cell.getNumericCellValue());
}
break;
case STRING:
value = cell.getStringCellValue();
break;
case BOOLEAN:
value = cell.getBooleanCellValue() + "";
break;
case FORMULA:
value = cell.getCellFormula() + "";
break;
case BLANK:
value = "";
break;
case ERROR:
value = "非法字符";
break;
default:
value = "未知类型";
break;
}
}
return value.trim();
}
public static Workbook getWorkbook(MultipartFile file) throws IOException {
Workbook workbook = null;
String fileName = file.getOriginalFilename();
if (fileName.endsWith("xls")) {
POIFSFileSystem pois = new POIFSFileSystem(file.getInputStream());
workbook = new HSSFWorkbook(pois);
} else if (fileName.endsWith("xlsx")) {
workbook = new XSSFWorkbook(file.getInputStream());
}
return workbook;
}
}