Springboot使用POI進(jìn)行excel文件的導(dǎo)出與下載方式
更新時間:2024年08月15日 14:16:38 作者:專注寫bug
這篇文章主要介紹了Springboot使用POI進(jìn)行excel文件的導(dǎo)出與下載方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
前言
之前寫了一篇使用poi進(jìn)行docx模板導(dǎo)出的文章,最近呢也使用POI實(shí)現(xiàn)excel文件的導(dǎo)出與下載,特此記錄。
Springboot —— 根據(jù)docx填充生成word文件,并導(dǎo)出pdf
環(huán)境
- springboot 2.1.4
- poi-tl 1.5.0
依賴引入
再新建的springboot工程項(xiàng)目中,引入下列的依賴即可
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.5.0</version>
</dependency>導(dǎo)出excel工具類編寫
編寫工具類,主要用于表頭的創(chuàng)建、單元格樣式的定義、以及數(shù)據(jù)格式的轉(zhuǎn)換等。
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Optional;
@Slf4j
public final class ExcelExport {
/**
* description: 依據(jù)excel模板,導(dǎo)出數(shù)據(jù)excel
* @param sheetName sheet 頁名稱
* @param headers 數(shù)據(jù)header部分
* @param dataList table 數(shù)據(jù)集合
* @param destFile excel模板文件路徑
*/
public static void export(String sheetName, String[] headers, List<List<Object>> dataList, File destFile) throws Exception {
SXSSFWorkbook workbook = new SXSSFWorkbook();
createSheet(sheetName, headers, dataList, workbook);
workbook.write(new FileOutputStream(destFile));
}
/**
* 根據(jù)header與data的集合,動態(tài)地創(chuàng)建并生成excel數(shù)據(jù)流進(jìn)行下載操作
* description: 導(dǎo)出excel --- 支持web
* @param sheetName sheet表名字
* @param headers 表頭
* @param dataList 表數(shù)據(jù)
* @param fileName 導(dǎo)出文件名
* @param response
*/
public static void export(String sheetName , String[] headers , List<List<Object>> dataList ,String fileName
, HttpServletResponse response) throws Exception {
SXSSFWorkbook workbook = new SXSSFWorkbook();
createSheet(sheetName, headers, dataList, workbook);
response.reset();
//response.setContentType("application/vnd.ms-excel; charset=utf-8");
response.setContentType("application/octet-stream; charset=utf-8");
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
workbook.write(response.getOutputStream());
// 刪除臨時文件
workbook.dispose();
}
/**
* description: 創(chuàng)建sheet表格
* @param sheetName 表sheet 名字
* @param headers 表頭
* @param dataList 表數(shù)據(jù)
* @param wb
*/
public static void createSheet(String sheetName , String[] headers , List<List<Object>> dataList , SXSSFWorkbook wb) {
SXSSFSheet sheet = wb.createSheet(sheetName);
// 設(shè)置表頭和單元格格式
CellStyle headStyle = setHeaderStyle(wb);
CellStyle bodyStyle = setBodyStyle(wb);
// 創(chuàng)建表頭和單元格數(shù)據(jù)
createHeader(headers, sheet, headStyle);
createBody(dataList, sheet, bodyStyle,wb);
}
/**
* description: 創(chuàng)建表頭
* @param headers
* @param sheet
* @param headStyle
*/
private static void createHeader(String[] headers, SXSSFSheet sheet, CellStyle headStyle) {
SXSSFRow row = sheet.createRow(0);
row.setHeightInPoints(16F);
for (int i = 0; i < headers.length; i++) {
// 創(chuàng)建單元格
SXSSFCell cell = row.createCell(i);
cell.setCellStyle(headStyle);
XSSFRichTextString text = new XSSFRichTextString(headers[i]);
cell.setCellValue(text);
sheet.trackAllColumnsForAutoSizing();
sheet.autoSizeColumn(i);
}
}
/**
* description: 表格中填充數(shù)據(jù)
* @param dataList
* @param sheet
* @param bodyStyle
* @param wb 主要是更改文本格式
*/
private static void createBody(List<List<Object>> dataList, SXSSFSheet sheet, CellStyle bodyStyle,SXSSFWorkbook wb) {
if (dataList == null) {
return;
}
for (int i = 0; i < dataList.size(); i++) {
// 從第二行開始,第一行做表頭
SXSSFRow row = sheet.createRow(i+1);
List<Object> rowList = dataList.get(i);
if (rowList == null) {
continue;
}
for (int j = 0; j < rowList.size(); j++) {
SXSSFCell cell = row.createCell(j);
Object data = rowList.get(j);
// 如果數(shù)據(jù)是 Double 類型,則需要保證金額數(shù)轉(zhuǎn)換,否則導(dǎo)出數(shù)據(jù)顯示為科學(xué)計(jì)數(shù)法 如: 8E7
if(data instanceof Double){
DataFormat format= wb.createDataFormat();
bodyStyle.setDataFormat(format.getFormat("#,##0.00")); // 千位符
// bodyStyle.setDataFormat(format.getFormat("#0.00")); // 小數(shù)
// bodyStyle.setDataFormat(format.getFormat("0.00%")); // 百分比 數(shù)據(jù)必須是小數(shù),如:0.59 -> 59%
cell.setCellStyle(bodyStyle);
cell.setCellValue(Double.parseDouble(String.valueOf(data)));
}else{
String textStr = Optional.ofNullable(rowList.get(j)).orElse("").toString();
XSSFRichTextString text = new XSSFRichTextString(textStr);
cell.setCellValue(text);
}
sheet.trackAllColumnsForAutoSizing();
//設(shè)置內(nèi)容列為列的最大值
sheet.autoSizeColumn(j);
}
}
}
/**
* description: 設(shè)置單元格內(nèi)容樣式
* @param wb
* @return HSSFCellStyle
*/
private static CellStyle setBodyStyle(SXSSFWorkbook wb) {
// 設(shè)置表格單元格格式
CellStyle style = wb.createCellStyle();
style.setFillForegroundColor(HSSFColor.WHITE.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
// 設(shè)置字體格式
Font font = wb.createFont();
font.setFontName("宋體");
font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
style.setFont(font);
return style;
}
/**
* description: 設(shè)置表頭樣式
* @param wb
* @return
* @return HSSFCellStyle
*/
private static CellStyle setHeaderStyle(SXSSFWorkbook wb) {
// 設(shè)置表格單元格格式
CellStyle style = wb.createCellStyle();
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
style.setBorderRight(BorderStyle.THIN);
style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setBorderLeft(BorderStyle.THIN);
style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setBorderTop(BorderStyle.THIN);
style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setBorderBottom(BorderStyle.THIN);
style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
// style.setFillBackgroundColor(IndexedColors.LIGHT_YELLOW.getIndex());
style.setFillForegroundColor(IndexedColors.LIGHT_YELLOW.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
// 設(shè)置字體格式
Font font = wb.createFont();
font.setFontName("宋體");
font.setFontHeightInPoints((short) 10);
style.setFont(font);
return style;
}
}測試案例
@GetMapping("/test-xls")
public void contractIntrQryPayxls(HttpServletResponse response) throws Exception {
String[] headers = new String[]{"編號","名稱","金額"};
List<List<Object>> dataLists = new ArrayList<>();
for (int i = 0; i < 10; i++) {
List<Object> data = new ArrayList<>();
data.add("xj_"+i);
data.add("xiangjiao "+i);
data.add(10000.00*i);
dataLists.add(data);
}
ExcelExport.export("sheetName",headers,dataLists,"xiangjiao測試.xls",response);
}
總結(jié)
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
JavaWeb學(xué)習(xí)過程之MVC查詢模式詳解
這篇文章主要介紹了JavaWeb學(xué)習(xí)過程之MVC查詢模式詳解的相關(guān)資料,非常不錯,具有參考借鑒價(jià)值,需要的朋友可以參考下2016-09-09

