当前位置:   article > 正文

Java实现excel文件上传、解析,对象存储_java 网页上传excel文件

java 网页上传excel文件

1、前端上传文件

  1. <Input.Group compact className='iptUpload'>
  2. <Input style={{width: 'calc(100% - 200px)',}} value={this.state.fileName}/>
  3. <Upload {...props} style={{ paddingLeft: 15 }} fileList={this.state.fileList}>
  4. <Button htmlType="button" type="primary">选择文件</Button>
  5. </Upload>
  6. </Input.Group>
  7. <span>
  8. <Button className='uploadBts' type="primary" disabled={disabled} onClick={() => {this.uploadClick()}}>上&emsp;</Button>
  9. </span>
  10. // 文件上传
  11. uploadClick = () => {
  12. console.log("上传")
  13. const fileName = this.state.fileName;
  14. const Operator = this.state.Operator;
  15. const info = this.state.fileList[0];
  16. const reader = new FileReader()
  17. reader.readAsDataURL(info.originFileObj)
  18. reader.onload = e => {
  19. const { result } = e.target
  20. console.log('result',result)
  21. const TransData = {
  22. TransData:{
  23. BaseInfo: {
  24. TradeType: 'http',
  25. TradeCode: 'S07',
  26. TradeSeq: tools.getTradeSeq(),
  27. TradeDate: tools.getToday(),
  28. TradeTime: tools.getTime(),
  29. Operator: Operator,
  30. Key: tools.getKey(),
  31. },
  32. InputData: {
  33. fileName: fileName,
  34. fileByte: result
  35. }
  36. }
  37. };
  38. axios({
  39. method: 'POST',
  40. url: url + '/fileUrl/uploadFile',
  41. data: TransData,
  42. }).then(response => {
  43. let res = response.data
  44. if (res.TransData.BaseInfo.TranFlag === '0'){
  45. message.success("上传成功")
  46. } else if (res.TransData.BaseInfo.TranFlag != '0') {
  47. message.error('上传失败,' + res.TransData.BaseInfo.ErrorMessage)
  48. } else {
  49. message.error('系统异常')
  50. }
  51. })
  52. .catch(response => {
  53. message.error('系统异常,接口调用失败')
  54. })
  55. }
  56. }

2.后端获取请求报文,解析excel文件存储到数据库,实现对象存储

(1)导入的excel文件sheet页的相关内容      @ExcelProperty(value = {"标题","对应列名"})

  1. package com.entity.pojo;
  2. import com.alibaba.excel.annotation.ExcelProperty;
  3. import lombok.Data;
  4. import java.io.Serializable;
  5. /**
  6. * title: SetReq
  7. * description:设置上传字段
  8. */
  9. @Data
  10. public class SetReq implements Serializable {
  11. @ExcelProperty(value = {"导入","序号"})
  12. private String serialNo;
  13. @ExcelProperty(value = {"导入","编码"})
  14. private String no;
  15. @ExcelProperty(value = {"导入","名称"})
  16. private String name;
  17. @ExcelProperty(value = {"导入","机构编码"})
  18. private String organ;
  19. @ExcelProperty(value = {"导入","机构名称"})
  20. private String organName;
  21. @ExcelProperty(value = {"导入","收费类型"})
  22. private String type;
  23. @ExcelProperty(value = {"导入","生效日期"})
  24. private String effectiveDate;
  25. @ExcelProperty(value = {"导入","截止日期"})
  26. private String expirationDate;
  27. @ExcelProperty(value = {"导入","备注"})
  28. private String remarks;
  29. }

