一、Apache POI簡介
Apache POI是Apache軟件基金會的開放源碼函式庫,POI提供API給Java程序對Microsoft Office格式檔案讀和寫的功能。
HSSF 是Horrible SpreadSheet Format的縮寫,通過HSSF,你可以用純Java代碼來讀取、寫入、修改Excel文件。
HSSF 爲讀取操作提供了兩類API:usermodel和eventusermodel,即“用戶模型”和“事件-用戶模型”
二、POI結構說明
- HSSF提供讀寫Microsoft Excel XLS格式檔案的功能。
- XSSF提供讀寫Microsoft Excel OOXML XLSX格式檔案的功能。
- HWPF提供讀寫Microsoft Word DOC格式檔案的功能。
- HSLF提供讀寫Microsoft PowerPoint格式檔案的功能。
- HDGF提供讀Microsoft Visio格式檔案的功能。
- HPBF提供讀Microsoft Publisher格式檔案的功能。
- HSMF提供讀Microsoft Outlook格式檔案的功能
三、常用組件
類名 | 說明 |
---|---|
HSSFWorkbook | Excel的文檔對象 |
HSSFSheet | Excel的表單 |
HSSFRow | Excel的行 |
HSSFCell | Excel的格子單元 |
HSSFFont | Excel字體 |
HSSFDataFormat | 格子單元的日期格式 |
HSSFHeader | Excel文檔Sheet的頁眉 |
HSSFFooter | Excel文檔Sheet的頁腳 |
HSSFCellStyle | 格子單元樣式 |
HSSFDateUtil | 日期 |
HSSFPrintSetup | 打印 |
HSSFErrorConstants | 錯誤信息表 |
引入pom文件
<!-- Excel 導入導出-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.8</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.8</version>
</dependency>
xls 格式的工具類
僅供參考
package com.user.base.util.Excel.POI;
import com.user.base.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
/**
* @author :mmzs
* @date :Created in 2020/3/26 16:36
* @description:poi導入導出Excel,Excel有.xls,2003最多隻允許存儲65536條數據,HSSFWorkbook
* @modified By:xphy
* @version: 1$
*/
@Slf4j
public class ExcelXlsPoiUtils {
/***
* @description: poi導出excel
* @param response 響應
* @param path 生成的文件路徑
* @param fileName 文件名
* @param sheetName 工作蒲名
* @param headers 表格頭部
* @param data 表格數據
* @return: void
* @author: Andy
* @time: 2020/3/27 14:40
*/
public static void Export(HttpServletResponse response, String path, String fileName,String sheetName,String[] headers, List<String[]> data) throws IOException {
//設置文件名稱
String fileNameTime = getFileName(path, fileName);
//實例化HSSFWorkbook
HSSFWorkbook workbook = new HSSFWorkbook();
//創建一個Excel表單,參數爲sheet的名字
HSSFSheet sheet = workbook.createSheet("sheet");
//設置表頭
setTitle(workbook, sheet, headers);
//設置單元格並賦值
setData(sheet, data);
//設置瀏覽器下載
setBrowser(response, workbook, fileNameTime+".xls");
log.info("導出解析成功!");
}
/**
* 方法名:setTitle
* 功能:設置表頭
* 描述:
* 創建人:typ
* 創建時間:2018/10/19 10:20
* 修改人:
* 修改描述:
* 修改時間:
*/
private static void setTitle(HSSFWorkbook workbook, HSSFSheet sheet, String[] str) {
try {
//創建表頭
HSSFRow row = sheet.createRow(0);
//設置列寬,setColumnWidth的第二個參數要乘以256,這個參數的單位是1/256個字符寬度
for (int i = 0; i <= str.length; i++) {
sheet.setColumnWidth(i, 15 * 256);
}
//設置爲居中加粗,格式化時間格式
HSSFCellStyle style = workbook.createCellStyle();
// 設置字體
Font font = workbook.createFont();
// 設置字體大小
font.setFontHeightInPoints((short) 11);
// 字體加粗
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 設置字體名字
font.setFontName("Courier New");
style.setWrapText(true);// 設置自動換行
style.setFont(font);
style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
//創建表頭名稱
HSSFCell cell;
for (int j = 0; j < str.length; j++) {
cell = row.createCell(j);
cell.setCellValue(str[j]);
cell.setCellStyle(style);
}
} catch (Exception e) {
log.info("導出時設置表頭失敗!");
e.printStackTrace();
}
}
/**
* 方法名:setData
* 功能:表格賦值
* 描述:
* 創建人:typ
* 創建時間:2018/10/19 16:11
* 修改人:
* 修改描述:
* 修改時間:
*/
private static void setData(HSSFSheet sheet, List<String[]> data) {
try {
int rowNum = 1;
for (int i = 0; i < data.size(); i++) {
HSSFRow row = sheet.createRow(rowNum);
for (int j = 0; j < data.get(i).length; j++) {
row.createCell(j).setCellValue(data.get(i)[j]);
}
rowNum++;
}
log.info("表格賦值成功!");
} catch (Exception e) {
log.info("表格賦值失敗!");
e.printStackTrace();
}
}
/***
* @description: 輸出到瀏覽器
* @param response 相應
* @param workbook 文件內容
* @param fileName 文件名字
* @return: void
* @author: Andy
* @time: 2020/3/26 17:31
*/
private static void setBrowser(HttpServletResponse response, HSSFWorkbook workbook, String fileName) {
try {
response.setContentType("application/ms-excel;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename="
.concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
response.flushBuffer();
OutputStream out = response.getOutputStream();
workbook.write(out);// 將數據寫出去
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 生成excel文件
* @param path 生成excel路徑
* @param fileName 文件名
*/
private static String getFileName (String path,String fileName){
String resultName = fileName;
long timeNew = System.currentTimeMillis()/ 1000;
File file = new File(path);
if (file.exists()) {
//如果文件存在
resultName = resultName + timeNew;
//file.delete();
}
return resultName;
}
/***
* @description: excel導入
* @param filePath 文件路徑
* @return: java.util.List<java.lang.Object[]>
* @author: Andy
* @time: 2020/3/27 15:06
*/
public static List<Object[]> importExcel(String filePath) {
log.info("導入解析開始,fileName:{}",filePath);
if(StringUtil.isEmpty(filePath)){
//導入文件不存在
return null;
}
try {
List<Object[]> list = new ArrayList<>();
//獲得輸入流
InputStream inputStream = new FileInputStream(filePath);
//獲取workbook對象
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0);
//獲取sheet的行數
int rows = sheet.getPhysicalNumberOfRows();
for (int i = 0; i < rows; i++) {
//過濾表頭行
if (i == 0) {
continue;
}
//獲取當前行的數據
Row row = sheet.getRow(i);
Object[] objects = new Object[row.getPhysicalNumberOfCells()];
int index = 0;
for (Cell cell : row) {
if (cell.getCellType()==0) {
objects[index] = (int) cell.getNumericCellValue();
}
if (cell.getCellType() == 1) {
objects[index] = cell.getStringCellValue();
}
if (cell.getCellType()== 4) {
objects[index] = cell.getBooleanCellValue();
}
if (cell.getCellType()==5) {
objects[index] = cell.getErrorCellValue();
}
index++;
}
list.add(objects);
}
inputStream.close();//是否需要關閉
log.info("導入文件解析成功!");
return list;
}catch (Exception e){
log.info("導入文件解析失敗!");
e.printStackTrace();
}
return null;
}
//測試導入
public static void main(String[] args) {
try {
String fileName = "D:/export/文件名.xls";
List<Object[]> list = importExcel(fileName);
// for (int i = 0; i < list.size(); i++) {
// User user = new User();
// user.setId((Integer) list.get(i)[0]);
// user.setUsername((String) list.get(i)[1]);
// user.setPassword((String) list.get(i)[2]);
// user.setEnable((Integer) list.get(i)[3]);
// System.out.println(user.toString());
// }
} catch (Exception e) {
e.printStackTrace();
}
}
}
設置單元格的樣式
/*
* 列頭單元格樣式
*/
public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {
// 設置字體
HSSFFont font = workbook.createFont();
// 設置字體大小
font.setFontHeightInPoints((short) 11);
// 字體加粗
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 設置字體名字
font.setFontName("Courier New");
// 設置樣式
HSSFCellStyle style = workbook.createCellStyle();
// 設置低邊框
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
// 設置低邊框顏色
style.setBottomBorderColor(HSSFColor.BLACK.index);
// 設置右邊框
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
// 設置頂邊框
style.setTopBorderColor(HSSFColor.BLACK.index);
// 設置頂邊框顏色
style.setTopBorderColor(HSSFColor.BLACK.index);
// 在樣式中應用設置的字體
style.setFont(font);
// 設置自動換行
style.setWrapText(false);
// 設置水平對齊的樣式爲居中對齊;
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
return style;
}
public HSSFCellStyle getStyle(HSSFWorkbook workbook) {
// 設置字體
HSSFFont font = workbook.createFont();
// 設置字體大小
font.setFontHeightInPoints((short) 10);
// 字體加粗
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 設置字體名字
font.setFontName("Courier New");
// 設置樣式;
HSSFCellStyle style = workbook.createCellStyle();
// 設置底邊框;
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
// 設置底邊框顏色;
style.setBottomBorderColor(HSSFColor.BLACK.index);
// 設置左邊框;
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
// 設置左邊框顏色;
style.setLeftBorderColor(HSSFColor.BLACK.index);
// 設置右邊框;
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
// 設置右邊框顏色;
style.setRightBorderColor(HSSFColor.BLACK.index);
// 設置頂邊框;
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
// 設置頂邊框顏色;
style.setTopBorderColor(HSSFColor.BLACK.index);
// 在樣式用應用設置的字體;
style.setFont(font);
// 設置自動換行;
style.setWrapText(false);
// 設置水平對齊的樣式爲居中對齊;
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 設置垂直對齊的樣式爲居中對齊;
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
return style;
}