将excel转换成xml

之前看过一个ODK(Open Data kit),里面有一个需求就是得把excel转换成xml ,觉得一般不会很常用,有兴趣的人可以看一下

/**
     * 将excel转换成xml
     *
     * @param multipartFile
     * @return
     * @throws IOException
     */
    private String excel2xml(MultipartFile multipartFile) throws IOException {
        String fileName = multipartFile.getOriginalFilename();
        BufferedReader bufferedReader = null;

        String outName = fileName.substring(0, fileName.indexOf(".")).concat(".xml");

        byte[] xlsx = IOUtils.toByteArray(multipartFile.getInputStream());
        File src = new File(fileName);
        File out = new File(outName);
        if (src.exists()) {
            FileUtils.deleteQuietly(src);
        }
        if ((!src.createNewFile()) || (!out.createNewFile())) {
            throw new RuntimeException("空间不足");
        }

        FileUtils.writeByteArrayToFile(src, xlsx);
        String commanderStr = "";
        Properties properties = System.getProperties();
        String os = properties.getProperty("os.name");
        if(os.contains("Linux")){
            commanderStr = "xls2xform ".concat(fileName).concat(" ").concat(outName);
        }else if(os.contains("Windows")){
            commanderStr = "cmd /c xls2xform ".concat(fileName).concat(" ").concat(outName);
        }else{
            throw new RuntimeException("未能识别的操作系统,无法执行Excel转换至xml");
        }

        Process p = Runtime.getRuntime().exec(commanderStr);
        bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = null;
        StringBuilder stringBuilder = new StringBuilder();
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line).append("\n");
        }
        if (stringBuilder.toString().contains("Error")) {
            throw new RuntimeException("Excel格式不标准");
        }
        p.destroy();
        bufferedReader.close();
        
        
        InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(out), StandardCharsets.UTF_8);
        bufferedReader = new BufferedReader(inputStreamReader);
        stringBuilder = new StringBuilder();
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line).append("\n");
        }
        bufferedReader.close();
        FileUtils.deleteQuietly(src);
        FileUtils.deleteQuietly(out);

        return stringBuilder.toString();
    }
}
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页