@GetMapping("/export") public void export(HttpServletResponse response) throws Exception { // 从数据库查询出所有的数据 List<Comment> list = commentService.list(); // 在内存操作,写出到浏览器 ExcelWriter writer = ExcelUtil.getWriter(true); // 一次性写出list内的对象到excel,使用默认样式,强制输出标题 writer.write(list, true); // 设置浏览器响应的格式 response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"); String fileName = URLEncoder.encode("Comment信息表", "UTF-8"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx"); ServletOutputStream out = response.getOutputStream(); writer.flush(out, true); out.close(); writer.close(); }
时间: 2023-06-20 08:07:41 浏览: 102
这段代码是一个 Spring Boot 的 Controller 中的方法,用于导出 Comment 数据到 Excel 文件并下载。具体流程如下:
1. 通过 commentService.list() 方法从数据库中查询出所有的 Comment 数据保存到 list 中。
2. 使用 EasyExcel 工具类的 ExcelUtil.getWriter() 方法创建 ExcelWriter 对象,该对象可以将数据写入到内存中的 Excel 文件中。
3. 调用 ExcelWriter 对象的 write() 方法将 list 中的数据写入到 Excel 文件中。
4. 设置 HttpServletResponse 的响应头信息,包括 Content-Type 和 Content-Disposition,告诉浏览器将要下载的文件类型和文件名。
5. 调用 HttpServletResponse 的 getOutputStream() 方法获取输出流,将 Excel 文件内容写入到输出流中,实现文件下载。
6. 关闭 ExcelWriter 对象和输出流。
需要注意的是,这段代码中使用了 EasyExcel 工具类来处理 Excel 文件的读写,需要先在项目的 pom.xml 文件中添加 EasyExcel 的依赖。
相关问题
/** * 导出接口 */ @GetMapping("/export") public void export(HttpServletResponse response) throws Exception { // 从数据库查询出所有的数据 List<Comments> list = commentsService.list(); // 在内存操作,写出到浏览器 ExcelWriter writer = ExcelUtil.getWriter(true); // 一次性写出list内的对象到excel,使用默认样式,强制输出标题 writer.write(list, true); // 设置浏览器响应的格式 response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"); String fileName = URLEncoder.encode("Comments信息表", "UTF-8"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx"); ServletOutputStream out = response.getOutputStream(); writer.flush(out, true); out.close(); writer.close(); } /** * excel 导入 */ @PostMapping("/import") public Result imp(MultipartFile file) throws Exception { InputStream inputStream = file.getInputStream(); ExcelReader reader = ExcelUtil.getReader(inputStream); // 通过 javabean的方式读取Excel内的对象,但是要求表头必须是英文,跟javabean的属性要对应起来 List<Comments> list = reader.readAll(Comments.class); commentsService.saveBatch(list); return Result.success(); }
这段代码是一个基于Spring Boot框架的Web应用程序的Controller,实现了Excel文件的导入和导出功能。
其中,export方法使用@GetMapping注解,表示该方法可以通过GET请求访问,接收一个HttpServletResponse类型的参数response,把数据库中的所有Comments对象查询出来,使用ExcelUtil将数据写入Excel文件,再将Excel文件响应给浏览器进行下载。
import方法使用@PostMapping注解,表示该方法可以通过POST请求访问,接收一个MultipartFile类型的参数file,从该文件中读取数据,使用ExcelUtil将数据读入Comments对象列表,再将该列表批量插入进数据库。
需要注意的是,在导出Excel文件时,需要设置响应的Content-Type为"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",并使用URLEncoder对文件名进行编码,避免出现中文乱码问题。同时,使用flush和close方法将数据输出到response的输出流中,完成响应的操作。
<h1>上传/下载文件</h1> <form method="post" action="/file/upload" enctype="multipart/form-data"> <input type="file" name="file" id="fileInput"/> <input type="submit" value="上传" /> </form> <hr> <form method="post" action="/file/download" > <input type="text" name="fileName" placeholder="请输入文件名" /> <input type="submit" value="下载" id="downloadBtn" /> </form> public class SFTPUtil { private static final String host = "10.60.0.160"; private static final int port = 22; private static final String username = "root"; private static final String password = "Z20"; private static Session session = null; public static void connect() throws Exception { } public static void upload(MultipartFile file, String path, String fileName) throws Exception { } public static boolean download(HttpServletResponse response, String path, String fileName) throws Exception { } @Controller @RequestMapping("/file") public class FileController { private static final String UPLOAD_PATH = "/data/sftp/adtuser1/upload/winbidding/"; private static final String DOWNLOAD_PATH = "/data/sftp/adtuser1/upload/winbidding/"; @PostMapping("/upload") @ResponseBody public ModelAndView upload(@RequestParam("file") MultipartFile file) { } @PostMapping("/download") public ModelAndView download(@RequestParam("fileName") String fileName, HttpServletResponse response) throws Exception { } 数据库有host port username password UPLOAD_PATH DOWNLOAD_PATH csmc字段,把上边写死的改成数据库查询,前台页面增加csmc字段下拉框,根据csmc字段把查出来的配置数据完成上传下载功能,用的mysql数据库,把代码改好写出来
首先需要在数据库中创建一个表,用于存储SFTP连接的相关信息:
```sql
CREATE TABLE sftp_config (
id INT PRIMARY KEY AUTO_INCREMENT,
csmc VARCHAR(50),
host VARCHAR(50),
port INT,
username VARCHAR(50),
password VARCHAR(50),
upload_path VARCHAR(255),
download_path VARCHAR(255)
);
```
然后在Spring Boot项目中创建一个SFTPUtil类,用于实现SFTP上传和下载功能:
```java
import com.jcraft.jsch.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.Properties;
public class SFTPUtil {
private String host;
private int port;
private String username;
private String password;
private String uploadPath;
private String downloadPath;
private Session session;
public SFTPUtil(String host, int port, String username, String password, String uploadPath, String downloadPath) {
this.host = host;
this.port = port;
this.username = username;
this.password = password;
this.uploadPath = uploadPath;
this.downloadPath = downloadPath;
}
public void connect() throws Exception {
JSch jsch = new JSch();
session = jsch.getSession(username, host, port);
session.setPassword(password);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
}
public void upload(MultipartFile file, String fileName) throws Exception {
ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
channel.connect();
channel.cd(uploadPath);
InputStream inputStream = file.getInputStream();
channel.put(inputStream, fileName);
inputStream.close();
channel.disconnect();
}
public boolean download(HttpServletResponse response, String fileName) throws Exception {
ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
channel.connect();
channel.cd(downloadPath);
SftpATTRS attrs = channel.lstat(fileName);
if (attrs == null) {
channel.disconnect();
return false;
}
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
OutputStream outputStream = response.getOutputStream();
channel.get(fileName, outputStream);
outputStream.flush();
outputStream.close();
channel.disconnect();
return true;
}
}
```
然后在Spring Boot项目中创建一个FileController类,用于处理文件上传和下载请求:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("/file")
public class FileController {
@Autowired
private JdbcTemplate jdbcTemplate;
@PostMapping("/upload")
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file, @RequestParam("csmc") String csmc) {
try {
// 从数据库中获取SFTP连接配置信息
String sql = "SELECT * FROM sftp_config WHERE csmc = ?";
Map<String, Object> map = jdbcTemplate.queryForMap(sql, csmc);
String host = (String) map.get("host");
int port = (int) map.get("port");
String username = (String) map.get("username");
String password = (String) map.get("password");
String uploadPath = (String) map.get("upload_path");
String fileName = file.getOriginalFilename();
// 使用SFTP上传文件
SFTPUtil sftpUtil = new SFTPUtil(host, port, username, password, uploadPath, null);
sftpUtil.connect();
sftpUtil.upload(file, fileName);
return "上传成功";
} catch (Exception e) {
e.printStackTrace();
return "上传失败";
}
}
@PostMapping("/download")
public void download(@RequestParam("fileName") String fileName, @RequestParam("csmc") String csmc, HttpServletResponse response) throws Exception {
// 从数据库中获取SFTP连接配置信息
String sql = "SELECT * FROM sftp_config WHERE csmc = ?";
Map<String, Object> map = jdbcTemplate.queryForMap(sql, csmc);
String host = (String) map.get("host");
int port = (int) map.get("port");
String username = (String) map.get("username");
String password = (String) map.get("password");
String downloadPath = (String) map.get("download_path");
// 使用SFTP下载文件
SFTPUtil sftpUtil = new SFTPUtil(host, port, username, password, null, downloadPath);
sftpUtil.connect();
boolean result = sftpUtil.download(response, fileName);
if (!result) {
response.getWriter().write("文件不存在");
}
}
@GetMapping("/csmcList")
@ResponseBody
public List<String> getCsmcList() {
// 从数据库中获取所有的csmc字段
String sql = "SELECT DISTINCT csmc FROM sftp_config";
List<String> csmcList = jdbcTemplate.queryForList(sql, String.class);
return csmcList;
}
}
```
最后,在HTML页面中加入下面的代码,即可实现文件上传和下载:
```html
<h1>上传/下载文件</h1>
<form method="post" action="/file/upload" enctype="multipart/form-data">
<input type="file" name="file" id="fileInput"/>
<select name="csmc" id="csmcSelect"></select>
<input type="submit" value="上传"/>
</form>
<hr>
<form method="post" action="/file/download">
<input type="text" name="fileName" placeholder="请输入文件名"/>
<select name="csmc" id="csmcSelect"></select>
<input type="submit" value="下载" id="downloadBtn"/>
</form>
<script>
// 获取csmc列表
$.get("/file/csmcList", function (data) {
var csmcSelect = $("#csmcSelect");
for (var i = 0; i < data.length; i++) {
var option = $("<option>").val(data[i]).text(data[i]);
csmcSelect.append(option);
}
});
</script>
```
阅读全文