Excel解析导入

controller
package com.basetnt.ad.game.xiaoxiaoqi.controller;

import com.basetnt.ad.game.xiaoxiaoqi.common.Result;
import com.basetnt.ad.game.xiaoxiaoqi.model.AdConfig;
import com.basetnt.ad.game.xiaoxiaoqi.service.ResolveExcelService;
import io.swagger.annotations.Api;
import java.util.List;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Desc
 * @Date 2019/4/26 15:09
 * @Author cui_yl
 */
@Api(tags = "ExcelController", description = "解析exce")
@RestController
@RequestMapping("/excel")
public class ExcelController {
	private static final Logger logger = LoggerFactory.getLogger(ExcelController.class);

	@Resource(name = "resolveExcelServiceImpl")
	private ResolveExcelService resolveExcelService;

	/**
	 * 文件上传
	 */
	@PostMapping(value = "/upload")
	public Result resolveExcel(@RequestParam("file") MultipartFile file) {
		try {
			List<AdConfig> result = resolveExcelService.resolveExcel(file);
			return Result.success(result);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("导入失败:" + e.getMessage(), 500);
		}
	}
}

service
package com.basetnt.ad.game.xiaoxiaoqi.service;

import com.basetnt.ad.game.xiaoxiaoqi.dao.AdConfigMapper;
import com.basetnt.ad.game.xiaoxiaoqi.model.AdConfig;
import com.basetnt.ad.game.xiaoxiaoqi.model.AdConfigExample;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Desc
 * @Date 2019/4/26 15:13
 * @Author cui_yl
 */
@Service("resolveExcelServiceImpl")
public class ResolveExcelService  {
    /**
     *打印日志
     */
    private static final Logger logger = LoggerFactory.getLogger(ResolveExcelService.class);

    /**
     * 注册url
     */
    private static final String SUFFIX_2003 = ".xls";
    private static final String SUFFIX_2007 = ".xlsx";

    @Autowired
    private AdConfigMapper adConfigMapper;

    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor=Exception.class)
    public List<AdConfig> resolveExcel(MultipartFile file) throws Exception {
        Date date = new Date();
        if (file == null) {
            throw new RuntimeException("文件不能为空");
        }

        //获取文件的名字
        String originalFilename = file.getOriginalFilename();
        if(StringUtils.isEmpty(originalFilename)){
            throw new RuntimeException("文件名不能为空");
        }

        Workbook workbook = null;
        if (originalFilename.endsWith(SUFFIX_2003)) {
            workbook = new HSSFWorkbook(file.getInputStream());
        } else if (originalFilename.endsWith(SUFFIX_2007)) {
            workbook = new XSSFWorkbook(file.getInputStream());
        }else {
            throw new RuntimeException("请上传.xls或者.xlsx格式的Excel");
        }

        List<AdConfig> list = new ArrayList<AdConfig>();
        AdConfig entity = null;
        JsonObject json = null;

        //获取所有的工作表的的数量
        int numOfSheet = workbook.getNumberOfSheets();
        //遍历这个这些表
        for (int i = 0; i < numOfSheet; i++) {
            //获取一个sheet也就是一个工作簿
            Sheet sheet = workbook.getSheetAt(i);
            int lastRowNum = sheet.getLastRowNum();
            /*
             * 第0行 标题
             * 第1行 数据
             * 从1行开始 循环遍历 封装数据
             */
            for (int j = 1; j <= lastRowNum; j++) {
                Row row = sheet.getRow(j);
                boolean falg = (null == row || null == row.getCell(0) || StringUtils.isEmpty(row.getCell(0).getStringCellValue()));

                if (falg) {
                    continue;
                }

                entity = new AdConfig();
                json = new JsonObject();

                if (row.getCell(0) != null) {
                    row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
                    String cellValue = row.getCell(0).getStringCellValue();
                    entity.setPackageName(cellValue.trim());
                }
                if (row.getCell(1) != null) {
                    row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
                    String cellValue = row.getCell(1).getStringCellValue();
                    entity.setAdSpace(cellValue.trim());
                }

                if (row.getCell(2) != null) {
                    row.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
                    String cellValue = row.getCell(2).getStringCellValue();
                    entity.setAdType(cellValue.trim());
                }

                if (row.getCell(3) != null) {
                    row.getCell(3).setCellType(Cell.CELL_TYPE_STRING);
                    String cellValue = row.getCell(3).getStringCellValue().trim();
                    entity.setTotalNum(Integer.valueOf(cellValue.trim()));
                }

                if (row.getCell(4) != null) {
                    row.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
                    String cellValue = row.getCell(4).getStringCellValue().trim();
                    entity.setDays(Integer.valueOf(cellValue.trim()));
                }

                if (row.getCell(5) != null) {
                    row.getCell(5).setCellType(Cell.CELL_TYPE_STRING);
                    String cellValue = row.getCell(5).getStringCellValue().trim();
                    entity.setGoldNum(Integer.valueOf(cellValue.trim()));
                }

                if (row.getCell(6) != null) {
                    row.getCell(6).setCellType(Cell.CELL_TYPE_STRING);
                    String cellValue = row.getCell(6).getStringCellValue().trim();
                    json.addProperty("百度", cellValue.trim());
                }

                if (row.getCell(7) != null) {
                    row.getCell(7).setCellType(Cell.CELL_TYPE_STRING);
                    String cellValue = row.getCell(7).getStringCellValue().trim();
                    json.addProperty("腾讯", cellValue.trim());
                }

                if (row.getCell(8) != null) {
                    row.getCell(8).setCellType(Cell.CELL_TYPE_STRING);
                    String cellValue = row.getCell(8).getStringCellValue().trim();
                    json.addProperty("穿三甲", cellValue.trim());
                }
                entity.setWeightConfig(json.toString());
                entity.setImportTime(date);
                entity.setCreatedTime(date);
                entity.setModifiedTime(date);
                list.add(entity);
            }
        }
        if(CollectionUtils.isEmpty(list)){
           return null;
        }
        batchInsertSelective(list);
        return list;
    }

    private void batchInsertSelective(List<AdConfig> list) {
        batchDeleteByPackageName(list);
        adConfigMapper.batchInsertSelective(list);
    }

    private void batchDeleteByPackageName(List<AdConfig> list) {
        for (AdConfig record : list) {
            AdConfigExample example = new AdConfigExample();
            example.createCriteria().andPackageNameEqualTo(record.getPackageName());
            adConfigMapper.deleteByExample(example);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中可以使用Apache POI库来进行Excel解析导入操作。以下是一个简单的示例代码: ```java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Iterator; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; public class ExcelParser { public static void main(String[] args) { try { // 读取Excel文件 FileInputStream file = new FileInputStream(new File("example.xlsx")); Workbook workbook = WorkbookFactory.create(file); // 选择工作表 Sheet sheet = workbook.getSheetAt(0); // 迭代行和单元格 Iterator<Row> rowIterator = sheet.iterator(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); // 根据单元格类型进行操作 switch (cell.getCellType()) { case STRING: System.out.print(cell.getStringCellValue() + "\t"); break; case NUMERIC: System.out.print(cell.getNumericCellValue() + "\t"); break; case BOOLEAN: System.out.print(cell.getBooleanCellValue() + "\t"); break; default: System.out.print("\t"); } } System.out.println(); } // 关闭文件流 file.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 这个示例代码会读取名为"example.xlsx"的Excel文件,并输出其中的内容。您可以根据需要进行修改来实现您的具体需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值