java程式碼解析excel檔案(包含日期、小數的處理)
阿新 • • 發佈:2019-01-28
package com.test.test;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class VolumeTest2 {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
VolumeTest2 test=new VolumeTest2();
test.readXlsx();
}
@SuppressWarnings("deprecation")
private void readXlsx() throws IOException{
String fileName = "e:\\Test2.xlsx";
XSSFWorkbook xssfWorkbook = new XSSFWorkbook(fileName);
List<String> list = new ArrayList<String>();
// 迴圈工作表Sheet
for(int numSheet = 0; numSheet < xssfWorkbook.getNumberOfSheets(); numSheet++){
XSSFSheet xssfSheet = xssfWorkbook.getSheetAt( numSheet);
if(xssfSheet == null){
continue;
}
if(xssfSheet.getLastRowNum() == 0){
continue;
}
//System.out.println(xssfSheet.getLastRowNum()+"###www");
// 迴圈行Row
for(int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++ ){
XSSFRow xssfRow = xssfSheet.getRow(rowNum);
if(xssfRow == null||xssfRow.toString().trim().equals("")){
continue;
}
// 迴圈列Cell
for(int cellNum = 1; cellNum <= xssfRow.getLastCellNum(); cellNum++){
XSSFCell xssfCell = xssfRow.getCell(cellNum);
if(xssfCell == null||xssfCell.toString().trim().equals("")){
continue;
}
System.out.print(getValue(xssfCell));
list.add(getValue(xssfCell));
}
System.out.println();
}
}
System.out.println("該集合最大值為"+Collections.max(list)+" 長度為"+list.size());
}
@SuppressWarnings("static-access")
private static String getValue(XSSFCell xssfCell){
if(xssfCell.getCellType() == xssfCell.CELL_TYPE_BOOLEAN){
return String.valueOf( xssfCell.getBooleanCellValue());
}else if(xssfCell.getCellType() == xssfCell.CELL_TYPE_NUMERIC){
if(HSSFDateUtil.isCellDateFormatted(xssfCell)) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = xssfCell.getDateCellValue();
return sdf.format(date);
}else {
String xssfCell2 = String.valueOf(xssfCell.getNumericCellValue());
DecimalFormat df = new DecimalFormat("#.#########");
return df.format(Double.valueOf(xssfCell2));
}
}else{
return String.valueOf(xssfCell.getStringCellValue());
}
}
}