(2)Java获取报文,上传,解析

  1. package com.biz;
  2. import com.entity.pojo.*;
  3. import com.util.*;
  4. import org.apache.commons.lang3.StringUtils;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Component;
  7. import org.springframework.web.multipart.MultipartFile;
  8. import java.io.File;
  9. import java.io.FileInputStream;
  10. import java.io.InputStream;
  11. import java.math.BigDecimal;
  12. import java.util.ArrayList;
  13. import java.util.HashMap;
  14. import java.util.List;
  15. /**
  16. * title: UploadBiz
  17. * description:上传
  18. */
  19. @Component
  20. public class UploadBiz {
  21. @Autowired
  22. private FileUtil fileUtil;
  23. public String upload(String requestJson) throws Exception {
  24. String responseJson;
  25. File file = null;
  26. try {
  27. // 请求报文转换
  28. JSONObject inputData = JSON.parseObject(requestMessage).getJSONObject("TransData").getJSONObject("InputData");
  29. String fileByte = inputData.getString("fileByte");
  30. // 校验文件名是否有中文
  31. String fileName = inputData.getString("fileName");
  32. if(this.verifyChinese(fileName)){
  33. fileName = "uploadFile.xlsx";
  34. }
  35. // 获取文件名称
  36. fileName = fileUtil.getUploadFileName(fileName);
  37. // base64转multipartFile
  38. MultipartFile multipartFile = Base64DecodeMultipartFile.base64Convert(fileByte);
  39. file = fileUtil.MultipartFileToFile(multipartFile);
  40. // 校验文件是否存在
  41. CheckDataUtil.checkFileExists(file);
  42. // 文件上传
  43. fileUtil.uploadFile(fileName, file);
  44. // 文件转为流
  45. InputStream excelInputStream = new FileInputStream(file);
  46. //定义返回数据
  47. List<FailInfo> failList = new ArrayList<>();
  48. //读取整个Excel
  49. List<SetReq> setReqList = EasyExcelUtil.readExcel(excelInputStream, SetReq.class, new EasyExcelUtil.ExcelListener<>());
  50. SetReqList.forEach(System.out::println); //打印读取的excel文件
  51. for (SetReq req : setReqList) {
  52. String serialNo = req.getSerialNo();
  53. StringBuilder errorMessage = new StringBuilder();
  54. //校验上传字段
  55. checkFieldData(req, errorMessage);
  56. // 如果导入结束给出成功与否提示和导入失败的每条数据的失败原因;
  57. if (errorMessage.length() > 0) {
  58. FailInfo failInfo = new FailInfo();
  59. failInfo.setRow(serialNo);
  60. failInfo.setMessage(errorMessage.toString());
  61. failList.add(failInfo);
  62. }
  63. }
  64. //判断导入文件是否有失败的记录,如果有,则导入文件中的所有记录均不导入,修改文件后可重新导入
  65. if (failList != null && failList.size() > 0) {
  66. responseJson = MessageConvertUtil.xStreamToJson(failList);
  67. //删除临时文件
  68. fileUtil.delete(file);
  69. return responseJson;
  70. }
  71. // 没有导入失败的记录,则写入数据库
  72. for (SetReq reqest : setReqList) {
  73. int record = insertData(reqest);
  74. if (record <= 0) {
  75. FailInfo failInfo = new FailInfo();
  76. failInfo.setRow(reqest.getSerialNo());
  77. failInfo.setMessage("数据库更新失败!");
  78. failList.add(failInfo);
  79. }
  80. }
  81. responseJson = MessageConvertUtil.xStreamToJson(failList);
  82. //删除临时文件
  83. fileUtil.delete(file);
  84. }catch (Exception e) {
  85. //删除临时文件
  86. fileUtil.delete(file);
  87. throw e;
  88. }
  89. return responseJson;
  90. }
  91. /**
  92. * 校验文件名是否有中文
  93. * @param fileName
  94. * @throws
  95. */
  96. public static boolean verifyChinese(String fileName) {
  97. String pattern = "[\u4e00-\u9fa5]";
  98. Pattern r = Pattern.compile(pattern);
  99. Matcher m = r.matcher(fileName);
  100. return m.find();
  101. }
  102. }

