Apache POI 簡介是用Java編寫的免費開源的跨平臺的 Java API旷余,Apache POI提供API給Java程式對Microsoft Office(Excel猫十、WORD觅闽、PowerPoint、Visio等)格式檔案讀和寫的功能薯嗤。POI為“Poor Obfuscation Implementation”的首字母縮寫豪墅,意為“可憐的模糊實現(xiàn)”。
Apache POI常用的類
HSSF - 提供讀寫Microsoft Excel XLS格式檔案的功能铣口。
XSSF - 提供讀寫Microsoft Excel OOXML XLSX格式檔案的功能滤钱。
HWPF - 提供讀寫Microsoft Word DOC97格式檔案的功能。
XWPF - 提供讀寫Microsoft Word DOC2003格式檔案的功能脑题。
HSLF - 提供讀寫Microsoft PowerPoint格式檔案的功能件缸。
HDGF - 提供讀Microsoft Visio格式檔案的功能。
HPBF - 提供讀Microsoft Publisher格式檔案的功能叔遂。
HSMF - 提供讀Microsoft Outlook格式檔案的功能他炊。
在開發(fā)中我們經(jīng)常使用HSSF用來操作Excel處理表格數(shù)據(jù),對于其它的不經(jīng)常使用已艰。
HSSF 是Horrible SpreadSheet Format的縮寫痊末,通過HSSF,你可以用純Java代碼來讀取旗芬、寫入舌胶、修改Excel文件捆蜀。HSSF 為讀取操作提供了兩類API:usermodel和eventusermodel疮丛,即“用戶模型”和“事件-用戶模型”。
常用的類和方法
HSSFWorkbook :工作簿辆它,代表一個excel的整個文檔
HSSFWorkbook(); // 創(chuàng)建一個新的工作簿
HSSFWorkbook(InputStream inputStream); // 創(chuàng)建一個關(guān)聯(lián)輸入流的工作簿誊薄,可以將一個excel文件封裝成工作簿
HSSFSheet createSheet(String sheetname); 創(chuàng)建一個新的Sheet
HSSFSheet getSheet(String sheetName); 通過名稱獲取Sheet
HSSFSheet getSheetAt(int index); // 通過索引獲取Sheet,索引從0開始
HSSFCellStyle createCellStyle()锰茉; 創(chuàng)建單元格樣式
int getNumberOfSheets(); 獲取sheet的個數(shù)
setActiveSheet(int index); 設(shè)置默認選中的工作表
write();
write(File newFile);
write(OutputStream stream);
HSSFSheet:工作表
HSSFRow createRow(int rownum); 創(chuàng)建新行呢蔫,需要指定行號,行號從0開始
HSSFRow getRow(int index); 根據(jù)索引獲取指定的行
int addMergedRegion(CellRangeAddress region); 合并單元格
CellRangeAddress(int firstRow, int lastRow, int firstCol, int lastCol); 單元格范圍, 用于合并單元格,需要指定要合并的首行片吊、最后一行绽昏、首列、最后一列俏脊。
autoSizeColumn(int column); 自動調(diào)整列的寬度來適應(yīng)內(nèi)容
getLastRowNum(); 獲取最后的行的索引全谤,沒有行或者只有一行的時候返回0
setColumnWidth(int columnIndex, int width); 設(shè)置某一列的寬度,width=字符個數(shù) * 256爷贫,例如20個字符的寬度就是20 * 256
HSSFRow :行
HSSFCell createCell(int column); 創(chuàng)建新的單元格
HSSFCell setCell(shot index);
HSSFCell getCell(shot index);
setRowStyle(HSSFCellStyle style); 設(shè)置行樣式
short getLastCellNum(); 獲取最后的單元格號认然,如果單元格有第一個開始算,lastCellNum就是列的個數(shù)
setHeightInPoints(float height); 設(shè)置行的高度
HSSFCell:單元格
setCellValue(String value); 設(shè)置單元格的值
setCellType(); 設(shè)置單元格類型漫萄,如 字符串卷员、數(shù)字、布爾等
setCellStyle(); 設(shè)置單元格樣式
String getStringCellValue(); 獲取單元格中的字符串值
setCellStyle(HSSFCellStyle style); 設(shè)置單元格樣式腾务,例如字體毕骡、加粗、格式化
setCellFormula(String formula); 設(shè)置計算公式岩瘦,計算的結(jié)果作為單元格的值挺峡,也提供了異常常用的函數(shù),如求和"sum(A1,C1)"担钮、日期函數(shù)橱赠、字符串相關(guān)函數(shù)、CountIf和SumIf函數(shù)箫津、隨機數(shù)函數(shù)等
HSSFCellStyle :單元格樣式
setFont(Font font); 為單元格設(shè)置字體樣式
setAlignment(HorizontalAlignment align); // 設(shè)置水平對齊方式
setVerticalAlignment(VerticalAlignment align); // 設(shè)置垂直對齊方式
setFillPattern(FillPatternType fp);
setFillForegroundColor(short bg); 設(shè)置前景色
setFillBackgroundColor(short bg); 設(shè)置背景顏色
HSSFFont:字體狭姨,
setColor(short color); // 設(shè)置字體顏色
setBold(boolean bold); // 設(shè)置是否粗體
setItalic(boolean italic); 設(shè)置傾斜
setUnderline(byte underline); 設(shè)置下劃線
HSSFName:名稱
HSSFDataFormat :日期格式化
HSSFHeader : Sheet的頭部
HSSFFooter :Sheet的尾部
HSSFDateUtil :日期工具
HSSFPrintSetup :打印設(shè)置
HSSFErrorConstants:錯誤信息表
Excel中的工作簿、工作表苏遥、行饼拍、單元格中的關(guān)系:
一個Excel文件對應(yīng)于一個workbook(HSSFWorkbook),
一個workbook可以有多個sheet(HSSFSheet)組成田炭,
一個sheet是由多個row(HSSFRow)組成师抄,
一個row是由多個cell(HSSFCell)組成
使用案例
在桌面生成一個Excel文件
/**
* 在桌面生成一個Excel文件
*
* @throws IOException
*/
public static void createExcel() throws IOException {
// 獲取桌面路徑
FileSystemView fsv = FileSystemView.getFileSystemView();
String desktop = fsv.getHomeDirectory().getPath();
String filePath = desktop + "/template.xls";
File file = new File(filePath);
OutputStream out = new FileOutputStream(file);
// 創(chuàng)建工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
// 創(chuàng)建sheet
HSSFSheet sheet = workbook.createSheet("Sheet1");
// 創(chuàng)建行
HSSFRow row = sheet.createRow(0);
// 創(chuàng)建單元格
row.createCell(0).setCellValue("id");
row.createCell(1).setCellValue("訂單號");
row.createCell(2).setCellValue("下單時間");
row.createCell(3).setCellValue("個數(shù)");
row.createCell(4).setCellValue("單價");
row.createCell(5).setCellValue("訂單金額");
// 設(shè)置行高
row.setHeightInPoints(25);
HSSFRow row1 = sheet.createRow(1);
row1.setHeightInPoints(18);
row1.createCell(0).setCellValue("1");
row1.createCell(1).setCellValue("No00001");
// 日期格式化
HSSFCellStyle cellStyle2 = workbook.createCellStyle();
HSSFCreationHelper creationHelper = workbook.getCreationHelper();
cellStyle2.setDataFormat(creationHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));
// 設(shè)置列寬
sheet.setColumnWidth(2, 20 * 256);
HSSFCell cell2 = row1.createCell(2);
cell2.setCellStyle(cellStyle2);
cell2.setCellValue(new Date());
row1.createCell(3).setCellValue(2);
// 保留兩位小數(shù)
HSSFCellStyle cellStyle3 = workbook.createCellStyle();
cellStyle3.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));
HSSFCell cell4 = row1.createCell(4);
cell4.setCellStyle(cellStyle3);
cell4.setCellValue(29.5);
// 貨幣格式化
HSSFCellStyle cellStyle4 = workbook.createCellStyle();
HSSFFont font = workbook.createFont();
font.setFontName("華文行楷");
font.setFontHeightInPoints((short) 15);
font.setColor(HSSFColor.RED.index);
cellStyle4.setFont(font);
HSSFCell cell5 = row1.createCell(5);
cell5.setCellFormula("D2*E2");
cell5.setCellStyle(cellStyle4);
// 獲取計算公式的值
HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(workbook);
cell5 = e.evaluateInCell(cell5);
System.out.println(cell5.getNumericCellValue());
workbook.setActiveSheet(0);
workbook.write(out);
out.close();
}
讀取Excel,解析數(shù)據(jù)
/**
* 讀取Excel教硫,解析數(shù)據(jù)
*/
public static void readExcel() throws IOException {
// 獲取桌面路徑
FileSystemView fsv = FileSystemView.getFileSystemView();
String desktop = fsv.getHomeDirectory().getPath();
// 獲取文件路徑
String filePath = desktop + "/template.xls";
InputStream in = new FileInputStream(filePath);
BufferedInputStream bis = new BufferedInputStream(in);
POIFSFileSystem fileSystem = new POIFSFileSystem(bis);
// 獲取工作薄
HSSFWorkbook workbook = new HSSFWorkbook(fileSystem);
// 根據(jù)名字獲取工作表
HSSFSheet sheet = workbook.getSheet("Sheet1");
// 獲取最后一行的索引
int lastRowIndex = sheet.getLastRowNum();
System.out.println("lastRowIndex:" + lastRowIndex);
for (int i = 0; i <= lastRowIndex; i++) {
// 獲取每一行
HSSFRow row = sheet.getRow(i);
// 獲取最后一個單元格的索引
int lastCellIndex = row.getLastCellNum();
System.out.println("lastCellIndex:" + lastCellIndex);
for (int j = 0; j < lastCellIndex; j++) {
// 獲取每個單元格字符類型的值
String cellValue = row.getCell(j).getStringCellValue();
System.out.println(cellValue);
}
}
bis.close();
}
導(dǎo)出和導(dǎo)入
/**
* @author zlm
*/
@Controller
public class Demo03 {
@RequestMapping("index.do")
public String showIndex() {
return "index";
}
/**
* 導(dǎo)出Excel
*
* @param response 響應(yīng)對象
* @throws Exception
*/
@RequestMapping("/export.do")
public void exportExcel(HttpServletResponse response) throws Exception {
String[] tableHeaders = {"id", "姓名", "年齡"};
// 創(chuàng)建工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
// 創(chuàng)建工作表
HSSFSheet sheet = workbook.createSheet("Sheet1");
// 創(chuàng)建單元格樣式
HSSFCellStyle cellStyle = workbook.createCellStyle();
// 水平對齊方式
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 垂直對齊方式
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
Font font = workbook.createFont();
font.setColor(HSSFColor.RED.index);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
cellStyle.setFont(font);
// 將第一行的三個單元格合并
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2));
HSSFRow row = sheet.createRow(0);
HSSFCell beginCell = row.createCell(0);
beginCell.setCellValue("通訊錄");
beginCell.setCellStyle(cellStyle);
row = sheet.createRow(1);
// 創(chuàng)建表頭
for (int i = 0; i < tableHeaders.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellValue(tableHeaders[i]);
cell.setCellStyle(cellStyle);
}
List<User> users = new ArrayList<User>();
users.add(new User(1L, "張三", 20));
users.add(new User(2L, "李四", 21));
users.add(new User(3L, "王五", 22));
for (int i = 0; i < users.size(); i++) {
row = sheet.createRow(i + 2);
User user = users.get(i);
row.createCell(0).setCellValue(user.getId());
row.createCell(1).setCellValue(user.getName());
row.createCell(2).setCellValue(user.getAge());
}
OutputStream out = response.getOutputStream();
response.reset();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment;filename=template.xls");
workbook.write(out);
out.flush();
out.close();
}
@RequestMapping("/import.do")
public void importFromFile(@RequestParam("file") MultipartFile file) throws IOException {
InputStream in = file.getInputStream();
BufferedInputStream bis = new BufferedInputStream(in);
POIFSFileSystem fileSystem = new POIFSFileSystem(bis);
HSSFWorkbook workbook = new HSSFWorkbook(fileSystem);
HSSFSheet sheet = workbook.getSheetAt(0);
int lastRowNum = sheet.getLastRowNum();
System.out.println("lastRowNum:" + lastRowNum);
for (int i = 2; i <= lastRowNum; i++) {
HSSFRow row = sheet.getRow(i);
int id = (int) row.getCell(0).getNumericCellValue();
String name = row.getCell(1).getStringCellValue();
int age = (int) row.getCell(2).getNumericCellValue();
System.out.println(id + "-" + name + "-" + age);
}
bis.close();
}
}
更多參考文章
點擊下載測試項目源碼
提取碼:8j9s
作者:vbirdbest
來源:CSDN
原文:https://blog.csdn.net/vbirdbest/article/details/72870714