JXL操作excel的对象主要是:Workbook、Sheet、Cell。Workbook对应的就是一个excel,一个workbook可以有多个sheet对象,一个Sheet中有多个Cell。
读取excel的步骤概括为:
1. 上传excel文件,得到workbook
2. 选择workbook中的工作表sheet
3. 选定工作表中的单元格cell
4. 读取单元格cell中的信息
5. 关闭workbook,释放资源
下面看一下这几步的代码吧,用的是struts2上传。
<form action="fileUpload" method="post" enctype="multipart/form-data">
<input type="file" name="upload">
<input type="submit" value="上传">
</form>
public class uploadAction extends ActionSupport{
private File upload;
private String uploadFileName;
private String uploadContextType;
public String execute(){
try{
//1. 得到Workbook
Workbook book = Workbook.getWorkbook(upload);
//2. 得到Workbook中的工作表sheet
Sheet sheet = book.getSheet(0);
int rows = sheet.getRows();
if(rows<=1){
throw new Exception("Excel文件中没有任何数据");
}
//读取sheet并添加到数据库
for(int i=1;i<rows;i++){
//3. 选定excel中一行数据
Cell[] cell = sheet.getRow(i);
//定义数组接收excel中一行数据
Object[] object = new Object[cell.length];
//4. 将excel每个单元格数据放到数组中
for(int j=0;j<cell.length;j++){
System.out.println(sheet.getCell(j,i).getContents());
//object[j]=sheet.getCell(j,i).getContents();
}
}
//5. 最后关闭WorkBook
book.close();
}catch(Exception e){
e.printStackTrace();
}
return "success";
}
public File getUpload() {
return upload;
}
public void setUpload(File upload) {
this.upload = upload;
}
public String getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
public String getUploadContextType() {
return uploadContextType;
}
public void setUploadContextType(String uploadContextType) {
this.uploadContextType = uploadContextType;
}
}