FileService.java 8.52 KB
Newer Older
eddie.woo's avatar
eddie.woo committed
1 2
package pwc.taxtech.atms.service.impl;

3 4
import java.io.File;
import java.io.IOException;
eddie.woo's avatar
eddie.woo committed
5 6 7 8 9
import java.io.InputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

10 11 12
import org.apache.commons.io.FileUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Sheet;
eddie.woo's avatar
eddie.woo committed
13 14 15 16 17 18 19 20 21 22
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.nutz.lang.Files;
import org.nutz.lang.Lang;
import org.nutz.lang.Streams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

23
import pwc.taxtech.atms.exception.ApplicationException;
eddie.woo's avatar
eddie.woo committed
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
import pwc.taxtech.atms.common.CommonConstants;
import pwc.taxtech.atms.common.CommonUtils;
import pwc.taxtech.atms.dto.OperationResultDto;
import pwc.taxtech.atms.thirdparty.ExcelLogs;
import pwc.taxtech.atms.thirdparty.ExcelUtil;

@Service
public class FileService {

    private static final Logger logger = LoggerFactory.getLogger(FileService.class);

    public OperationResultDto<Object> saveFile(InputStream inputStream, String filePath) {
        logger.debug("保存输入流到指定的路径, filePath:{}", filePath);
        OperationResultDto<Object> operationResultDto = new OperationResultDto<>();
        try {
            Files.write(filePath, inputStream);
            logger.debug("保存成功");
            operationResultDto.setResult(true);
        } catch (Exception e) {
            logger.error("Catch error", e);
            Map<String, String> error = new HashMap<>();
            error.put(CommonUtils.getUUID(), e.getMessage());
            operationResultDto.setResultMsg(CommonConstants.SAVE_FILE_ERROR);
            operationResultDto.setResult(false);
            operationResultDto.setErrors(error);
        }
        Assert.notNull(operationResultDto.getResult(), "Null result");
        return operationResultDto;
    }

    /** 读取Excel输入流, 最后关闭该输入流 */
    @SuppressWarnings("rawtypes")
    public Collection<Map> readExcelAndClose(InputStream inputStream) {
        logger.debug("读取Excel输入流");
        ExcelLogs logs = new ExcelLogs();
        Workbook workBook = null;
        try {
            
                workBook = WorkbookFactory.create(inputStream);
            Collection<Map> result = ExcelUtil.importExcel(Map.class, workBook, null, "yyyy/MM/dd HH:mm:ss", logs, 0);
            if (logs.getHasError() != null && logs.getHasError()) {
                throw new ApplicationException("Cannot read excel file");
            }
            logger.debug("读取Excel输入流成功, result size:{}", result.size());
            return result;
        } catch (Exception e) {
            logger.error("load excel file error", e);
            throw Lang.wrapThrow(e);
        } finally {
            logger.debug("关闭Excel输入流");
            Streams.safeClose(inputStream);
            if(workBook!=null) {
                try {
                    workBook.close();
                }
                catch (Exception e) {
                    logger.error("Error closing workbook", e);
                }
                finally {
                    workBook = null;
                }
            }
        }
    }
    
    /** 读取Excel输入流, 最后关闭该输入流 */
    @SuppressWarnings("rawtypes")
    public Map<String, Collection<Map>> readExcelAndClose(InputStream inputStream, String ...sheetNames) {
        
        logger.debug("读取Excel输入流");
        ExcelLogs logs = new ExcelLogs();
        Workbook workBook = null;
        try {
            workBook = WorkbookFactory.create(inputStream);
            Map<String, Collection<Map>> sheetMap = new HashMap<>();
            for(String sheetName: sheetNames) {
                Collection<Map> result = ExcelUtil.importExcel(Map.class, workBook, sheetName, "yyyy/MM/dd HH:mm:ss", logs, 0);
                if(result!=null) {
                    sheetMap.put(sheetName, result);
                }
            }
            if (logs.getHasError() != null && logs.getHasError()) {
                throw new ApplicationException("Cannot read excel file");
            }
            logger.debug("读取Excel输入流成功, sheets number:{}", sheetMap.size());
            return sheetMap;
        } 
        catch (Exception e) {
            logger.error("load excel file error", e);
            throw Lang.wrapThrow(e);
        }
        finally {
            logger.debug("关闭Excel输入流");
            Streams.safeClose(inputStream);
            if(workBook!=null) {
                try {
                    workBook.close();
                }
                catch (Exception e) {
                    logger.error("Error closing workbook", e);
                }
                finally {
                    workBook = null;
                }
            }
        }
    }
    
