中国开发网: 论坛: 程序员情感CBD: 贴子 493061
wynnhjg
有啥高效的做法没?
import java.io.FileInputStream;
import java.text.DecimalFormat;
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;

public class ReadExcel {

public static String outputFile = "Test.xls";

public static String fileToBeRead = "Test.xls";

public List readExcel() {

DecimalFormat df = new DecimalFormat("#");

try {
// 创建对Excel工作簿文件的引用
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(
fileToBeRead));

List list = new ArrayList();

for (int numSheets = 0; numSheets < workbook.getNumberOfSheets(); numSheets++) {
if (null != workbook.getSheetAt(numSheets)) {
HSSFSheet aSheet = workbook.getSheetAt(numSheets);// 获得一个sheet

for (int rowNumOfSheet = 1; rowNumOfSheet <= aSheet
.getLastRowNum(); rowNumOfSheet++) {
Customer customer = new Customer();
if (null != aSheet.getRow(rowNumOfSheet)) {
HSSFRow aRow = aSheet.getRow(rowNumOfSheet);

for (short cellNumOfRow = 0; cellNumOfRow <= aRow
.getLastCellNum(); cellNumOfRow++) {
if (null != aRow.getCell(cellNumOfRow)) {
HSSFCell aCell = aRow.getCell(cellNumOfRow);

int cellType = aCell.getCellType();

switch (cellType) {
case 0:
String strCell = df.format(aCell
.getNumericCellValue());
if (cellNumOfRow == 3) {
customer.setTel(strCell);
}

break;
case 1:
strCell = aCell.getStringCellValue();
if (cellNumOfRow == 0) {
customer.setName(strCell);
}
if (cellNumOfRow == 1) {
customer.setSex(strCell);
}
if (cellNumOfRow == 2) {
customer.setAddress(strCell);
}
break;
default:

}

}

}
list.add(customer);
}

}

}

}
return list;
} catch (Exception e) {
System.out.println("ReadExcelError" + e);
return null;

}

}

public static void main(String[] args) {

List list = new ArrayList();

ReadExcel readExcel = new ReadExcel();

list = readExcel.readExcel();

for (int i = 0; i < list.size(); i++) {
Customer customer = new Customer();

customer = (Customer) list.get(i);
System.out.println(customer.getName() + "\t" + customer.getSex()
+ "\t" + customer.getAddress() + "\t" + customer.getTel());
}

}

}

相关信息:


欢迎光临本社区,您还没有登录,不能发贴子。请在 这里登录