利用freemarker+SAX解析xml的方式对excel文件字段校验

利用freemarker对参数进行校验

这篇文章主要用到的技术点:

  • 自定义注解的使用
  • 反射机制
  • SAX解析xml
  • Freemarker的运用

我们在工作中经常需要上传excel文件,然后在对文件中的字段进行校验。如果文件里的字段是反复出现,或者文件的字段比较多的话,这是就会使代码变得繁琐,而且也不容易维护。
比如说像下面那张学生的表格
这里插入图片描述学生
我们需要对上面表中的每个字段做校验
1.userName 必传字段
2. telephone 手机电话号码格式校验
3. email格式的校验
4. birthday 格式的校验
5. userId的生成规则等

有时候我们用自定义注解+反射,往往可以使代码变得清晰明了,不说了,直接上代码:

package com.example.demo.Controller;

import com.example.demo.utils.DealException;
import com.example.demo.utils.ExcelUtils;
import com.example.demo.validate.TemplateXmlUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static freemarker.template.Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS;

@RestController
public class UploadExcelController {
    @RequestMapping("/upload")
    public Object uploadFile(MultipartFile file) throws IOException, TemplateException {
        //读取文件的基本信息
        String filename = file.getOriginalFilename();
        InputStream inputStream = file.getInputStream();
        try {
         //   Workbook workbook = ExcelUtils.buildWorkookFromStream(filename, inputStream);
            //解析excel
            List<Map<String, Object>> maps = ExcelUtils.excelToList(filename, inputStream, 0, 0);
            Configuration configuration = new Configuration(DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
            URL url = this.getClass().getClassLoader().getResource("freemarkers");
            configuration.setDirectoryForTemplateLoading(new File(url.getFile()));
            Template template = configuration.getTemplate("userMapper.ftl");
            HashMap<String, Object> objMap = new HashMap<>();
            objMap.put("maps",maps);
            StringWriter sw = new StringWriter();
            template.process(objMap,sw);
            System.out.println(sw.toString());

 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值