Excel导出功能
1.引入poi依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
2.创建Excel导出工具类
public class ExcelUtils {
/**
* Excel表格导出
*
* @param response HttpServletResponse对象
* @param excelData Excel表格的数据,封装为List<List<String>>
* @param sheetName sheet的名字
* @param fileName 导出Excel的文件名
* @param columnWidth Excel表格的宽度
* @throws IOException 抛IO异常
*/
public static void exportExcel(HttpServletResponse response,
List<List<String>> excelData,
String sheetName,
String fileName,
int columnWidth) throws IOException {
//声明一个工作簿
HSSFWorkbook workbook = new HSSFWorkbook();
//生成一个表格,设置表格名称
HSSFSheet sheet = workbook.createSheet(sheetName);
//设置表格列宽度
sheet.setDefaultColumnWidth(columnWidth);
//写入List<List<String>>中的数据
int rowIndex = 0;
for (List<String> data : excelData) {
//创建一个row行,然后自增1
HSSFRow row = sheet.createRow(rowIndex++);
//遍历添加本行数据
for (int i = 0; i < data.size(); i++) {
//创建一个单元格
HSSFCell cell = row.createCell(i);
//创建一个内容对象
HSSFRichTextString text = new HSSFRichTextString(data.get(i));
//将内容对象的文字内容写入到单元格中
cell.setCellValue(text);
}
}
//准备将Excel的输出流通过response输出到页面下载
//八进制输出流
response.setContentType("application/octet-stream");
//设置导出Excel的名称
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
//刷新缓冲
response.flushBuffer();
//workbook将Excel写入到response的输出流中,供页面下载该Excel文件
workbook.write(response.getOutputStream());
//关闭workbook
workbook.close();
}
}
3.创建service
@Service
public class ExcelService {
public List<List<String>> excelTest() {
List<List<String>> excelData = new ArrayList<>();
//设置表头
List<String> head = new ArrayList<>();
head.add("列1");
head.add("列2");
head.add("列3");
excelData.add(head);
//设置数据
List<String> data1 = new ArrayList<>();
data1.add("A1");
data1.add("A2");
data1.add("A3");
excelData.add(data1);
List<String> data2 = new ArrayList<>();
data2.add("B1");
data2.add("B2");
data2.add("B3");
excelData.add(data2);
return excelData;
}
}
4.创建controller
@RestController
@RequestMapping("/demo/excel")
public class ExcelController {
@Autowired
private ExcelService excelService;
/**
* Excel表格导出接口
* http://localhost:8998/demo/excel/export
*
* @param response response对象
* @throws IOException 抛IO异常
*/
@GetMapping("/export")
public void excelDownload(HttpServletResponse response) throws IOException {
List<List<String>> excelData = excelService.excelTest();
String sheetName = "测试";
String fileName = "test.xls";
ExcelUtils.exportExcel(response, excelData, sheetName, fileName, 15);
}
}
5.启动项目,浏览器中访问 http://localhost:8998/demo/excel/export ,得到文件如下:
