如何读取格式化单元格数据
在实际开发应用中,我们会遇到用户需要我们提供一个导入excel的数据功能,如果用户没有对数据进行格式,我们利用POI读取的数据与显示的实际值是一致的。
当用户对某列进行函数运算或数值格式后,显示的数值与实际值就不一样了。我们如何读取显示的值了,在网上找了很多资料,还没有发现有一篇对这个问题提供思路的文章,本人将提供
一种解决思路。
解决的思路基本思路如下:
1.先获取sheet
2.再获取row
3.获取cell
4.获取cellStyle
5.获取cellStyle 的getDataformatString
6.根据DataformatString判断处理
代码如下
package org.rodjson.io;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
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.xssf.usermodel.XSSFWorkbook;
/** */
public class POIExcelUtil {
private int totalRows = 0;// 总行数
private int totalCells = 0;// 总列数
public POIExcelUtil() {
}
// 根据文件名读取excel文件
public List<ArrayList<String>> read(String fileName) {
List<ArrayList<String>> dataLst = new ArrayList<ArrayList<String>>();
// 检查文件名是否为空或者是否是Excel格式的文件
if (fileName == null || !fileName.matches("^.+\\.(?i)((xls)|(xlsx))$")) {
return dataLst;
}
boolean isExcel2003 = true;
// 对文件的合法性进行验
if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
isExcel2003 = false;
}
// 检查文件是否存在
File file = new File(fileName);
if (file == null || !file.exists()) {
return dataLst;
}
try {
// 读取excel
dataLst = read(new FileInputStream(file), isExcel2003);
} catch (Exception ex) {
ex.printStackTrace();
}
return dataLst;
}
// 根据流读取Excel文件
public List<ArrayList<String>> read(InputStream inputStream, boolean isExcel2003) {
List<ArrayList<String>> dataLst = null;
try {
// 根据版本选择创建Workbook的方式
Workbook wb = isExcel2003 ? new HSSFWorkbook(inputStream) : new XSSFWorkbook(inputStream);
dataLst = read(wb);
} catch (IOException e) {
e.printStackTrace();
}
return dataLst;
}
// 得到总行数
public int getTotalRows() {
return totalRows;
}
// 得到总列数
public int getTotalCells() {
return totalCells;
}
// 读取数据
private List<ArrayList<String>> read(Workbook wb) {
List<ArrayList<String>> dataLst = new ArrayList<ArrayList<String>>();
Sheet sheet = wb.getSheetAt(0);// 得到第一个shell
this.totalRows = sheet.getPhysicalNumberOfRows();
if (this.totalRows >= 1 && sheet.getRow(0) != null) {
this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
}
// 循环Excel的行
for (int r = 0; r < this.totalRows; r++) {
Row row = sheet.getRow(r);
if (row == null) {
continue;
}
ArrayList<String> rowLst = new ArrayList<String>();
// 循环Excel的列
for (short c = 0; c < this.getTotalCells(); c++) {
Cell cell = row.getCell(c);
String cellValue = "";
String cellStyle="";
if (cell == null) {
rowLst.add(cellValue);
continue;
}
// 处理数字型的,自动去零
if (Cell.CELL_TYPE_NUMERIC == cell.getCellType()) {
cellStyle=getFormatCellStyle(cell.getCellStyle().getDataFormatString());//获取单元格样式
cellValue = getRightStr(cell.getNumericCellValue() + "",cellStyle);
} else if (Cell.CELL_TYPE_STRING == cell.getCellType()) {// 处理字符串型
cellValue = cell.getStringCellValue();
} else if (Cell.CELL_TYPE_BOOLEAN == cell.getCellType()) {// 处理布尔型
cellValue = cell.getBooleanCellValue() + "";
} else {// 其它数据类型
cellValue = cell.toString() + "";
}
rowLst.add(cellValue);
}
dataLst.add(rowLst);
}
return dataLst;
}
/**
* @author RodJohnSon
* @param String
* @return String
* @exception
*
* GET CELLSTYLE
* */
private String getFormatCellStyle(String cellStyle){
String FormatCellStyle="";
if(cellStyle.endsWith("_")){
cellStyle=cellStyle.replace("_", "");
}else{
cellStyle=cellStyle.split(";")[0];
cellStyle=cellStyle.trim();
cellStyle=cellStyle.replace(")", "");
cellStyle=cellStyle.replace("_", "");
}
FormatCellStyle=cellStyle+"#";
return FormatCellStyle;
}
// 格式化数据
private String getRightStr(String sNum,String cellStyle) {
if(cellStyle.endsWith("#")){
DecimalFormat decimalFormat = new DecimalFormat(cellStyle);
String resultStr = decimalFormat.format(new Double(sNum));
if (resultStr.matches("^[-+]?\\d+\\.[0]+$")) {
resultStr = resultStr.substring(0, resultStr.indexOf("."));
}
return resultStr;
}else{
return sNum;
}
}
public static void main(String[] args) throws Exception {
String fileName = "e:\\2012.xls";//读取2003的OK
//String fileName = "e:\\2013.xlsx";// 读取 2007的OK
POIExcelUtil excelUtil = new POIExcelUtil();
List<ArrayList<String>> dataLst = excelUtil.read(fileName);// 读取excle,并把数据打包成list
System.out.println(" --------------------------excel内容如下--------------------------------");
for (ArrayList<String> innerLst : dataLst) {
StringBuffer rowData = new StringBuffer();
for (String dataStr : innerLst) {
rowData.append(",").append(dataStr);
}
if (rowData.length() > 0) {
System.out.println(" " + rowData.deleteCharAt(0).toString());
}
}
System.out.println(" 总行数:" + excelUtil.getTotalRows() + " , 总列数:" + excelUtil.getTotalCells());
}
}