1.Maven依賴
2.ExcelUtil工具類代碼
3.Test測試
4.遇到的問題
公司要寫導出Excel的功能,就寫了一下,順便記錄記錄,代碼從這裏copy來的,自己改了一下。源碼應該是3.9的poi版本,裏面挺多類已經不推薦使用了,我用的poi是3.17。
1.Maven依賴
<!-- 數據導出到xlsx -->
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>2.6.0</version>
</dependency>
<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>
2.ExcelUtil工具類代碼
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import static org.apache.poi.ss.usermodel.CellType.NUMERIC;
public class ExcelUtil {
/**
* 導出excel
*
* @param title 導出表的標題
* @param rowsName 導出表的列名
* @param dataList 需要導出的數據
* @param fileName 生成excel文件的文件名
* @param response
*/
public void exportExcel(String title, String[] rowsName, List<String[]> dataList, String fileName, HttpServletResponse response) throws Exception {
OutputStream output = response.getOutputStream();
response.reset();
response.setHeader("Content-disposition",
"attachment; filename=" + fileName);
response.setContentType("application/msexcel");
this.export(title, rowsName, dataList, fileName, output);
this.close(output);
}
/**
* 數據導出
* @param title
* @param rowName
* @param dataList
* @param fileName
* @param out
* @throws Exception
*/
private void export(String title, String[] rowName, List<String[]> dataList, String fileName, OutputStream out) throws Exception {
//查看poi使用的是什麼版本的jar包
//System.out.println("!!!!!!!!!"+ XSSFCellStyle.class.getProtectionDomain().getCodeSource().getLocation());
try {
// 創建工作簿對象
XSSFWorkbook workbook = new XSSFWorkbook();
// 創建工作表
XSSFSheet sheet = workbook.createSheet(title);
// 產生表格標題行
XSSFRow rowm = sheet.createRow(0);
//創建表格標題列
XSSFCell cellTiltle = rowm.createCell(0);
// sheet樣式定義; getColumnTopStyle(); getStyle()均爲自定義方法 --在下面,可擴展
// 獲取列頭樣式對象
XSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);
// 獲取單元格樣式對象
XSSFCellStyle style = this.getStyle(workbook);
//合併表格標題行,合併列數爲列名的長度,第一個0爲起始行號,第二個1爲終止行號,第三個0爲起始列好,第四個參數爲終止列號
sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length - 1)));
//設置標題行樣式
cellTiltle.setCellStyle(columnTopStyle);
//設置標題行值
cellTiltle.setCellValue(title);
// 定義所需列數
int columnNum = rowName.length;
// 在索引2的位置創建行(最頂端的行開始的第二行)
XSSFRow rowRowName = sheet.createRow(2);
// 將列頭設置到sheet的單元格中
for (int n = 0; n < columnNum; n++) {
// 創建列頭對應個數的單元格
XSSFCell cellRowName = rowRowName.createCell(n);
// 設置列頭單元格的數據類型
cellRowName.setCellType(CellType.STRING);
XSSFRichTextString text = new XSSFRichTextString(rowName[n]);
// 設置列頭單元格的值
cellRowName.setCellValue(text);
// 設置列頭單元格樣式
cellRowName.setCellStyle(columnTopStyle);
}
// 將查詢出的數據設置到sheet對應的單元格中
for (int i = 0; i < dataList.size(); i++) {
// 遍歷每個對象
Object[] obj = dataList.get(i);
// 創建所需的行數
XSSFRow row = sheet.createRow(i + 3);
for (int j = 0; j < obj.length; j++) {
// 設置單元格的數據類型
XSSFCell cell = null;
if (j == 0) {
cell = row.createCell(j, NUMERIC);
cell.setCellValue(i + 1);
} else {
cell = row.createCell(j, CellType.STRING);
if (!"".equals(obj[j]) && obj[j] != null) {
// 設置單元格的值
cell.setCellValue(obj[j].toString());
}
}
cell.setCellStyle(style); // 設置單元格樣式
}
}
// 讓列寬隨着導出的列長自動適應
for (int colNum = 0; colNum < columnNum; colNum++) {
int columnWidth = sheet.getColumnWidth(colNum) / 256;
for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
XSSFRow currentRow;
// 當前行未被使用過
if (sheet.getRow(rowNum) == null) {
currentRow = sheet.createRow(rowNum);
} else {
currentRow = sheet.getRow(rowNum);
}
if (currentRow.getCell(colNum) != null) {
XSSFCell currentCell = currentRow.getCell(colNum);
if (currentCell.getCellType() == 1) {
int length = currentCell.getStringCellValue()
.getBytes().length;
if (columnWidth < length) {
columnWidth = length;
}
}
}
}
if (colNum == 0) {
sheet.setColumnWidth(colNum, (columnWidth - 2) * 256);
} else {
sheet.setColumnWidth(colNum, (columnWidth + 8) * 256);
}
}
workbook.write(out);
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* 列頭單元格樣式
*/
private XSSFCellStyle getColumnTopStyle(XSSFWorkbook workbook) {
// 設置字體
XSSFFont font = workbook.createFont();
// 設置字體大小
font.setFontHeightInPoints((short) 16);
// 字體加粗
font.setBold(true);
// 設置字體名字
font.setFontName("Courier New");
// 設置樣式;
XSSFCellStyle style = workbook.createCellStyle();
// 設置底邊框;
style.setBorderBottom(BorderStyle.THIN);
// 設置底邊框顏色;
style.setBottomBorderColor(new XSSFColor(Color.BLACK));
// 設置左邊框;
style.setBorderLeft(BorderStyle.THIN);
// 設置左邊框顏色;
style.setLeftBorderColor(new XSSFColor(Color.BLACK));
// 設置右邊框;
style.setBorderRight(BorderStyle.THIN);
// 設置右邊框顏色;
style.setRightBorderColor(new XSSFColor(Color.BLACK));
// 設置頂邊框;
style.setBorderTop(BorderStyle.THIN);
// 設置頂邊框顏色;
style.setTopBorderColor(new XSSFColor(Color.BLACK));
// 在樣式用應用設置的字體;
style.setFont(font);
// 設置自動換行;
style.setWrapText(false);
// 設置水平對齊的樣式爲居中對齊;
style.setAlignment(HorizontalAlignment.CENTER);
// 設置垂直對齊的樣式爲居中對齊;
style.setVerticalAlignment(VerticalAlignment.CENTER);
return style;
}
/*
* 列數據信息單元格樣式
*/
private XSSFCellStyle getStyle(XSSFWorkbook workbook) {
// 設置字體
XSSFFont font = workbook.createFont();
// 設置字體大小
// font.setFontHeightInPoints((short)10);
// 字體加粗
// font.setBold(true);
// 設置字體名字
font.setFontName("Courier New");
// 設置樣式;
XSSFCellStyle style = workbook.createCellStyle();
// 設置底邊框;
style.setBorderBottom(BorderStyle.THIN);
// 設置底邊框顏色;
//style.setBottomBorderColor(new XSSFColor(Color.RED));
// 設置左邊框;
style.setBorderLeft(BorderStyle.THIN);
// 設置左邊框顏色;
style.setLeftBorderColor(new XSSFColor(Color.BLACK));
// 設置右邊框;
style.setBorderRight(BorderStyle.THIN);
// 設置右邊框顏色;
style.setRightBorderColor(new XSSFColor(Color.BLACK));
// 設置頂邊框;
style.setBorderTop(BorderStyle.THIN);
// 設置頂邊框顏色;
style.setTopBorderColor(new XSSFColor(Color.BLACK));
// 在樣式用應用設置的字體;
style.setFont(font);
// 設置自動換行;
style.setWrapText(false);
// 設置水平對齊的樣式爲居中對齊;
style.setAlignment(HorizontalAlignment.CENTER);
// 設置垂直對齊的樣式爲居中對齊;
style.setVerticalAlignment(VerticalAlignment.CENTER);
return style;
}
/**
* 關閉輸出流
*
* @param os
*/
private void close(OutputStream os) {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
3.Test測試
@GetMapping("/test")
public R test(HttpServletResponse response) {
ExcelUtil excelUtil = new ExcelUtil();
List<String[]> el = new ArrayList<>();
//需要導出的數據
List<ReportLogDataDto> reportList = reportService.getReportList();
if (reportList.isEmpty()) {
return R.failed("查詢到的報表條數爲0");
}
//遍歷取出數據,封裝成List<String[]>的形式
reportList.forEach(item -> {
int count = 0;
String[] col = new String[8];
//這行是給編號留出一個空位
col[count++] = "";
col[count++] = item.getCode();
col[count++] = item.getRoomName();
col[count++] = item.getStartTime();
col[count++] = item.getEndTime();
col[count++] = item.getIsFinished();
col[count++] = item.getFailureReason();
col[count++] = item.getTime();
el.add(col);
});
//這裏是列名
String[] name = {"編號", "設備編號", "房間名", "開始時間", "結束時間", "是否完成消毒", "失敗原因", "時間段"};
try {
excelUtil.exportExcel("消毒報表", name, el, "DisinfectionReport.xlsx", response);
System.out.println("excel finished");
} catch (Exception e) {
e.printStackTrace();
}
return R.ok();
}
我是用SwaggerUI看的,結果如下:
4.遇到的問題
1)jar包的升級導致CELL_TYPE_STRING、XSSFCell.CELL_TYPE_NUMERIC等無法使用
可以使用CellType.STRING、CellType.NUMERIC等等代替。圖片是CellType中的內容,可以看出,從3.15就可以使用新的參數了。新的版本都會有舊版本的替代方法,改改就好了。
同時,以下也可以進行替換
POI舊版本 | POI新版本 |
HSSFCellStyle.BORDER_THIN | BorderStyle.THIN |
HSSFColor.BLACK.index | new XSSFColor(Color.BLACK) |
HSSFCellStyle.ALIGN_CENTER | HorizontalAlignment.CENTER |
HSSFCellStyle.VERTICAL_CENTER | VerticalAlignment.CENTER |
2)Caused by: java.lang.NoSuchMethodError: org.apache.poi.hssf.usermodel.XSSFCell.setEncoding(S)V
這可能是由於poi版本覆蓋,或者沒有正確的引用poi的jar包導致的,我最開始用的jar包,應該是poi3.9,但是下載依賴的時候,會自動把3.17的版本也下載下來,自動覆蓋了3.9的版本,導致雖然沒有報錯,但是 HSSFCellStyle 和部分class一直提示NoSuchMethodError。
ExcelUtil代碼中有一行sysout語句如下,這行會把使用的class所在的路徑打印出來,通過打印出的信息,可以看看自己用的jar包到底是哪裏的,版本號是多少,這個其實也算是版本升級導致的問題了。建議使用新版本的poi,別用老的了。
System.out.println("!!!!!!!!!"+ XSSFCellStyle.class.getProtectionDomain().getCodeSource().getLocation());
引用: