import java.io.FileInputStream;
import java.util.ArrayList;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
public class TestPOIreadExcel {
public static void main(String[] args) throws Exception {
String base="C:/Documents and Settings/Administrator/桌面/";
String e2007 = "1.xlsx";
String e2003 = "1.xls";
String path =base+e2003;
Sheet esheet =null;
if(path.indexOf(".xlsx")!=-1) {
org.apache.poi.xssf.usermodel.XSSFWorkbook wb = new org.apache.poi.xssf.usermodel.XSSFWorkbook(new FileInputStream(path));
org.apache.poi.xssf.usermodel.XSSFSheet sheet = wb.getSheetAt(0); //获取2007excel第一页
esheet = sheet;
}else {
org.apache.poi.hssf.usermodel.HSSFWorkbook wb = new org.apache.poi.hssf.usermodel.HSSFWorkbook(new FileInputStream(path));
org.apache.poi.hssf.usermodel.HSSFSheet sheet = wb.getSheetAt(0); //获取2003excel第一页
esheet = sheet;
}
int[] cols = new int[]{0,1};
// readExcel(excel标签页,获取行,获取列);
readExcel(esheet,1,cols);
}
protected static ArrayList<String> readExcel(Sheet sheet, int rownum,int[] cols) {
ArrayList<String> rowData = new ArrayList<String>();
for (int colIndex : cols) {
Row row = sheet.getRow(rownum);
Cell cell = row.getCell(colIndex);
rowData.add(getCellValue(cell));
}
return rowData;
}
/** 获取单元格内容 */
private static String getCellValue(Cell cell) {
if (cell == null) {
return "";
}
String value = cell.toString().trim();
System.out.println(value+"===============");
try {
// This step is used to prevent Integer string being output with '.0'.
Float.parseFloat(value);
value = value.replaceAll("\\.0$", "");
value = value.replaceAll("\\.0+$", "");
return value;
} catch (NumberFormatException ex) {
return value;
}
}
}
POI读取excel
最新推荐文章于 2024-10-12 22:35:37 发布