    /** 读取Excel输入流, 最后关闭该输入流 */
    public Map<String, Integer> readExcelHeaderAndClose(InputStream inputStream) {
        
        logger.debug("读取Excel输入流");
        ExcelLogs logs = new ExcelLogs();
        Workbook workBook = null;
        try {
            workBook = WorkbookFactory.create(inputStream);
            Map<String, Integer> titleMap = ExcelUtil.importExcelHeader(workBook, null);
            if (logs.getHasError() != null && logs.getHasError()) {
                throw new ApplicationException("Cannot read excel file");
            }
            logger.debug("读取Excel输入流成功, header size:{}", titleMap.size());
            return titleMap;
        } catch (Exception e) {
            logger.error("Load excel file error",e);
            throw Lang.wrapThrow(e);
        } finally {
            logger.debug("关闭Excel输入流");
            Streams.safeClose(inputStream);
            if(workBook!=null) {
                try {
                    workBook.close();
                }
                catch (Exception e) {
                    logger.error("Error closing workbook", e);
                }
                finally {
                    workBook = null;
                }
            }
        }
    }
    
    /** 读取Excel输入流, 最后关闭该输入流 */
    public Map<String, Map<String, Integer>> readExcelHeaderAndClose(InputStream inputStream, String ...sheetNames) {
        
        logger.debug("读取Excel输入流");
        ExcelLogs logs = new ExcelLogs();
        Workbook workBook = null;
        try {
            workBook = WorkbookFactory.create(inputStream);
            Map<String, Map<String, Integer>> sheetTitleMap = new HashMap<>();
            for(String sheetName: sheetNames) {
                Map<String, Integer> titleMap = ExcelUtil.importExcelHeader(workBook, sheetName);
                if(titleMap!=null) {
                    sheetTitleMap.put(sheetName, titleMap);
                }
            }
            if (logs.getHasError() != null && logs.getHasError()) {
                throw new ApplicationException("Cannot read excel file");
            }
            logger.debug("读取Excel输入流成功, sheet size:{}", sheetTitleMap.size());
            return sheetTitleMap;
        } catch (Exception e) {
            logger.error("Load excel file error",e);
            throw Lang.wrapThrow(e);
        } finally {
            logger.debug("关闭Excel输入流");
            Streams.safeClose(inputStream);
            if(workBook!=null) {
                try {
                    workBook.close();
                }
                catch (Exception e) {
                    logger.error("Error closing workbook", e);
                }
                finally {
                    workBook = null;
                }
            }
        }
    }

206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223

    public Workbook getWorkbook(InputStream inputStream, String fileName, String fileDir) throws IOException, InvalidFormatException {
        String filePath = FileUtils.getTempDirectory().getAbsolutePath() + File.separator + fileDir + File.separator
                + CommonUtils.getUUID() + "_" + fileName;
        //保存导入的文件
        OperationResultDto<Object> saveResult = saveFile(inputStream, filePath);
        //判断是否成功导入
        if (saveResult.getResult() != null && !saveResult.getResult()) {
            return null;
        }
        //获取保存文件的输入流
        InputStream newInputStream = Files.findFileAsStream(filePath);

        //通过输入流获取当前workbook
        Workbook workbook = WorkbookFactory.create(newInputStream);
        return workbook;
    }

224

ZeGang Z Si's avatar
ZeGang Z Si committed
225 226 227
    //上传文件


eddie.woo's avatar
eddie.woo committed
228
}