前一篇关于excel导出的文章,在本机上测试是没有什么问题的,但是应用程序布置在linux服务器上时会出现乱码问题,所以又找了一个关于excel导出的程序,具体步骤如下:
1.配置文件:
<action name="exportUserExcel" class="userAction" method="exportUserExcel">
<result name="input">/WEB-INF/pages/admin/listUser.jsp
</result>
</action>
2.导出函数
/**
* 导出所有用户的列表
*
* @return
* @throws Exception
*/
public String exportUserExcel() throws Exception {
HttpServletResponse response = ServletActionContext.getResponse();
// 定义request ,response.
// 查询下载附件.
// 设置下载头信息.begin
response.setCharacterEncoding("UTF-8");
response.setContentType("file");
response.setHeader("Content-Disposition", "attachment; filename="
+ new String("用户通讯录.xls".getBytes("GB2312"), "iso8859-1"));
// 这个地方一定要进行编码的转换要不然中文字符会出现乱码.
// 设置下载头信息.end,
OutputStream output = null;
InputStream fis = null;
try {
output = response.getOutputStream();
jxl.write.WritableWorkbook wwb = Workbook.createWorkbook(output);
jxl.write.WritableSheet ws = wwb.createSheet("用户通讯录", 0);
// 设置标题.ws.addCell(new jxl.write.Label(列, 行, 内容.));
ws.addCell(new Label(0, 1, "编号"));
ws.addCell(new Label(1, 1, "登录名称"));
ws.addCell(new Label(2, 1, "联系人"));
ws.addCell(new Label(3, 1, "电话"));
ws.addCell(new Label(4, 1, "email"));
ws.addCell(new Label(5, 1, "单位名称"));
ws.addCell(new Label(6, 1, "单位邮编"));
ws.addCell(new Label(7, 1, "单位地址"));
// 设置显示长度.
ws.setColumnView(1, 15);
// 登录名长度
ws.setColumnView(2, 15);
ws.setColumnView(3, 15);
ws.setColumnView(4, 20);
ws.setColumnView(5, 20);
ws.setColumnView(6, 20);
ws.setColumnView(7, 20);
ws.setColumnView(8, 40);
int i = 1;
List list1 = mobjUserService.findAllUser();
for (int j = 0; j < list1.size(); j++) {
User user = (User) list1.get(j);
ws.addCell(new jxl.write.Number(0, i + 1, i));
// 这里设置是自增的序号而不是ID号.也可以改成ID号.
// ws.addCell(new jxl.write.Label(1, i + 1, ""
// + user.getUserId()));
ws.addCell(new Label(1, i + 1, "" + user.getLoginName()));
// 登录名
ws.addCell(new Label(2, i + 1, "" + user.getContactPerson()));
// 联系人
ws.addCell(new Label(3, i + 1, "" + user.getPhone()));
// 联系电话.
ws.addCell(new Label(4, i + 1, "" + user.getEmail()));
// email.
if (null != user.getRecommendCompany()) {
ws.addCell(new Label(5, i + 1, ""
+ user.getRecommendCompany().getCompanyName()));
if (user.getRecommendCompany().getCompanyZipcode() != null) {
ws.addCell(new Label(6, i + 1, ""
+ user.getRecommendCompany()
.getCompanyZipcode()));
} else {
ws.addCell(new Label(6, i + 1, ""));
// 增加邮编为""的判断.因为这个是Integer的类型.
}
ws.addCell(new Label(7, i + 1, ""
+ user.getRecommendCompany().getCompanyAddress()));
} else {
ws.addCell(new Label(5, i + 1, ""));
ws.addCell(new Label(6, i + 1, ""));
ws.addCell(new Label(7, i + 1, ""));
}
i++;
}
wwb.write();
wwb.close();
} catch (Exception e) {
System.out.println("Error!");
e.printStackTrace();
} finally {// 正常关闭输入输出流.
try {
if (fis != null) {
fis.close();
fis = null;
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (output != null) {
output.close();
output = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
3.页面上的只要有提交执行该方法就行了