--所需包:
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
--导入Exls文件模板
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set factory constraints
factory.setSizeThreshold(1024 * 1024);
//设置读入的文件暂时存放的目录
factory.setRepository(new File("."));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(1024 * 1024 * 5);
// Parse the request
List items = null;
String
failed = "<font color='red'>导入失败</font><br>";
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
state.setState(state.EXCEPTION);
state.setException(e.getMessage());
return;
}
Iterator iter = items.iterator();
while (iter.
hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
InputStream is = null;
try {
is = item.getInputStream();
} catch (IOException e) {
e.printStackTrace();
state.setState(state.EXCEPTION);
state.setException(failed + e.getMessage());
return;
}
Workbook workbook = null;
try {
workbook = WorkbookFactory.create(is);
} catch (InvalidFormatException e) {
e.printStackTrace();
state.setState(state.EXCEPTION);
state.setException(failed + e.getMessage());
is.close();
return;
}
/**要从项目信息表中取信息**/
Sheet sheet = workbook.getSheet("项目信息表");
if(sheet == null){
state.setState(state.EXCEPTION);
state.setException(failed + "Excel无[项目信息表]sheet表单");
return;
}
/**日期格式器**/
SimpleDateFormat formater = new SimpleDateFormat("yyyy/MM/dd");
/**用于存放导入的excel模板中所有记录**/
List<ImportExportProjectRecord> list = new ArrayList<ImportExportProjectRecord>();
/**模板中的信息是从第3行开始的,所以j=2**/
Connection con = null;
Statement statement = null;
try{
for (int j = 2; j < sheet.getLastRowNum()+1; j++) {
Row rowRecord = sheet.getRow(j);
/**项目名称是自动生成的**/
Cell cell;
/**项目状态**/
cell = rowRecord.getCell(1,Row.RETURN_BLANK_AS_NULL);
String bur_state = null;
if(cell != null){
bur_state = cell.getStringCellValue();
}
。。。。
}
}
--备注
/**剔除模板中的空行**//*
for(int j = 0 ; j < list.size() ; j ++ ){
if(list.get(j).isEmpty()){
list.remove(j);
}
}*/