`
hq185fvl
  • 浏览: 5779 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

导出Excel乱码问题(少于2条出现乱码解决方案)

阅读更多
导出Excel格式的文件在网上已经有很多了解决方案了,先前都是用报表工具(jasperreport)来弄的,后来打算用opi,jxl,同事说那样子写代码会写很多,所以就用html代码来些,说是可以自动转换。
    以下为转换的具体方法:
    StringBuilder sb = new StringBuilder(2000);
   
     sb.append("<html>");
			sb.append("<head><meta http-equiv=Content-Type content='text/html; charset=utf-8'></head><body>");//这个必须设置,不然只有1条记录的时候,导出会出现乱码
			sb.append("<table width='800' border='1' cellpadding='0' cellspacing='0' bordercolor='#000000'>");
			sb.append("<caption>");
			sb.append("<span  style='font-size: medium;font-weight: bold;'>交接班日志列表</span>");
			sb.append("</caption>");
			sb.append("<tr>");
			sb.append("<th width='149' bgcolor='#CCCCFF'>日期</th>");
			sb.append("<th width='132' bgcolor='#CCCCFF'>当班时间</th>");
			sb.append("<th width='126' bgcolor='#CCCCFF'>值班人</th>");
			sb.append("<th width='112' bgcolor='#CCCCFF'>班组</th>");
			sb.append("<th width='93' bgcolor='#CCCCFF'>班次</th>");
			sb.append("<th width='148' bgcolor='#CCCCFF'>开始值班时间</th>");
			sb.append("</tr>");
			if (runOnwatchList != null) {
				listSize = runOnwatchList.size();
				// 循环取出数据填充表格
				for (int i = 0; i < listSize; i++) {
					sb.append("<tr>");
					RunOnwatch runOnwatch = runOnwatchList.get(i);
					String[] data = new String[6];
					data[0] = DateUtil.format(runOnwatch.getOnwatchdate());
					data[1] = runOnwatch.getRunOnwatchorder().getStarttime()
							+ "-"
							+ runOnwatch.getRunOnwatchorder().getEndtime();
					data[2] = runOnwatch.getOnwatchby();
					data[3] = runOnwatch.getGroupname();
					data[4] = runOnwatch.getGrouporder();
					data[5] = DateUtil.format(runOnwatch.getStartwatchtime(),
							DateUtil.YMDHMS);
					for (int j = 0; j < 6; j++) {
						sb.append("<td align='left'>");
						sb.append(data[j]);
						sb.append("</td>");
					}
					sb.append("</tr>");
				}
			}
			sb.append("</table>");
			sb.append("</body></html>");

    
;
   以下为编码格式:
String fileName = java.net.URLEncoder.encode("交接班日志列表.xls",
						"UTF-8");//这个必须设置,不然导出另存为的时候,文件名会出现乱码(支持中文的)
				res.setHeader("Content-Type", "application/force-download");
				res.setHeader("Content-Type",
						"application/vnd.ms-excel;charset='UTF-8'");
				res.setHeader("Content-Disposition", "attachment;filename="
						+ fileName);
				res.setCharacterEncoding("UTF-8");//这个必须设置
				PrintWriter pw = res.getWriter();
				System.out.print("excelData=="+excelData);
				pw.write(excelData);
				pw.flush();
				pw.close();

1
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics