批量导出市场活动
需求分析
? 用户在市场活动主页面,点击"批量导出"按钮,把所有市场活动生成一个excel文件,弹出文件下载的对话框;
? 用户选择要保存的目录,完成导出市场活动的功能.
? *导出成功之后,页面不刷新
时序&流程
Mapper层
ActivityMapper.java
查询所有市场活动数据
List<Activity> selectAllActivitys();
ActivityMapper.xml
<select id="selectAllActivitys" resultMap="BaseResultMap">
select a.id,u1.name as owner,a.name,a.start_date,a.end_date,a.cost,a.description,a.create_time,
u2.name as create_by,a.edit_time,u3.name as edit_by
from tbl_activity a
join tbl_user u1 on a.owner=u1.id
join tbl_user u2 on a.create_by=u2.id
left join tbl_user u3 on a.edit_by=u3.id
order by a.create_time desc
</select>
Service层
ActivityService.java
创建查询所有活动的业务
List<Activity> queryAllActivitys();
ActivityServiceImpl.java
调用activityMapper的selectAllActivitys方法实现ActivityService的queryAllActivitys业务
@Override
public List<Activity> queryAllActivitys() {
return activityMapper.selectAllActivitys();
}
Controller层
笔记1 导出数据
导出市场活动:
? 1)给"批量导出"按钮添加单击事件,发送导出请求 ? 2)查询所有的市场活动 ? 3)创建一个excel文件,并且把市场活动写到excel文件中 ? 4)把生成的excel文件输出到浏览器(文件下载)
笔记2 数据写入excel文件
1)使用java生成excel文件:iText,apache-poi 关于办公文档插件使用的基本思想:把办公文档的所有元素封装成普通的Java类,程序员通过操作这些类达到操作办公文档目的。 文件---------HSSFWorkbook 页-----------HSSFSheet 行-----------HSSFRow 列-----------HSSFCell 样式---------HSSFCellStyle
使用apache-poi生成excel: a)添加依赖:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
? b)使用封装类生成excel文件:
2)文件下载: filedownloadtest.jsp ActivityController |->fileDownload()
*所有文件下载的请求只能发送同步请求。
? b)使用封装类生成excel文件:
@RequestMapping("/workbench/activity/exportAllActivitys.do")
public void exportAllActivitys(HttpServletResponse response) throws Exception{
List<Activity> activityList=activityService.queryAllActivitys();
HSSFWorkbook wb=new HSSFWorkbook();
HSSFSheet sheet=wb.createSheet("市场活动列表");
HSSFRow row=sheet.createRow(0);
HSSFCell cell;
String[] titles = {"ID","所有者","名称","开始日期","结束日期","成本","描述","创建时间","创建者","修改时间","修改者"};
for (int i = 0 ; i < titles.length ; i ++){
cell=row.createCell(i);
cell.setCellValue(titles[i]);
}
if(activityList!=null && activityList.size()>0){
Activity activity=null;
for(int i=0;i<activityList.size();i++){
activity=activityList.get(i);
row=sheet.createRow(i+1);
String[] contents = {activity.getId(),activity.getOwner(),activity.getName(),activity.getStartDate(),activity.getEndDate(),activity.getCost(),
activity.getDescription(),activity.getCreateTime(),activity.getCreateBy(),activity.getEditTime(),activity.getEditBy()};
for (int j = 0 ; j < contents.length ; j ++){
cell=row.createCell(j);
cell.setCellValue(contents[j]);
}
}
}
response.setContentType("application/octet-stream;charset=UTF-8");
response.addHeader("Content-Disposition","attachment;filename=activityList.xls");
OutputStream out=response.getOutputStream();
wb.write(out);
wb.close();
out.flush();
}
前台页面
index.jsp
给“批量导出”按钮加id选择器
<button id="exportActivityAllBtn" type="button" class="btn btn-default"><span class="glyphicon glyphicon-export"></span> 下载列表数据(批量导出)</button>
单击事件向后台发起导出请求
$("#exportActivityAllBtn").click(function () {
window.location.href="workbench/activity/exportAllActivitys.do";
});
选择导出市场活动
需求分析
? 用户在市场活动主页面,选择要导出的市场活动,点击"选择导出"按钮,把所有选择的数据生成一个excel文件,弹出文件下载的对话框;
? 用户选择要保存的目录,完成选择导出市场活动的功能.
*每次至少选择导出一条记录
? *导出成功之后,页面不刷新
时序&流程
与批量导出类似
Mapper层
ActivityMapper.java
List<Activity> selectActivityByIds(String[] ids);
ActivityMapper.xml
<select id="selectActivityByIds" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from tbl_activity
where id in
<foreach collection="array" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</select>
Service层
ActivityService.java
List<Activity> queryActivityByIds(String[] ids);
ActivityServiceImpl.java
@Override
public List<Activity> queryActivityByIds(String[] ids) {
return activityMapper.selectActivityByIds(ids);
}
Controller层
@RequestMapping("/workbench/activity/exportActivitysByIds.do")
public void exportActivitysByIds(HttpServletResponse response, HttpServletRequest request) throws Exception {
String checkId=request.getParameter("checkId");
System.out.println("接收的checkid:"+checkId);
String[] ids=checkId.split(",");
List<Activity> activityList = activityService.queryActivityByIds(ids);
HSSFWorkbook wb=new HSSFWorkbook();
HSSFSheet sheet=wb.createSheet("市场活动列表");
HSSFRow row=sheet.createRow(0);
HSSFCell cell;
String[] titles = {"ID","所有者","名称","开始日期","结束日期","成本","描述","创建时间","创建者","修改时间","修改者"};
for (int i = 0 ; i < titles.length ; i ++){
cell=row.createCell(i);
cell.setCellValue(titles[i]);
}
if (activityList!=null && activityList.size()>0){
Activity activity=null;
for(int i=0;i<activityList.size();i++) {
activity=activityList.get(i);
row=sheet.createRow(i+1);
String[] contents = {activity.getId(), activity.getOwner(), activity.getName(), activity.getStartDate(), activity.getEndDate(), activity.getCost(),
activity.getDescription(), activity.getCreateTime(), activity.getCreateBy(), activity.getEditTime(), activity.getEditBy()};
for (int j = 0 ; j < contents.length ; j ++){
cell=row.createCell(j);
cell.setCellValue(contents[j]);
}
}
}
response.setContentType("application/octet-stream;charset=UTF-8");
response.addHeader("Content-Disposition","attachment;filename=activityList.xls");
OutputStream out=response.getOutputStream();
wb.write(out);
wb.close();
out.flush();
}
前端页面
index.jsp
$("#exportActivityXzBtn").click(function () {
var chekkedIds=$("#tBody input[type='checkbox']:checked");
if(chekkedIds.size()==0){
alert("请选择要导出的市场活动");
return;
}
var checkId=[];
$("input[type='checkbox']:checked").each(function (i){
checkId[i]=$(this).val();
})
window.location.href="workbench/activity/exportActivitysByIds.do?checkId="+checkId;
});
导入市场活动数据
需求分析
用户在市场活动主页面,点击市场活动名称超级链接,跳转到明细页面,完成查看市场活动明细的功能.
? *在市场活动明细页面,展示:
? -市场活动的基本信息
? -该市场活动下所有的备注信息
时序&流程
Mapper层
ActivityMapper.java
int insertActivityByList(List<Activity> activityList);
ActivityMapper.xml
<insert id="insertActivityByList" parameterType="com.yyp.crm.workbench.domain.Activity">
insert into tbl_activity(id, owner, name, start_date, end_date, cost, description, create_time, create_by)
values
<foreach collection="list" item="obj" separator=",">
(#{obj.id},#{obj.owner},#{obj.name},#{obj.startDate},#{obj.endDate},#{obj.cost},#{obj.description},#{obj.createTime},#{obj.createBy})
</foreach>
</insert>
Service层
ActivityService.java
int saveCreateActivityByList(List<Activity> activityList);
ActivityServiceImpl.java
@Override
public int saveCreateActivityByList(List<Activity> activityList) {
return activityMapper.insertActivityByList(activityList);
}
准备工作
配置springmvc的文件上传解析器
applicationContext-mvc.xml
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="#{1024*1024*5}"/>
<property name="defaultEncoding" value="utf-8"/>
</bean>
关于excel文件操作的工具类
HSSFUtils.java
public static String getCellValueForStr(HSSFCell cell){
String ret="";
if(cell.getCellType()==HSSFCell.CELL_TYPE_STRING){
ret=cell.getStringCellValue();
}else if(cell.getCellType()==HSSFCell.CELL_TYPE_NUMERIC){
ret=cell.getNumericCellValue()+"";
}else if(cell.getCellType()==HSSFCell.CELL_TYPE_BOOLEAN){
ret=cell.getBooleanCellValue()+"";
}else if(cell.getCellType()==HSSFCell.CELL_TYPE_FORMULA){
ret=cell.getCellFormula();
}else{
ret="";
}
return ret;
}
Controller层
笔记3 导入市场活动
1)把用户计算机上的excel文件上传到服务器(文件上传) 2)使用java解析excel文件,获取excel文件中的数据 3)把解析出来的数据添加数据库中 4)返回响应信息
笔记4 解析excel文件数据
1)文件上传:
fileuploadtest.jsp
ActivityController
|->fileUpload()
2)使用java解析excel文件:iText,apache-poi
关于办公文档插件使用的基本思想:把办公文档的所有元素封装成普通的Java类,程序员通过操作这些类达到操作办公文档目的。
文件---------HSSFWorkbook
页-----------HSSFSheet
行-----------HSSFRow
列-----------HSSFCell
@RequestMapping("/workbench/activity/exportActivitysByIds.do")
public void exportActivitysByIds(HttpServletResponse response, HttpServletRequest request) throws Exception {
String checkId=request.getParameter("checkId");
System.out.println("接收的checkid:"+checkId);
String[] ids=checkId.split(",");
List<Activity> activityList = activityService.queryActivityByIds(ids);
HSSFWorkbook wb=new HSSFWorkbook();
HSSFSheet sheet=wb.createSheet("市场活动列表");
HSSFRow row=sheet.createRow(0);
HSSFCell cell;
String[] titles = {"ID","所有者","名称","开始日期","结束日期","成本","描述","创建时间","创建者","修改时间","修改者"};
for (int i = 0 ; i < titles.length ; i ++){
cell=row.createCell(i);
cell.setCellValue(titles[i]);
}
if (activityList!=null && activityList.size()>0){
Activity activity=null;
for(int i=0;i<activityList.size();i++) {
activity=activityList.get(i);
row=sheet.createRow(i+1);
String[] contents = {activity.getId(), activity.getOwner(), activity.getName(), activity.getStartDate(), activity.getEndDate(), activity.getCost(),
activity.getDescription(), activity.getCreateTime(), activity.getCreateBy(), activity.getEditTime(), activity.getEditBy()};
for (int j = 0 ; j < contents.length ; j ++){
cell=row.createCell(j);
cell.setCellValue(contents[j]);
}
}
}
response.setContentType("application/octet-stream;charset=UTF-8");
response.addHeader("Content-Disposition","attachment;filename=activityList.xls");
OutputStream out=response.getOutputStream();
wb.write(out);
wb.close();
out.flush();
}
@RequestMapping("/workbench/activity/importActivity.do")
public @ResponseBody Object importActivity(MultipartFile activityFile, String userName, HttpSession session){
System.out.println("userName="+userName);
User user=(User) session.getAttribute(Contants.SESSION_USER);
ReturnObject returnObject=new ReturnObject();
try {
InputStream is=activityFile.getInputStream();
HSSFWorkbook wb=new HSSFWorkbook(is);
HSSFSheet sheet=wb.getSheetAt(0);
HSSFRow row=null;
HSSFCell cell=null;
Activity activity=null;
List<Activity> activityList=new ArrayList<>();
for(int i=1;i<=sheet.getLastRowNum();i++) {
row=sheet.getRow(i);
activity=new Activity();
activity.setId(UUIDUtils.getUUID());
activity.setOwner(user.getId());
activity.setCreateTime(DateUtils.formateDateTime(new Date()));
activity.setCreateBy(user.getId());
for(int j=0;j<row.getLastCellNum();j++) {
cell=row.getCell(j);
String cellValue= HSSFUtils.getCellValueForStr(cell);
if(j==0){
activity.setName(cellValue);
}else if(j==1){
activity.setStartDate(cellValue);
}else if(j==2){
activity.setEndDate(cellValue);
}else if(j==3){
activity.setCost(cellValue);
}else if(j==4){
activity.setDescription(cellValue);
}
}
activityList.add(activity);
}
int ret=activityService.saveCreateActivityByList(activityList);
returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
returnObject.setRetData(ret);
}catch (Exception e){
e.printStackTrace();
returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
returnObject.setMessage("系统忙,请稍后重试....");
}
return returnObject;
}
前端页面
$("#importActivityBtn").click(function () {
var activityFileName=$("#activityFile").val();
var suffix=activityFileName.substr(activityFileName.lastIndexOf(".")+1).toLocaleLowerCase();
if(suffix!="xls"){
alert("只支持xls文件");
return;
}
var activityFile=$("#activityFile")[0].files[0];
if(activityFile.size>5*1024*1024){
alert("文件大小不超过5MB");
return;
}
var formData=new FormData();
formData.append("activityFile",activityFile);
formData.append("userName","元昱鹏");
$.ajax({
url:'workbench/activity/importActivity.do',
data:formData,
processData:false,
contentType:false,
type:'post',
dataType:'json',
success:function (data) {
if(data.code=="1"){
alert("成功导入"+data.retData+"条记录");
$("#importActivityModal").modal("hide");
queryActivityByConditionForPage(1,$("#demo_pag1").bs_pagination('getOption', 'rowsPerPage'));
}else{
alert(data.message);
$("#importActivityModal").modal("show");
}
}
});
});
|