求助贴:spring + springmvc + mybatis 使用POI导出,ajax请求后台返回时,ajax始终进入error

spring + springmvc + mybatis 使用使用POI导出,ajax请求后台返回时,ajax始终进入error,无论怎么修改返回类型,依然进入error,把dataType修改为text时,就进入了success,但是一直乱码,无论怎么设置编码格式,始终乱码,但是导入时,一样的写法又是正常的,不报错,求大佬们帮帮忙

前端请求代码:

function exportExcel(){
	layer.confirm("确定批量导出?",{title:"提示"},function(){
		$.ajax({
			url:"/LearnJAVAwithXge01/exportExcelAreas",
			type:"post",
			data:{},
			dataType:"json",
			success:function(result) {
				if (result == "1") {
					layer.alert("批量导出成功!",{title:"提示"});
				} else if (result == "-1") {
					layer.alert("无可导出数据,批量导出失败!",{title:"提示"});
				} else {
					layer.alert("批量导出失败!",{title:"提示"});
				}
			},
			error:function() {
				layer.alert("批量导出错误!",{title:"提示"});
			}
		});
	});
}

controller代码:

//Excel导出
	@RequestMapping(value = "/exportExcelAreas", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
	@ResponseBody
	public Object exportExcel(HttpServletRequest request, HttpServletResponse response) throws IOException{
		
		log.info("Excel导出准备...");
		
		List<Areas> list = service.exportExcel();
		
		if (list.size() > 0) {
			String message = ImportExportExcel.OutExcel(request, response, list, "areas");
			log.info("导出状态:" + message);
			
			if ("success".equals(message)) {
				return "1";
			}
			
			return null;
		}
		
		return "-1";
		
	}

工具类OutExcel:

/*
	 * 导出
	 */
	public static String OutExcel(HttpServletRequest request, HttpServletResponse response, List<?> list, String exportEntity){
		
		String message = "fail";
		//String dir = request.getSession().getServletContext().getRealPath("/export");
		String dir = "D:/Users/Desktop/export";//将文件导出至export文件夹
		log.info("导出路径为:" + dir);
		File fileLocation = new File(dir);
		if (!fileLocation.exists()) {
			boolean isCreated = fileLocation.mkdirs();//mkdirs():在本建立文件夹
			if (!isCreated) {
				return "本地文件创建失败!";
			}
		}
		
		//String webUrl = request.getSession().getServletContext().getRealPath("/export");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String createExcelName = sdf.format(new Date()) + "exportExcel.xls";
		String exportFile = dir + File.separator + createExcelName;
		log.info("导出的文件名:" + createExcelName);
		
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet();
		workbook.setSheetName(0, exportEntity);
		HSSFRow row1 = sheet.createRow(0);
		
		if ("areas".equals(exportEntity) || "languages".equals(exportEntity)) {//导出区域表,语言表
			//1行7列
			HSSFCell cell0 = row1.createCell(0,HSSFCell.CELL_TYPE_STRING);
			HSSFCell cell1 = row1.createCell(1,HSSFCell.CELL_TYPE_STRING);
			HSSFCell cell2 = row1.createCell(2,HSSFCell.CELL_TYPE_STRING);
			HSSFCell cell3 = row1.createCell(3,HSSFCell.CELL_TYPE_STRING);
			HSSFCell cell4 = row1.createCell(4,HSSFCell.CELL_TYPE_STRING);
			HSSFCell cell5 = row1.createCell(5,HSSFCell.CELL_TYPE_STRING);
			HSSFCell cell6 = row1.createCell(6,HSSFCell.CELL_TYPE_STRING);
			
			//设置列名
			cell0.setCellValue("ID");
			cell1.setCellValue("Name");
			cell2.setCellValue("Creater");
			cell3.setCellValue("CreateTime");
			cell4.setCellValue("Modifier");
			cell5.setCellValue("ModifiedTime");
			cell6.setCellValue("ModuleId");
			response.setContentType("text/html;charset=UTF-8");
			
			if ("areas".equals(exportEntity)) {
				for (int i = 0 ; i < list.size(); i++) {
					Areas areas = new Areas();
					areas = (Areas) list.get(i);
					
					HSSFRow row = sheet.createRow(i + 1);
					//1行7列,设置列值
					HSSFCell c0 = row.createCell(0,HSSFCell.CELL_TYPE_STRING);
					HSSFCell c1 = row.createCell(1,HSSFCell.CELL_TYPE_STRING);
					HSSFCell c2 = row.createCell(2,HSSFCell.CELL_TYPE_STRING);
					HSSFCell c3 = row.createCell(3,HSSFCell.CELL_TYPE_STRING);
					HSSFCell c4 = row.createCell(4,HSSFCell.CELL_TYPE_STRING);
					HSSFCell c5 = row.createCell(5,HSSFCell.CELL_TYPE_STRING);
					HSSFCell c6 = row.createCell(6,HSSFCell.CELL_TYPE_STRING);
					
					//判断值是否为空
					if ((null == areas.getAreaModifier()) || "".equals(areas.getAreaModifier())) {
						c0.setCellValue(areas.getAreaId());
						c1.setCellValue(areas.getAreaName());
						c2.setCellValue(areas.getAreaCreater());
						c3.setCellValue(areas.getAreaCreateTime());
						c4.setCellValue("");
						c5.setCellValue("");
						c6.setCellValue(areas.getMasterModuleId());
						
						log.info("导出的值为:" + areas.getAreaId() + "," + areas.getAreaName() + "," + areas.getAreaCreater() + "," + areas.getAreaCreateTime() + "," + areas.getMasterModuleId());
					
					} else {
						c0.setCellValue(areas.getAreaId());
						c1.setCellValue(areas.getAreaName());
						c2.setCellValue(areas.getAreaCreater());
						c3.setCellValue(areas.getAreaCreateTime());
						c4.setCellValue(areas.getAreaModifier());
						c5.setCellValue(areas.getAreaModifiedTime());
						c6.setCellValue(areas.getMasterModuleId());
						
						log.info("导出的值为:" + areas.getAreaId() + "," + areas.getAreaName() + "," + areas.getAreaCreater() + "," + areas.getAreaCreateTime() + "," + areas.getAreaModifier() + "," + areas.getAreaModifiedTime() + "," + areas.getMasterModuleId());
					}
				}
			}
			
		}
		
		try {
			FileOutputStream fos = new FileOutputStream(exportFile);
			workbook.write(fos);
			fos.flush();
			fos.close();
			
			File file = new File(exportFile);
			if (file.exists() && file.isFile()) {
				FileInputStream fis = new FileInputStream(file);
				URLEncoder.encode(file.getName(), "UTF-8");
				byte[] b = new byte[fis.available()];
				fis.read(b);
				
				response.setCharacterEncoding("UTF-8");
				response.setHeader("Content-Disposition", "attachment; filename=" + createExcelName + "");
				
				ServletOutputStream out = response.getOutputStream();
				out.write(b);
				out.flush();
				out.close();
				
				if (fis != null) {
					fis.close();
				}
				
				file.createNewFile();//在指定路径下建立文件
				
				message = "success";
			}
			
			return message;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return message;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return message;
		}
	}

spring-mvc.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

	<!-- 启动自动扫描 -->
	<!-- 后台管理 -->
	<context:component-scan base-package="com.*" />

	<!-- 注册MVC注解驱动 -->
	<mvc:annotation-driven>
		<!-- 指定http返回编码格式,不然返回ajax请求json会出现中文乱码 -->
		<mvc:message-converters>
			<bean class="org.springframework.http.converter.StringHttpMessageConverter">
				<property name="supportedMediaTypes">
					<list>
						<value>text/html;charset=UTF-8</value>
						<value>application/json;charset=UTF-8</value>
						<value>*/*;charset=UTF-8</value>
					</list>
				</property>
			</bean>
		</mvc:message-converters>
	</mvc:annotation-driven>

	<!-- 静态资源可访问的设置方式 -->
	<mvc:default-servlet-handler />

	<!-- 配置视图解析器,可以显式设置,也可以不设置,不设置会依据SpringMVC的默认设置 -->
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/" />
		<property name="suffix" value=".jsp" />
	</bean>
	<!-- 文件上传 -->
	<!-- 配置nultipartresolver,注意:id名必须这样写,不然会报错 -->
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="defaultEncoding" value="UTF-8"></property>
		<property name="maxInMemorySize" value="10240000"></property>
	</bean>
</beans>

 

  • 0
    点赞
  • 1
    评论
  • 0
    收藏
  • 打赏
    打赏
  • 扫一扫,分享海报

评论 1 您还未登录,请先 登录 后发表或查看评论
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页

打赏作者

Java小弟xu

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值