Java poi——excel的模板下載和導入

畢設的項目涉及到了excel的模板下載和導入 記錄一下

maven倉庫
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi-ooxml</artifactId>
	<version>3.17</version>
</dependency>
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi-scratchpad</artifactId>
	<version>3.17</version>
</dependency>

一、下載模板

// excel模板的路徑:webapp/template/excel模板.xls
private String excelTemplate = "/template/\u0065\u0078\u0063\u0065\u006c\u6a21\u677f.xls";

@GetMapping("/excel/download")
	public ResponseEntity<byte[]> download(HttpServletRequest request) throws IOException {
		Path path = Paths.get(request.getServletContext().getRealPath(excelTemplate));
		if (!path.toFile().exists()) {
			throw new FileNotFoundException("文件: " + path + "未被找到.");
		}
		byte[] body = Files.readAllBytes(path);
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Disposition",
				"attchement;filename=" + URLEncoder.encode(FilenameUtils.getName(excelTemplate), "UTF-8"));
		ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, HttpStatus.OK);
		return entity;
	}

二、導入

@PostMapping("/excel/import")
@ResponseBody
public String importFile(MultipartFile file) {
	if (file == null || file.isEmpty()) {
		return "文件不能爲空";
	}
	if (!StringUtil.isExcelFileName(file.getOriginalFilename())) {
		return "只支持xlsx或xls文件";
	}
	String result = importing(file);
	return result;
}

@Transactional(rollbackFor = Exception.class)
	public String importing(MultipartFile file) {
		try (Workbook workbook = WorkbookFactory.create(file.getInputStream())) {
			Sheet sheet = workbook.getSheetAt(0);
			int rowNum = sheet.getLastRowNum();
			List<User> results = new ArrayList<>();
			Integer startRow = 0;
			for (int i = 1; i <= rowNum; i++) {
				
				Row row = sheet.getRow(i);
				if (row == null || i <= startRow) {
					continue;
				}
				
				User user = new User();
				user.setUsername(getStringValue(row.getCell(0)));
				user.setName(getStringValue(row.getCell(1)));
			
				results.add(user);
				
			}
			
			if (results.isEmpty()) {
				return "導入數據爲空";
			}

			// 對導入的數據進行操作 例如插入到數據庫中等
			
			return "success";
		} catch (EncryptedDocumentException | InvalidFormatException | IOException e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
	}
供參考的導入包

在這裏插入圖片描述

jsp

在這裏插入圖片描述

	<button class="btn btn-primary" data-toggle="modal" data-target="#import">
		一鍵導入
	</button>
	
	<div class="modal fade" id="import" tabindex="-1" role="dialog">
		<div class="modal-dialog" role="document">
			<div class="modal-content">
				<div class="modal-header"> 
					<button type="button" class="close" data-dismiss="modal"
						aria-label="Close">
						<span aria-hidden="true">&times;</span>
					</button>
				</div>
				<div class="modal-body">
					<a class="btn btn-primary" href="./excel/download">下載模板</a>
					<hr>
					<div class="alert alert-danger" role="alert" style="display: none;"></div>
					<form action="./excel/import" method="post" enctype="multipart/form-data">
						<div class="form-group">
							<label for="file">選擇文件</label> <input type="file"
								class="form-control-file" name="file" id="importNoFile">
						</div>
					</form>
					<div class="card">
						<div class="card-header">導入說明</div>
						<div class="card-body">
							<p>請下載導入模板按標準填寫</p>
						</div>
					</div> 
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-secondary" data-dismiss="modal">關閉</button>
					<button type="button" class="btn btn-primary" onclick="importing()">確定</button>
				</div>
			</div>
		</div>
	</div>

<script>

function importing() {
	var formData = new FormData();
	formData.append('file', $('#importNoFile')[0].files[0]);
	$.post({
		url: '.',
		data: formData,
		contentType: false,
		processData: false,
		cache: false,
		success: function(data) {
			if (data == 'success') {
				$('#import').modal('toggle');
				$('#importNoFile').val('');
				$('#import .alert').hide();
			} else {
				$('#import .alert').text(data).show();
			}
		},
		error: function() {
			alert('錯誤');
		}
	});
}
</script>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章