標籤

星期三, 12月 29, 2010

以POI讀取Excel檔案儲存格內容

此工具類別提供靜態方法,將所傳入之儲存格物件解析其格式依指定型態字串,傳回內容值之字串。

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.DateUtil;

/**
* @author Acer
*
*/
public class HSSFCellUtil {

public static String getCellContent(HSSFCell cell, String type) {
return getCellContent(cell, type, "");
}

public static String getCellContent(HSSFCell cell, String type, String pattern) {

String content = "";
if (!(cell == null)) {
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_STRING:
content = cell.getStringCellValue().trim();
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
content = new Boolean(cell.getBooleanCellValue()).toString();
break;
case HSSFCell.CELL_TYPE_NUMERIC:
if (HSSFDateUtil.isCellDateFormatted(cell)) {
Date d = HSSFDateUtil.getJavaDate(cell.getNumericCellValue());
if (pattern != "" || (!pattern.equals(""))) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
content = sdf.format(d);
} else
content = d.toString();
} else {
if (type.equals("byte")) {
content = new Byte(new Double(cell
.getNumericCellValue()).byteValue()).toString();
} else if (type.equals("short")) {
content = new Short(new Double(cell
.getNumericCellValue()).shortValue())
.toString();
} else if (type.equals("int")) {
content = new Integer(new Double(cell
.getNumericCellValue()).intValue()).toString();
} else if (type.equals("long")) {
content = new Long(new Double(cell
.getNumericCellValue()).longValue()).toString();
} else if (type.equals("float")) {
content = new Float(new Double(cell
.getNumericCellValue()).floatValue())
.toString();
} else if (type.equals("double")) {
content = new Double(cell.getNumericCellValue())
.toString();
} else if (type.equals("string")) {
content = new Double(cell.getNumericCellValue())
.toString().replaceAll("\\.[0]*", "");
} else {
content = new Double(cell.getNumericCellValue())
.toString();
}
}
break;
default:
break;
}
}
return content;
}
}

沒有留言: