package com.book.book.controller;
import com.book.book.pojo.Books;
import com.book.book.service.BooksService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
@RequestMapping("/demo")
@Controller
public class DemoController {
@Resource
BooksService booksService;
String sheetName = "ceshi";
String [] sd= {"标题","作者"};
String filePath = "D:\\temp\\";
@GetMapping("se")
public void se() {
String timeStamp = String.valueOf(System.currentTimeMillis()); // 获取当前时间戳
//查询出要导出的列表
List<Books> books = booksService.booksList1();
//导出的是个对象,现在new出这个对象
Workbook workBook = new XSSFWorkbook();
//设置表格名字
Sheet sheet = workBook.createSheet(sheetName);
//设置第一行 表头行
Row row = sheet.createRow(0);
//循环表头上面已经列出的数组
for (int i = 0; i < sd.length; i++) {
row.createCell(i).setCellValue(sd[i]);
}
//从第二行开始 循环插入数据列表
for (int i = 0; i < books.size(); i++) {
Row currentRow = sheet.createRow(i + 1); // 从第二行开始
currentRow.createCell(0).setCellValue(books.get(i).getBookTitle()); // 设置书标题
currentRow.createCell(1).setCellValue(books.get(i).getBookAuthor()); // 设置作者
}
//打开输出流操作
try (FileOutputStream fileOutputStream = new FileOutputStream(filePath+timeStamp+"ssd.xlsx")) {
workBook.write(fileOutputStream);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (workBook != null) {
try {
workBook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} }
}
springboot导出excel功能
于 2024-06-04 15:47:11 首次发布