提到Excel導出功能,可能很多人都使用springmvc框架做過,筆者今天要給大家分享的是基於springBoot開發Excel複雜模板導出功能(所謂複雜模板指在模板裏的特定表頭裏有不同的單元格合併以及背景色,字體顏色的填充,文本內容的對齊方式等)。
實現思路:
首先在springBoot(或者SpringCloud)項目的默認templates目錄放入提前定義好的Excel模板,然後在具體的導出接口業務代碼裏通過IO流加載到這個Excel模板文件,讀取指定的工作薄(也就是excel左下角的Sheet),接着給模板裏的指定表頭填充表頭數據,接着讀取數據庫的相關數據用數據傳輸模型(DTO)封裝數據,最後循壞填充excel的數據行(逐行逐列的填充數據),最後把填充完數據的Excel文件流輸出(下載),即完成了數據庫數據按照指定Excel模板導出Excel的完整過程。廢話不多說,下面直接上代碼。
一、配置POI框架的依賴
本案例是maven項目,解析Excel採用市面主流的POI框架,在pom.xml文件添加POI框架的依賴
<!--讀取excel文件,配置POI框架的依賴-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
二、放入excel模板文件
目錄結構如下所示:
二、導出excel具體實現
@RestController
@RequestMapping("/excel")
public class ExcelExportController {
@RequestMapping(value="/excelExport")
public ResponseEntity<Resource> excel2007Export(HttpServletResponse response,HttpServletRequest request) {
try {
ClassPathResource cpr = new ClassPathResource("/templates/"+"student.xlsx");
InputStream is = cpr.getInputStream();
Workbook workbook = new XSSFWorkbook(is);
org.apache.poi.ss.usermodel.Sheet sheet0 =workbook.getSheetAt(0);
Row row = sheet0.getRow(2);
Cell cell0 = row.getCell(0);
Cell cell1 = row.getCell(1);
Cell cell2 = row.getCell(2);
cell0.setCellValue("guo");
cell1.setCellValue("bin");
cell2.setCellValue("hui");
System.out.println(cell0);
//這裏作爲演示,造幾個演示數據,模擬數據庫裏查數據
List <Student> list = new ArrayList<Student>();
Student st1 = new Student();
Student st2 = new Student();
st1.setName("張三");
st1.setScore("87");
st1.setClass("一班");
st2.setName("張四");
st2.setScore("57");
st2.setClass("二班");
list.add(st1);
list.add(st2);
for(int i = 0;i<list.size();i++){
Row row = sheet0.getRow(i+3);//從第三行開始填充數據
row.setCellValue(list.get(i).getName());
row.setCellValue(list.get(i).getScore());
row.setCellValue(list.get(i).getClass());
}
String fileName = "moban.xlsx";
downLoadExcel(fileName, response, workbook);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new ResponseEntity<Resource>(HttpStatus.OK);
}
public static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
try {
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition",
"attachment;filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
workbook.write(response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
}
歡迎各位開發者朋友一起交流。筆者電話(微信):18629374628