(3)文件处理类

  1. package com.util;
  2. import com.amazonaws.ClientConfiguration;
  3. import com.amazonaws.Protocol;
  4. import com.amazonaws.auth.AWSCredentials;
  5. import com.amazonaws.auth.BasicAWSCredentials;
  6. import com.amazonaws.services.s3.AmazonS3;
  7. import com.amazonaws.services.s3.AmazonS3Client;
  8. import com.amazonaws.services.s3.S3ClientOptions;
  9. import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
  10. import com.amazonaws.services.s3.model.PutObjectRequest;
  11. import org.apache.commons.lang3.StringUtils;
  12. import org.slf4j.Logger;
  13. import org.slf4j.LoggerFactory;
  14. import org.springframework.beans.factory.annotation.Autowired;
  15. import org.springframework.stereotype.Component;
  16. import org.springframework.web.multipart.MultipartFile;
  17. import java.io.*;
  18. /**
  19. * Title: FileUtil
  20. * Description: 文件处理类
  21. */
  22. @Component
  23. public class FileUtil {
  24. private static final Logger log= LoggerFactory.getLogger(FileUtil.class);
  25. SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
  26. @Autowired
  27. private UploadLogMapper UploadLogMapper;
  28. @Autowired
  29. private UploadConfigCephMapper UploadConfigCephMapper;
  30. /**
  31. * 文件上传
  32. *
  33. * @param fileName
  34. * @param file
  35. * @return
  36. */
  37. public void uploadFile(String fileName, File file){
  38. String filePath = "";
  39. try {
  40. UploadConfigCeph config = getConfig(1);
  41. BasicAWSCredentials awsCreds = new BasicAWSCredentials(config.getAccessKey(), config.getSecretKey());
  42. //根据ceph连接配置,获取连接对象
  43. AmazonS3 awsConnection = getAWSConnection(config);
  44. String key = sdf.format(new Date())+"/"+fileName;
  45. PutObjectRequest request = new PutObjectRequest(config.getBucketName(), key, file);
  46. awsConnection.putObject(request);
  47. GeneratePresignedUrlRequest requests = new GeneratePresignedUrlRequest(config.getBucketName(), key);
  48. filePath = awsConnection.generatePresignedUrl(requests).getPath();
  49. } catch (Exception e) {
  50. throw e;
  51. }
  52. }
  53. /**
  54. * 根绝configId获取连接配置
  55. * @param configId配置表主键
  56. */
  57. public UploadConfigCeph getConfig(Integer configId) {
  58. return UploadConfigCephMapper.selectByPrimaryKey(configId);
  59. }
  60. /**
  61. * 根据连接配置,获取连接对象
  62. * @param config配置类
  63. * @return com.amazonaws.services.s3.AmazonS3 连接对象
  64. */
  65. public AmazonS3 getAWSConnection(UploadConfigCeph config) {
  66. //获取完整连接路径
  67. String endPoint = config.getEndpoint();
  68. //创建AWS配置
  69. AWSCredentials credentials = new BasicAWSCredentials(config.getAccessKey(), config.getSecretKey());
  70. ClientConfiguration clientConfig = new ClientConfiguration();
  71. //设置传输权限HTTPS or HTTP
  72. if (endPoint.startsWith(CommonValue.HTTPS)) {
  73. clientConfig.setProtocol(Protocol.HTTPS);
  74. } else {
  75. clientConfig.setProtocol(Protocol.HTTP);
  76. }
  77. //创建连接
  78. AmazonS3 conn = new AmazonS3Client(credentials, clientConfig);
  79. //如果链接是域名,打开域名拼接方式
  80. conn.setS3ClientOptions(S3ClientOptions.builder().setPathStyleAccess(true).build());
  81. //发起连接
  82. conn.setEndpoint(endPoint);
  83. return conn;
  84. }
  85. /**
  86. * 获取文件名称
  87. * @param fileName
  88. */
  89. public String getUploadFileName(String fileName) {
  90. if (StringUtils.isEmpty(fileName)) {
  91. log.info("文件名称fileName为空");
  92. }
  93. //获得上传的文件名,例如ooa.jpg,只需要ooa,其前面的后面的都不需要,可以使用年月日时分秒毫秒设置文件名
  94. String fName = fileName.substring(0, fileName.lastIndexOf(".")) + DateUtil.getDateTime17();
  95. //获得文件的后缀名
  96. String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
  97. return fName +"."+ fileExtension;
  98. }
  99. /**
  100. * MultipartFile 转 File
  101. * @param multipartFile
  102. */
  103. public static File MultipartFileToFile(MultipartFile multipartFile) {
  104. File file = null;
  105. //判断是否为null
  106. if (multipartFile.equals("") || multipartFile.getSize() <= 0) {
  107. return file;
  108. }
  109. //MultipartFile转换为File
  110. InputStream ins = null;
  111. OutputStream os = null;
  112. try {
  113. ins = multipartFile.getInputStream();
  114. file = new File(multipartFile.getOriginalFilename());
  115. os = new FileOutputStream(file);
  116. int bytesRead = 0;
  117. byte[] buffer = new byte[8192];
  118. while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
  119. os.write(buffer, 0, bytesRead);
  120. }
  121. } catch (IOException e) {
  122. e.printStackTrace();
  123. }finally {
  124. if(os != null){
  125. try {
  126. os.flush();
  127. os.close();
  128. } catch (IOException e) {
  129. e.printStackTrace();
  130. }
  131. }
  132. if(ins != null){
  133. try {
  134. ins.close();
  135. } catch (IOException e) {
  136. e.printStackTrace();
  137. }
  138. }
  139. }
  140. return file;
  141. }
  142. /**
  143. * 操作完上的文件 需要删除在根目录下生成的文件
  144. * @param file
  145. */
  146. public static void delete(File file){
  147. File f = new File(file.toURI());
  148. if (f.delete()){
  149. System.out.println("删除成功");
  150. }else {
  151. System.out.println("删除失败");
  152. }
  153. }
  154. }

(3)excel解析

  1. package com.util;
  2. import com.alibaba.excel.EasyExcel;
  3. import com.alibaba.excel.ExcelReader;
  4. import com.alibaba.excel.context.AnalysisContext;
  5. import com.alibaba.excel.event.AnalysisEventListener;
  6. import com.alibaba.excel.read.builder.ExcelReaderBuilder;
  7. import com.sinosoft.microservice.entity.pojo.HandlingFeeRateSetReq;
  8. import lombok.extern.slf4j.Slf4j;
  9. import org.apache.commons.lang3.ObjectUtils;
  10. import java.io.File;
  11. import java.io.FileInputStream;
  12. import java.io.InputStream;
  13. import java.util.ArrayList;
  14. import java.util.List;
  15. /**
  16. * ClassName:EasyExcel工具类
  17. */
  18. @Slf4j
  19. public class EasyExcelUtil {
  20. /**
  21. * 读取文件解析监听类,此类供外部实例化使用需要设置为静态类
  22. */
  23. public static class ExcelListener<T> extends AnalysisEventListener<T>{
  24. // 存放读取后的数据
  25. public List<T> datas = new ArrayList<>();
  26. // 读取数据,一条一条读取
  27. @Override
  28. public void invoke(T t, AnalysisContext analysisContext) {
  29. datas.add(t);
  30. }
  31. // 解析完毕之后执行
  32. @Override
  33. public void doAfterAllAnalysed(AnalysisContext analysisContext) {
  34. log.info("读取数据条数:{}条!", datas.size());
  35. }
  36. public List<T> getDatas(){
  37. return this.datas;
  38. }
  39. }
  40. /**
  41. * 读取Excel文件返回数据集合,不包含表头,默认读取第一个sheet数据
  42. * @param inputStream 输入流
  43. * @param tClass 数据映射类
  44. * @param excelListener 读取监听类
  45. * @return List 结果集
  46. */
  47. public static <T> List<T> readExcel(InputStream inputStream, Class<T> tClass, ExcelListener<T> excelListener){
  48. if(ObjectUtils.isEmpty(inputStream) || ObjectUtils.isEmpty(tClass) || ObjectUtils.isEmpty(excelListener)){
  49. return null;
  50. }
  51. ExcelReaderBuilder read = EasyExcel.read(inputStream, tClass, excelListener);
  52. //.excelType("手续费率导入11111.xlsx".contains(ExcelTypeEnum.XLSX.getValue()) ? ExcelTypeEnum.XLSX : ExcelTypeEnum.XLS);
  53. read.sheet().doRead();
  54. return excelListener.getDatas();
  55. }
  56. /**
  57. * 读取Excel文件返回数据集合,不包含表头,读取第n个sheet数据,不设置sheet就读取全部个sheet数据,不设置sheet就读取全部
  58. * @param inputStream 输入流
  59. * @param tClass 数据映射类
  60. * @param excelListener 读取监听类
  61. * @return List 结果集
  62. */
  63. public static <T> List<T> readExcel(InputStream inputStream, Integer sheetNo, Class<T> tClass, ExcelListener<T> excelListener){
  64. if(ObjectUtils.isEmpty(inputStream) || ObjectUtils.isEmpty(tClass) || ObjectUtils.isEmpty(excelListener)){
  65. return null;
  66. }
  67. ExcelReaderBuilder read = EasyExcel.read(inputStream, tClass, excelListener);
  68. if(ObjectUtils.isNotEmpty(sheetNo)){
  69. read.sheet(sheetNo).doRead();
  70. }else{
  71. ExcelReader excelReader = read.build();
  72. excelReader.readAll();
  73. excelReader.finish();
  74. }
  75. return excelListener.getDatas();
  76. }
  77. }

