SpringBoot前后端分离项目Excel导出数据的代码实现
时间: 2023-09-28 08:07:23 浏览: 124
SpringBootMybatis+poi+Thymeleaf实现excel文件数据导入到数据库以及从数据库将数据导出成excel.zip
4星 · 用户满意度95%
下面是SpringBoot前后端分离项目Excel导出数据的代码实现步骤:
1. 引入poi包
在pom.xml中添加以下依赖:
```
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
```
2. 编写Excel导出工具类
创建ExcelUtil.java文件,编写Excel导出工具类,具体代码如下:
```
public class ExcelUtil {
/**
* 导出excel
* @param response
* @param fileName 文件名
* @param headers 表头
* @param dataList 数据
*/
public static void exportExcel(HttpServletResponse response, String fileName, String[] headers, List<List<String>> dataList) {
// 创建工作簿
XSSFWorkbook workbook = new XSSFWorkbook();
// 创建表格
XSSFSheet sheet = workbook.createSheet();
// 设置列宽
for (int i = 0; i < headers.length; i++) {
sheet.setColumnWidth(i, 20 * 256);
}
// 创建表头行
XSSFRow row = sheet.createRow(0);
// 设置表头
for (int i = 0; i < headers.length; i++) {
XSSFCell cell = row.createCell(i);
cell.setCellValue(headers[i]);
}
// 添加数据
for (int i = 0; i < dataList.size(); i++) {
XSSFRow dataRow = sheet.createRow(i + 1);
List<String> rowData = dataList.get(i);
for (int j = 0; j < rowData.size(); j++) {
XSSFCell cell = dataRow.createCell(j);
cell.setCellValue(rowData.get(j));
}
}
// 设置响应头
response.setContentType("application/octet-stream");
try {
fileName = URLEncoder.encode(fileName, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
// 输出Excel文件
try {
workbook.write(response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
3. 调用Excel导出工具类
在Controller中调用Excel导出工具类,具体代码如下:
```
@Controller
public class ExcelController {
@RequestMapping("/export")
public void export(HttpServletResponse response) {
// 文件名
String fileName = "测试导出.xlsx";
// 表头
String[] headers = {"姓名", "年龄", "性别"};
// 数据
List<List<String>> dataList = new ArrayList<>();
dataList.add(Arrays.asList("张三", "23", "男"));
dataList.add(Arrays.asList("李四", "25", "女"));
dataList.add(Arrays.asList("王五", "28", "男"));
// 调用Excel导出工具类
ExcelUtil.exportExcel(response, fileName, headers, dataList);
}
}
```
4. 配置跨域访问
由于是前后端分离项目,需要配置跨域访问,具体代码如下:
```
@Configuration
public class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
}
```
以上就是SpringBoot前后端分离项目Excel导出数据的代码实现步骤。
阅读全文