因为业务需要,就写了一个例子
代码很详细了,这里不解释了
package com.ctsi.dataservice.controller;
import com.ctsi.core.common.entity.ApiResult;
import com.ctsi.core.common.utils.ApiResultUtil;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/test")
@ApiSupport(order = 12)
@Api(tags = "测试", description = "测试")
@ApiResponses(value = {@ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 500, message = "ERROR", response = ApiResult.class)})
public class TestController {
@PostMapping("/v1/dealfile")
@ApiOperation("测试上传")
@ApiOperationSupport(order = 1)
public ApiResult<String> dealfile(@RequestParam("file") MultipartFile file) throws IOException {
Path filePath = uploadFile(file);
System.out.println("上传完成");
Path fullPath = Paths.get(filePath.toString());
Path directoryPath = fullPath.getParent(); //
System.out.println("解压完成");
searchExcel(extractXlsXlsxFiles(directoryPath));
System.out.println("遍历excel");
return ApiResultUtil.createSuccessApiResult("查询成功",null);
//删除
}
private void searchExcel(String directoryPath) {
//遍历excel
File directory = new File(directoryPath);
// Get all files in the directory
File[] files = directory.listFiles((dir, name) -> name.endsWith(".xls") || name.endsWith(".xlsx"));
if (files != null) {
for (File file : files) {
try (FileInputStream fis = new FileInputStream(file)) {
Workbook workbook = WorkbookFactory.create(fis);
Sheet sheet = workbook.getSheetAt(0); // Assuming 'sheet1' is the first sheet
DataFormatter formatter = new DataFormatter();
// Skip the first row
boolean skipFirstRow = true;
for (Row row : sheet) {
if (skipFirstRow) {
skipFirstRow = false;
continue;
}
for (Cell cell : row) {
String cellValue = formatter.formatCellValue(cell);
System.out.print(cellValue + "\t");
}
System.out.println();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public String extractXlsXlsxFiles(Path path) throws IOException {
// 获取当前时间戳,作为新文件夹的名称
long timestamp = System.currentTimeMillis();
// 在当前路径下创建以时间戳命名的文件夹
Path extractDir = path.resolve(timestamp + "");
Files.createDirectory(extractDir);
// 获取所有zip文件
DirectoryStream<Path> directoryStream = Files.newDirectoryStream(path, "*.zip");
for (Path zipFilePath : directoryStream) {
try (ZipFile zipFile = new ZipFile(zipFilePath.toFile())) {
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
String entryName = entry.getName();
// 只解压.xls和.xlsx文件
if (entryName.endsWith(".xls") || entryName.endsWith(".xlsx")) {
Path extractedFilePath = extractDir.resolve(entryName);
if (!entry.isDirectory()) {
try (InputStream is = zipFile.getInputStream(entry);
OutputStream os = Files.newOutputStream(extractedFilePath)) {
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) >= 0) {
os.write(buffer, 0, length);
}
}
}
}
}
}
}
return extractDir.toString();
}
public Path uploadFile(MultipartFile file) {
if (file.isEmpty()) {
System.out.println("File is empty");
return null;
}
// 获取环境变量中配置的上传目录,或者直接指定路径
String uploadDir = System.getenv("UPLOAD_DIR");
if (uploadDir == null || uploadDir.isEmpty()) {
// 如果环境变量未设置,则使用默认路径
uploadDir = "D:\\code\\upload\\"+ LocalDate.now();
}
// 构建文件完整路径
String filename = file.getOriginalFilename();
Path path = Paths.get(uploadDir + File.separator + filename);
// 检查文件是否已存在
if (Files.exists(path)) {
System.out.println("File already exists: " + filename);
return null;
}
try {
byte[] bytes = file.getBytes();
File directory = new File(uploadDir);
if (!directory.exists()) {
directory.mkdirs();
}
Files.write(path, bytes);
System.out.println("File uploaded successfully: " + file.getOriginalFilename());
return path;
} catch (IOException e) {
e.printStackTrace();
System.out.println("File upload failed: " + e.getMessage());
return null;
}
}
}