注意:easyexcel要解析wps的需要使用高版本的依赖(低版本只能解析office),例如:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>3.0.5</version>
</dependency>

主要用到的依赖

<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-java-sdk-s3</artifactId>
    <version>1.11.98</version>
</dependency>

Base64DecodeMultipartFile

  1. package com.sinosoft.microservice.util;
  2. import org.springframework.web.multipart.MultipartFile;
  3. import sun.misc.BASE64Decoder;
  4. import java.io.*;
  5. /**
  6. * base64转为multipartFile工具类
  7. *
  8. */
  9. public class Base64DecodeMultipartFile implements MultipartFile {
  10. private final byte[] imgContent;
  11. private final String header;
  12. public Base64DecodeMultipartFile(byte[] imgContent, String header) {
  13. this.imgContent = imgContent;
  14. this.header = header.split(";")[0];
  15. }
  16. @Override
  17. public String getName() {
  18. return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1];
  19. }
  20. @Override
  21. public String getOriginalFilename() {
  22. return System.currentTimeMillis() + (int) Math.random() * 10000 + "." + header.split("/")[1];
  23. }
  24. @Override
  25. public String getContentType() {
  26. return header.split(":")[1];
  27. }
  28. @Override
  29. public boolean isEmpty() {
  30. return imgContent == null || imgContent.length == 0;
  31. }
  32. @Override
  33. public long getSize() {
  34. return imgContent.length;
  35. }
  36. @Override
  37. public byte[] getBytes() throws IOException {
  38. return imgContent;
  39. }
  40. @Override
  41. public InputStream getInputStream() throws IOException {
  42. return new ByteArrayInputStream(imgContent);
  43. }
  44. @Override
  45. public void transferTo(File dest) throws IOException, IllegalStateException {
  46. new FileOutputStream(dest).write(imgContent);
  47. }
  48. /**
  49. * base64转multipartFile
  50. *
  51. * @param base64
  52. * @return
  53. */
  54. public static MultipartFile base64Convert(String base64) {
  55. String[] baseStrs = base64.split(",");
  56. BASE64Decoder decoder = new BASE64Decoder();
  57. byte[] b = new byte[0];
  58. try {
  59. b = decoder.decodeBuffer(baseStrs[1]);
  60. } catch (IOException e) {
  61. e.printStackTrace();
  62. }
  63. for (int i = 0; i < b.length; ++i) {
  64. if (b[i] < 0) {
  65. b[i] += 256;
  66. }
  67. }
  68. return new Base64DecodeMultipartFile(b, baseStrs[0]);
  69. }
  70. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/591755
推荐阅读
相关标签
  

闽ICP备14008679号