有時候我們在做項目時,有些項目需要生成Microsoft Excel文件格式的報告。有時,甚至希望將Excel文件作爲輸入數據。這是我們需要用到Apache POI 。例如,本次利用 POI 技術實現使用模板批量添加數據。
下載上傳模板
1.編寫頁面
function downloadTemplate(){
window.open('template/userExporTemplate.xls');
}
2.查看結果
利用 POI 技術實現使用模板批量添加數據
1.編寫導出工具類
public static String formatCell(HSSFCell hssfCell){
if(hssfCell==null){
return "";
}else{
if(hssfCell.getCellType()==HSSFCell.CELL_TYPE_BOOLEAN){
return String.valueOf(hssfCell.getBooleanCellValue());
}else if(hssfCell.getCellType()==HSSFCell.CELL_TYPE_NUMERIC){
return String.valueOf(hssfCell.getNumericCellValue());
}else{
return String.valueOf(hssfCell.getStringCellValue());
}
}
}
2.編寫action類導出方法
public String upload()throws Exception{
POIFSFileSystem fs=new POIFSFileSystem(new FileInputStream(userUploadFile));
HSSFWorkbook wb=new HSSFWorkbook(fs);
HSSFSheet hssfSheet=wb.getSheetAt(0); // 獲取第一個Sheet頁
if(hssfSheet!=null){
for(int rowNum=1;rowNum<=hssfSheet.getLastRowNum();rowNum++){
HSSFRow hssfRow=hssfSheet.getRow(rowNum);
if(hssfRow==null){
continue;
}
User user=new User();
user.setName(ExcelUtil.formatCell(hssfRow.getCell(0)));
user.setPhone(ExcelUtil.formatCell(hssfRow.getCell(1)));
user.setEmail(ExcelUtil.formatCell(hssfRow.getCell(2)));
user.setQq(ExcelUtil.formatCell(hssfRow.getCell(3)));
Connection con=null;
try{
con=dbUtil.getCon();
userDao.userAdd(con, user);
}catch(Exception e){
e.printStackTrace();
}finally{
dbUtil.closeCon(con);
}
}
}
JSONObject result=new JSONObject();
result.put("success", "true");
ResponseUtil.write(ServletActionContext.getResponse(), result);
return null;
}
3.編寫頁面
<div id="dlg2" class="easyui-dialog" style="width:400px;height:180px;padding:10px 20px"
closed="true" buttons="#dlg-buttons2">
<form id="uploadForm" action="user!upload" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>下載模版:</td>
<td><a href="javascript:void(0)" class="easyui-linkbutton" onclick="downloadTemplate()">導入模版</a></td>
</tr>
<tr>
<td>上傳文件:</td>
<td><input type="file" name="userUploadFile"></td>
</tr>
</table>
</form>
</div>
function uploadFile(){
alert("1");
$("#uploadForm").form("submit",{
success:function(result){
var result=eval('('+result+')');
if(result.errorMsg){
$.messager.alert("系統提示",result.errorMsg);
}else{
$.messager.alert("系統提示","上傳成功");
$("#dlg2").dialog("close");
$("#dg").datagrid("reload");
}
}
});
}
4.查看結果