如何使用Spring Boot在模板化的Excel文件中附加JSON数据?

时间:2018-10-26 07:19:35

标签: java excel spring-boot apache-poi

我有一个excel文件模板,其中包含标题和一个按钮。如何使用Spring Boot在该文件中附加JSON数据?

如何开始从excel文件中的特定行附加数据并将其下载到特定位置?

1 个答案:

答案 0 :(得分:0)

我创建了一个示例项目来使其正常工作,基本上我已经创建了2种方法来满足 POST PUT 请求以遵循REST标准,Post请求将总是创建一个文件,即资源,PUT请求会将数据更新到该文件,即追加在请求正文中发送的JSON文本。

这是我的引导程序类

@SpringBootApplication
public class SpringBootWebApplication extends SpringBootServletInitializer {

        @Override
        protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
            return application.sources(SpringBootWebApplication.class);
        }

        public static void main(String[] args) throws Exception {
            SpringApplication.run(SpringBootWebApplication.class, args);
        }
    }

这是我的配置类,它基本上添加了MappingJackson2HttpMessageConverter作为消息转换器来来回解析json数据

@Configuration
@EnableWebMvc
public class AppConfig extends WebMvcConfigurerAdapter{

    @Bean
    public MappingJackson2HttpMessageConverter customJackson2HttpMessageConverter() {
        MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        jsonConverter.setObjectMapper(objectMapper);
        return jsonConverter;
    }
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(customJackson2HttpMessageConverter());
    }
}

最后是将请求映射到xls创建者方法的控制器类

@Controller
public class WelcomeController {

    @RequestMapping(value="/writeData", method=RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> writeJSONDataToFile(@RequestBody(required=true) Map<String, String> input){
        try {  
            String fileName = "C:\\Test\\Sample.xls";
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet();
            int rownum =0;
            for (Entry<String, String> entry : input.entrySet()) {
                HSSFRow row = sheet.createRow(rownum++);
                short cellNum = 0;
                HSSFCell cell1 = row.createCell(cellNum++);
                cell1.setCellValue(entry.getKey());
                HSSFCell cell2 = row.createCell(cellNum++);
                cell2.setCellValue(entry.getValue());
            }
            FileOutputStream fileOutputStream = new FileOutputStream(new File(fileName));
            workbook.write(fileOutputStream); 
            fileOutputStream.close();
            System.out.println("Sample.xls created successfully on disk."); 
        }catch (Exception e) { 
            e.printStackTrace(); 
        }
        return new ResponseEntity<String>("Create", HttpStatus.CREATED);
    }


    @RequestMapping(value="/writeData", method=RequestMethod.PUT, consumes=MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> updateJSONDataToFile(@RequestBody(required=true) Map<String, String> input){
        try {  
            String fileName = "C:\\Test\\Sample.xls";
            HSSFWorkbook workbook = null;
            FileInputStream fileInputStream = null;
            HSSFSheet sheet = null;
            File file = new File(fileName);
            if(file.exists()){
                fileInputStream = new FileInputStream(file); 
                workbook = new HSSFWorkbook(fileInputStream); //Reading from file
                sheet = workbook.getSheetAt(0);
            }else{
                return new ResponseEntity<String>("File doesnt Exists", HttpStatus.BAD_REQUEST);
            }
            int rownum =sheet.getLastRowNum();
            for (Entry<String, String> entry : input.entrySet()) {
                HSSFRow row = sheet.createRow(++rownum);
                short cellNum = row.getLastCellNum();
                HSSFCell cell1 = row.createCell(++cellNum);
                cell1.setCellValue(entry.getKey());
                HSSFCell cell2 = row.createCell(++cellNum);
                cell2.setCellValue(entry.getValue());
            }
            if(fileInputStream!=null)
                fileInputStream.close();

            FileOutputStream fileOutputStream = new FileOutputStream(file);
            workbook.write(fileOutputStream); 
            fileOutputStream.close();
            System.out.println("Sample.xls written/Updated successfully on disk."); 
        }catch (Exception e) { 
            e.printStackTrace(); 
        }
        return new ResponseEntity<String>("updated successfully", HttpStatus.OK);
    }
}

我用过Apache poi-3.15-final.jar