📄 excelutil.java
字号:
package com.sxit.wap.groupuser;
import java.io.*;
import java.util.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.poifs.filesystem.*;
import com.sxit.wap.common.*;
import com.sxit.wap.exception.*;
public class ExcelUtil {
HSSFWorkbook wb = null;
HSSFSheet sheet = null;
public ExcelUtil() {
}
public Collection read(String fileName) throws AppException {
Collection value = new ArrayList();
try {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(fileName));
wb = new HSSFWorkbook(fs);
sheet = wb.getSheetAt(0);
} catch (IOException e) {
throw new AppException("读取EXCEL文件失改");
}
int rowCount = sheet.getLastRowNum();
System.out.println("************" + rowCount);
int columnCount = 2;
HSSFRow hssfrow = null;
HSSFCell cell = null;
for (int row=1; row<=rowCount-1; row++) {
hssfrow = sheet.getRow(row);
if (hssfrow == null) continue;
Hashtable element = new Hashtable();
for (short column=0; column<columnCount; column++) {
cell = hssfrow.getCell(column);
String s = "";
if (cell != null) {
if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
double d = cell.getNumericCellValue();
long l = (long)d;
s = "" + l;
} else if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
s = cell.getStringCellValue();
}
}
try {
switch (column) {
case 0:
if (StringUtil.isEmpty(s))
throw new AppException("手机号不能为空");
s = PageUtil.parseStringField(s, "手机号码", false, 11);
element.put("userMdn", s);
break;
case 1:
if (StringUtil.isEmpty(s))
throw new AppException("用户姓名不能为空");
s = PageUtil.parseStringField(s, "用户姓名", false, 20);
element.put("userName", s);
break;
}
} catch (AppException e) {
throw new AppException(e.getMessage() + ",出错位置在文件中的第" + (row+1) + "行,第" + (column+1) + "列");
}
}
value.add(element);
}
return value;
}
public static void main(String[] args){
String fileName = "D:\\0099.xls";
ExcelUtil ex = new ExcelUtil();
try{
Collection coll = ex.read(fileName);
Iterator it = coll.iterator();
while(it.hasNext()){
Hashtable ht = (Hashtable)it.next();
System.out.println(ht.get("userMdn"));
}
System.out.println(coll.size());
}catch(Exception e){
e.printStackTrace();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -