上传下载文件,下载excel

文章简介
上传下载文件:

下载,解析excel,下载excle模板

  • 上传下载文件

描述:上传文件

private String saveAttachment(String filePath, MultipartFile file) throws IOException {
        String attachNo = UUID.randomUUID().toString().replaceAll("-", "");
        String fileName = file.getOriginalFilename();
        String newName = attachNo + fileName.substring(fileName.lastIndexOf("."));
        String url = newName;     //TODO 暂定url
        File saveFile = new File(filePath + newName);
        //判断文件父目录是否存在
        if (!saveFile.getParentFile().exists()) {
            saveFile.getParentFile().mkdir();
        }
        file.transferTo(new File(saveFile.getAbsolutePath()));
        return newName;
    }

/**
     * 描述:上传文件
     *
     * @param file:文件集合
     * @param FileDetails:文件描述
     * @param catalogId:目录id
     * @return Boolean
     * @author zhangruiguang
     * @version 2020/7/10 10:15
     */
    @PostMapping("/upload-illustration")
    @Transactional
    public Boolean uploadIllustration(@RequestParam("file") List<MultipartFile> file, @RequestParam("FileDetails") String FileDetails, @RequestParam("CatalogId") String catalogId, HttpServletRequest request) throws IOException {

        try {
            MyAssert.isTrue(file.size()!=0, "文件为空");
            OAuthUserBean userBean = UserBeanUtil.getUserBean(request);
            List<KnowledgeFile> knowFileList = new ArrayList();
            KnowledgeFile fileBean = null;
            String fileType = null;
            String fileName = null;
            for (int i = 0; i < file.size(); i++) {

                fileName = file.get(i).getOriginalFilename();
                MyAssert.notEmpty(fileName, "文件名错误");
                String type = fileName.contains(".") ? fileName.substring(fileName.lastIndexOf(".") + 1) : null;

                //boolean isType = fileName.matches(fileUploadAllowFormat);
                if (file.isEmpty() || !fileUploadAllowFormat.contains(type)) {
                    throw new ResponseException(
                            KnowledgeReturnCodeBean.UPLOAD_ILLUSTRATION_FILE_ISEMPTY, "上传失败,请选择文件");
                }
            }

            String fileID = fileType + "_" + System.currentTimeMillis();
            // SimpleDateFormat dateFormat = new SimpleDateFormat("/yyyy/MM/dd");
            String tempPath = knownFilePath + "/temp/";
            File dir = new File(tempPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            for (int i = 0; i < file.size(); i++) {
                fileBean = new KnowledgeFile();
                String url = saveAttachment(tempPath, file.get(i));//保存文件
                String fileId = UUID.randomUUID().toString().replace("-", "");
                fileBean.setId(fileId);
                fileBean.setCatalogId(catalogId);
                fileBean.setName(file.get(i).getOriginalFilename());
                fileBean.setFilePath(url);
                fileBean.setDescription(FileDetails);
                fileBean.setUploader(userBean.getId());
                fileBean.setUploadTime(new Date());
                fileBean.setIsPublish("0");
                fileBean.setFileSize(new BigDecimal(file.get(i).getSize()));

                knowFileList.add(fileBean);
            }
            knowledgeFileService.saveBatch(knowFileList);
            return true;

        } catch (IOException e) {
            throw new ResponseException(KnowledgeReturnCodeBean.UPLOAD_ILLUSTRATION_IOEXCEPTION, e.toString());
        }
    }

描述:文件下载相关代码

  /**
     * 描述:文件下载相关代码
     *
     * @param id:文件id
     * @return 无
     * @author zhangruiguang
     * @version 2020/7/10 10:15
     */
    @GetMapping("/resource/{id}")
    public void downloadFile(HttpServletResponse response, @PathVariable String id) throws Exception {


        KnowledgeFile knownFile = knowledgeFileService.getById(id);
        String fileName = knownFile.getName();
        String filePath = knownFilePath + "\\temp\\" + knownFile.getFilePath();

        if (filePath != null) {
            File file = new File(filePath);
          //  file = new File(file.getAbsolutePath());
            if (file.exists()) {
                response.setContentType("application/force-download");
                response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
                response.setContentType("multipart/form-data;charset=UTF-8");
                response.setHeader(
                        "Content-Disposition",
                        "attachment;fileName="
                                + new String(fileName.getBytes("GB2312"), StandardCharsets.ISO_8859_1));
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

  • 下载excel
Workbook wkb = OutExcelUtil.toExcel("xls", "员工表",
                new String[]{"员工id","中文名","英文名","性别","身份证号","邮箱","座机号码","手机号码","绑定手机设备码","系统","系统版本","绑定电脑设备码", "部门"},
                funcList, umList);

            String filename = CommonUtil.getCurrentTime() + ".xlsx";
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            wkb.write(response.getOutputStream());
  • 解析excel
    工具类:
package com.kingpoint.awork.contacts.util;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 解析xls,xlsx文件工具类
 * @author Administrator
 *
 */
public class ReadExcelUtils {
	private Logger logger = LoggerFactory.getLogger(ReadExcelUtils.class);
	private Workbook wb;
	private Sheet sheet;
	private Row row;

	public ReadExcelUtils(String fileName, InputStream in) {
		if(fileName==null || in == null){
			wb = null;
			return;
		}
		try {
			//以xlsx解析
			wb = new XSSFWorkbook(in);
		} catch (Exception e){
			logger.error(e.toString());
			wb = null;
		}
	}

	/**
	 * 读取Excel数据内容
	 * 
	 * @return Map 包含单元格数据内容的Map对象
	 */
	public Map<Integer, Map<Integer,Object>> readExcelContent() throws Exception{
		if(wb==null){
			throw new Exception("Workbook对象为空!");
		}
		Map<Integer, Map<Integer,Object>> content = new HashMap<Integer, Map<Integer,Object>>();
		
		sheet = wb.getSheetAt(0);
		// 得到总行数
		int rowNum = sheet.getLastRowNum();
		row = sheet.getRow(0);

		for (int i = 0; i <= rowNum; i++) {
			row = sheet.getRow(i);
			int j = 0;
			Map<Integer,Object> cellValue = new HashMap<>();
			int colNum = row.getLastCellNum();
			while (j < colNum) {
				String obj;
				/*row.getCell(x)获取指定单元格内的数据*/
				if (row.getCell(j) != null) {
					//把每个单元格内的值都转成String类型
					if(row.getCell(j).getCellType() == Cell.CELL_TYPE_NUMERIC && HSSFDateUtil.isCellDateFormatted(row.getCell(j))) {
						Date date = row.getCell(j).getDateCellValue();
						SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy年MM月dd日");	
				        obj = dateFormat.format(date);
					}
					else {
						row.getCell(j).setCellType(Cell.CELL_TYPE_STRING);
						obj = row.getCell(j).getStringCellValue();
					}
				}else{
					//单元格内无数据
					obj = "";
				}
				cellValue.put(j, obj);
				j++;
			}
			content.put(i, cellValue);
		}
		return content;
	}
}

例子:

  @PostMapping("/{id}/user/batch-add")
    @AutoReturnCode(ContactsReturnCodeBean.FAILURE_ADD_USER_BATCH)
    public ResponseBean batchNew(@PathVariable String id, @RequestParam MultipartFile userFile, @RequestParam String orgId, HttpServletRequest request) {
String fileName = userFile.getOriginalFilename();
        InputStream inputStream;
        Map<Integer, Map<Integer, Object>> map;
        try {
            inputStream = userFile.getInputStream();
            ReadExcelUtils readExcel = new ReadExcelUtils(fileName, inputStream);
            map = readExcel.readExcelContent();
        } catch (Exception e) {
            ServiceLoggerTracer.record("contacts.UserController.batch-add", ServiceLoggerUtil.getExceptionStack(e));
            throw new AutoReturnCodeException("读取文件失败");
        }


}
  • 下载excle模板
@PostMapping("/{id}/down-import-template")
    @AutoReturnCode(ContactsReturnCodeBean.FAILURE_DOWNLOAD_TEMPLATE)
    public ResponseBean downloadTemplate(HttpServletResponse response){
        try {
            File file = new File(filePath);
            if(!file.exists()){
                throw new AutoReturnCodeException("未找到导出文件");
            }

            String filename = "template.xlsx";
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            FileUtils.copyFile(file, response.getOutputStream());
            return null;
        } catch (Exception e) {
            ServiceLoggerTracer.record("partners.PartnersController.downloadTemplate", ServiceLoggerUtil.getExceptionStack(e));
            throw new AutoReturnCodeException("导出失败");
        }
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值