直接扔代码:
package test;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
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;
import com.ctsi.common.CTSIException;
import com.zhongying.busi.common.SLSpeed;
public class ReadExcelPoi {
private ArrayList<SLSpeed> result = new ArrayList<SLSpeed>();// 记录集合
SLSpeed slSpeed = null;// 一行记录
public List<SLSpeed> getImportInfoFromExcel(String filePath)
throws CTSIException, Exception {
InputStream is = null;
HSSFWorkbook wb = null;
try {
is = new FileInputStream(filePath);
wb = new HSSFWorkbook(is);
// 循环sheet页
for (int numSheet = 0; numSheet < wb.getNumberOfSheets(); numSheet++) {
HSSFSheet sheet = wb.getSheetAt(numSheet);
if (sheet == null) {
continue;
}
// 处理当前sheet页中的每一行
for (int i = 1; i < sheet.getLastRowNum(); i++) {
HSSFRow row = sheet.getRow(i);
slSpeed = new SLSpeed();
if (row == null) {
continue;
}
HSSFCell xh = row.getCell((short) 0);
HSSFCell xh2 = row.getCell((short) 1);
if ((xh == null || xh.getCellType() == HSSFCell.CELL_TYPE_BLANK)
&& (xh2 == null || xh2.getCellType() == HSSFCell.CELL_TYPE_BLANK)) {
continue;
}
slSpeed.setImCustAccountNum(getValue(xh));
slSpeed.setImpSpeed(getValue(xh2));
if (!slSpeed.getImCustAccountNum().equals("")
|| !slSpeed.getImpSpeed().equals("")) {
if (slSpeed.getImpSpeed() == null
|| slSpeed.getImpSpeed().equals("")) {
slSpeed.setErrInfo("电路速率为空");
} else {
if (!isNum(slSpeed.getImpSpeed())) {
slSpeed.setErrInfo("电路速率不是数字");
}
}
if (slSpeed.getCustAccountNum() == null
|| slSpeed.getCustAccountNum().equals("")) {
slSpeed.setErrInfo("专线号格式不对");
}
if (slSpeed.getImCustAccountNum() == null
|| slSpeed.getImCustAccountNum().equals("")) {
slSpeed.setErrInfo("专线号为空");
}
if (!result.contains(slSpeed)) {
result.add(slSpeed);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
private String getValue(HSSFCell cell) {
String temp = "";
if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
temp = cell.getStringCellValue();
} else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
temp = String.valueOf(cell.getNumericCellValue());
}
return temp;
}
private boolean isNum(String num) {
try {
Integer.parseInt(num);
return true;
} catch (Exception e) {
return false;
}
}
public static void main(String[] args) throws Exception {
ReadExcelPoi rep = new ReadExcelPoi();
rep.getImportInfoFromExcel("E:\\6530.xls");
}
}
不知道怎么添加Excel附件,所以直接把Excel截了图片,一看就明白。