歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> Apache POI處理Excel文檔

Apache POI處理Excel文檔

日期:2017/2/28 13:54:44   编辑:Linux教程

目前比較流行處理excel文檔的方式一般有兩種,分別是POI和JXL。重量級POI優缺點:適合對excel文檔細節有比較專業的要求,如使用公式、宏等高級功能;缺點是操作相對繁瑣,非純java編寫的架包,跨平台性有待加強。輕量級JXL優缺點:Jxl是純javaAPI,跨平台性優越,操作相對簡便;缺點是對excel文檔的一些高級功能不支持,但可以滿足日常需求。這裡我們介紹POI的基本使用。

1.首先導入相關架包,如圖:

這裡還要注意你開發項目的JDK版本是什麼,要根據相應JDK版本下載不同POI的版本。

如圖:

2.操作ExcelReader輔助類可以處理xls和xlsx文件,readExcelTitle(InputStream is)方法讀取文件標題,也就是文件首行,readExcelContent(InputStream is)方法讀取文件內容:

import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

/**
* 操作Excel表格的功能類
*/
public class ExcelReader {
private static DecimalFormat df = new DecimalFormat("0");
private final static Logger log = Logger.getLogger(ExcelReader.class);
private Workbook wb=null;
private Sheet sheet=null;
private Row row=null;

/**
* 讀取Excel表格表頭的內容
* @param InputStream
* @return String 表頭內容的數組
* @throws IOException
*/
public String[] readExcelTitle(InputStream is) throws Exception {
try {
wb = WorkbookFactory.create(is);
} catch (IOException e) {
log.error("讀取Excel表格表頭的內容異常", e);
throw e;
}
sheet = wb.getSheetAt(0);
row = sheet.getRow(0);
// 標題總列數
int colNum = row.getPhysicalNumberOfCells();
String[] title = new String[colNum];
for (int i = 0; i < colNum; i++) {
title[i] = getCellFormatValue(row.getCell(i));
}
log.info("讀取Excel表格表頭的內容完畢");
return title;
}

/**
* 讀取Excel數據內容
* @param InputStream
* @return Map 包含單元格數據內容的Map對象
* @throws IOException
*/
public Map<Integer, String> readExcelContent(InputStream is) throws Exception {
Map<Integer, String> content = new LinkedHashMap<Integer, String>();
String str = "";
try {
wb = WorkbookFactory.create(is);
} catch (IOException e) {
log.error("讀取Excel數據內容", e);
throw e;
}
sheet = wb.getSheetAt(0);
// 得到總行數
int rowNum = sheet.getLastRowNum();
row = sheet.getRow(0);
int colNum = row.getPhysicalNumberOfCells();
// 正文內容應該從第二行開始,第一行為表頭的標題
for (int i = 1; i <= rowNum; i++) {
row = sheet.getRow(i);
int j = 0;
while (j < colNum) {
// 每個單元格的數據內容用"-"分割開,以後需要時用String類的replace()方法還原數據
// 也可以將每個單元格的數據設置到一個javabean的屬性中,此時需要新建一個javabean
// str += getStringCellValue(row.getCell((short) j)).trim() +
// "-";
if (row != null) {
str += getCellFormatValue(row.getCell(j)).trim() + ",";
} else {
str += "" + ",";
}
j++;
}
content.put(i, str.substring(0, str.length() - 1));
str = "";
}
log.info("讀取Excel數據內容完畢");
return content;
}

/**
* 根據Cell類型設置數據
* @param cell
* @return
*/
private String getCellFormatValue(Cell cell) {
String cellvalue = "";
if (cell != null) {
// 判斷當前Cell的Type
switch (cell.getCellType()) {
// 如果當前Cell的Type為NUMERIC
case Cell.CELL_TYPE_NUMERIC:
case Cell.CELL_TYPE_FORMULA: {
// 判斷當前的cell是否為Date
if (DateUtil.isCellDateFormatted(cell)) {
// 如果是Date類型則,轉化為Data格式

//方法1:這樣子的data格式是帶時分秒的:2015-12-18 0:00:00
//cellvalue = cell.getDateCellValue().toLocaleString();

//方法2:這樣子的data格式是不帶帶時分秒的:2011-10-12
Date date = cell.getDateCellValue();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
cellvalue = sdf.format(date);

}
// 如果是純數字
else {
// 取得當前Cell的數值
cellvalue = String.valueOf(df.format(cell.getNumericCellValue()));
}
break;
}
// 如果當前Cell的Type為STRIN
case Cell.CELL_TYPE_STRING:
// 取得當前的Cell字符串
cellvalue = cell.getRichStringCellValue().getString();
break;
// 默認的Cell值
default:
cellvalue = " ";
}
} else {
cellvalue = "";
}
return cellvalue;

}
}

簡單實例代碼,實際使用中應該加上異常處理機制:
12345678910111213 FileInputStream is = new FileInputStream(file);
ExcelReader excelReader = new ExcelReader();
String[] title = excelReader.readExcelTitle(is);//讀取文件標題(非文件名,而是文件第一行)
for (String str : title) {
System.out.println(str);
}
is.close();
is = new FileInputStream(file);
Map<Integer, String> map = excelReader.readExcelContent(is);//讀取文件內容
for (int i = 1; i <= map.size(); i++) {
System.out.println(map.get(i));
}
is.close();

相關截圖:

POI實現導出EXCEL詳解 http://www.linuxidc.com/Linux/2014-10/108119.htm

POI 的詳細介紹:請點這裡
POI 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved