使用java进行导出Excel功能
内部功能实现方法
导出Excel操作
1、在 pom文件中导入 POI jar包
<dependencies>
<!-- excel 批量的导入导出 -->
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependencies>
2、Jsp中的导出方法
function doexcel() {
var filename = window.prompt("请输入Excel文件名称","文档");
window.location.href="<%=basePath %>/cus/doExcel?excelName="+filename;
}
3、后台接收参数并实现功能
//Excel的导出操作 需要工具包的支持 – 前提:在查询的时候将数据放在了session中
@RequestMapping("doExcel")
public String doExcel(HttpSession session,String excelName) {
/*
获取数据 – 进行了强转 --
值存放到session中之后被转化为Object?
经过源码的查看 可以确定就是Object
*/
List<Customer> list = (List<Customer>)session.getAttribute("customerInfo");
//标题
String[] title = {"id","comname","companyperson","comaddress","comphone","camera","present","remark","addtime"};
//Excel 文件名称
String fileName = System.currentTimeMillis() + excelName+".xls";
//sheet名 表格名称
String sheetName = "客户信息表";
//设置二维数组 -- list.size() 数据的条数 -- title.length 由标题确定数据的列数
String[][] content = new String[list.size()][title.length];
//开始进行添加数据
for (int i = 0; i <list.size(); i++) {
Customer customer = list.get(i);
content[i][0] = customer.getId().toString();
content[i][1] = customer.getComname();
content[i][2] = customer.getCompanyperson();
content[i][3] = customer.getComaddress();
content[i][4] = customer.getComphone();
content[i][5] = customer.getCamera();
content[i][6] = customer.getPresent();
content[i][7] = customer.getRemark();
content[i][8] = customer.getAddtime().toString();
}
//创建HSSWorkbook
HSSFWorkbook workbook = ExcelUtil.getHSSWorkbook(sheetName,title,content,null);
//响应客户端
try {
//创建存放Excel表格的位置
File file = new File("F:\\Excel\\" + fileName);
FileOutputStream fos = new FileOutputStream(file);
workbook.write(fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
//将session清空
session.removeAttribute("customerInfo");
return "customer";
}