Excel导入有两个方法:JXL 和POI
1、JXL解析Excel
public class JxlReadExcel {
/**
* JXL解析Excel
* @author David
* @param args
*/
public static void main(String[] args) {
try {
//创建workbook
Workbook workbook = Workbook.getWorkbook(new File("e:/students.xls"));
//获取第一个工作表sheet
Sheet sheet = workbook.getSheet(0);
//获取数据
for (int i = 0; i < sheet.getRows(); i++) {
for (int j = 0; j < sheet.getColumns(); j++) {
Cell cell = sheet.getCell(j,i);
System.out.print(cell.getContents() + " ");
}
System.out.println();
}
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
2、POI解析Excel
public class PoiReadExcel {
/**
* POI解析Excel文件内容
* @author David
* @param args
*/
public static void main(String[] args) {
//需要解析的Excel文件
File file = new File("e:/students.xls");
try {
//创建Excel,读取文件内容
HSSFWorkbook workbook =
new HSSFWorkbook(FileUtils.openInputStream(file));
//读取默认第一个工作表sheet
HSSFSheet sheet = workbook.getSheetAt(0);
int firstRowNum = 0;
//获取sheet中最后一行行号
int lastRowNum = sheet.getLastRowNum();
for (int i = firstRowNum; i <=lastRowNum; i++) {
HSSFRow row = sheet.getRow(i);
//获取当前行最后单元格列号
int lastCellNum = row.getLastCellNum();
for (int j = 0; j < lastCellNum; j++) {
HSSFCell cell = row.getCell(j);
if (row.getCell(j)!=null) {
row.getCell(j).setCellType(Cell.CELL_TYPE_STRING);
}
String value = cell.getStringCellValue();
System.out.print(value + " ");
}
System.out.println();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}