- 导入依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
- 工具类
public class ExcelUtil {
/**
* 导出Excel
* @param sheetName sheet名称
* @param title 标题
* @param values 内容
* @param wb HSSFWorkbook对象
*/
public static HSSFWorkbook getHSSFWorkbook(String sheetName, String []title, String [][]values, HSSFWorkbook wb){
// 第一步,创建一个HSSFWorkbook,对应一个Excel文件
if(wb == null){
wb = new HSSFWorkbook();
}
// 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet
HSSFSheet sheet = wb.createSheet(sheetName);
// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
HSSFRow row = sheet.createRow(0);
// 第四步,创建单元格,并设置值表头 设置表头居中
HSSFCellStyle style = wb.createCellStyle();
//声明列对象
HSSFCell cell;
//创建标题
for(int i=0;i<title.length;i++){
cell = row.createCell(i);
cell.setCellValue(title[i]);
cell.setCellStyle(style);
}
//创建内容
for(int i=0;i<values.length;i++){
row = sheet.createRow(i + 1);
for(int j=0;j<values[i].length;j++){
//将内容按顺序赋给对应的列对象
row.createCell(j).setCellValue(values[i][j]);
}
}
return wb;
}
}
- 调用工具类
/**
* /exportFile/export
* @param params
* @param request
* @param response
*/
@RequestMapping("exportHSSFWorkbook")
public void exportHSSFWorkbook(Map<String, Object> params, HttpServletRequest request, HttpServletResponse response){
try {
//文件名称,客户端传来的参数,防止中文文件名乱码参数编码因此这里需要解码
// String title = URLDecoder.decode(request.getParameter("title"),"UTF-8");
String title = "村民表";
String[] columnHeader = new String[] {"姓名","年龄","地址"};
// 获取list
String[][] list = new String[][]{
{"刘大海","54","桃李村1号"},
{"王大富","34","桃李村4号"},
{"王婆婆","82","桃李村6号"},
{"李复","24","桃李村9号"},
{"陈月","14","桃李村3号"},
{"老村长","74","桃李村3号"}
};
// 导出 Excel
HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(title, columnHeader, list, null);
OutputStream output=response.getOutputStream();
response.reset();
response.setHeader( "Content-disposition" , "attachment; filename= "+new String(title.getBytes("GB2312"), "8859_1")+".xls" );
response.setContentType( "application/msexcel" );
wb.write(output);
output.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
- 前端调用
<button onclick="exportHSSFWorkbook()">导出</button>
function exportHSSFWorkbook(){
window.location.href ="http://localhost:9000/exportFile/exportHSSFWorkbook"
}
备注:表格数据参数使用二维数组,可以根据需求调整为list<T>