您的位置:首页 > 运维架构 > Apache

Apache POI 第七讲之利用 POI 技术实现使用模板批量添加数据

2016-07-07 12:52 871 查看
有时候我们在做项目时,有些项目需要生成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.查看结果





内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  apache poi 数据