import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class CommonReadExcel {
public void readExcel(String filePath) throws Exception {
Map<String, String> map = new HashMap<String, String>();
String value = "";
HSSFWorkbook wookbook = new HSSFWorkbook(new FileInputStream(filePath));
HSSFSheet sheet = wookbook.getSheetAt(0);
int rows = sheet.getPhysicalNumberOfRows();// hang
int max_cells = 0;// 列
// 获取最长的列,在实践中发现如果列中间有空值的话,那么读到空值的地方就停止了。所以我们需要取得最长的列
for (int i = 0; i < rows; i++) {
HSSFRow row = sheet.getRow(i);
if (row != null) {
int cells = row.getPhysicalNumberOfCells();
if (max_cells < cells) {
max_cells = cells;
}
}
}
for (int i = 1; i < rows; i++) {
HSSFRow row = sheet.getRow(i);
if (row != null) {
// 遍历列
for (int j = 0; j < max_cells; j++) {
HSSFCell cell = row.getCell(j);
if (cell == null) {
value += "NULL,";
}else{
//判断单元格的类型
switch(cell.getCellType()){
case(HSSFCell.CELL_TYPE_NUMERIC):
value = value + cell.getNumericCellValue() + ",";
break;
case(HSSFCell.CELL_TYPE_FORMULA)://公式
try{
value = value + cell.getNumericCellValue() + ",";// cell.getCellFormula()
}catch(Exception e ){
value = value + cell.getRichStringCellValue() + ",";
}
break;
case(HSSFCell.CELL_TYPE_STRING):
value = value + cell.getStringCellValue() + ",";
break;
}
}
}
}
}
String[] k = value.split(",");
for (String string : k) {
System.out.println(string);
}
}
public static void main(String[] args) throws Exception {
CommonReadExcel cre = new CommonReadExcel();
cre.readExcel("C:\\Users\\Administrator.WINDOWS-VK1LA9F\\Desktop\\04接卫宁.xls");
}
}