本文將介紹在Java Web中使用Apache POI實現管理系統中常見的導出Excel功能。
首先在pom.xml中導入poi的依賴包:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.6</version>
</dependency>
然後編寫工具類ExcelUtil.java,具體內容及解釋如下:
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class ExcelUtil {
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();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 創建一個居中格式
// 聲明列對象
HSSFCell cell = null;
// 創建標題
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;
}
}
最後直接在controller中使用即可,這裏筆者使用購房網站的信息作爲例子,在實現時需要根據業務的數據修改下面方法:
@RequestMapping(value = "/export")
@ResponseBody
public void export(HttpServletRequest request, HttpServletResponse response) throws Exception {
//獲取數據
Map<String, Object> data = requirementService.query(null);
List<Requirement> list = (List<Requirement>) data.get("requirements");
//excel標題
String[] title = {"id","姓名","手機號","城市","縣區","房源","地鐵線","地鐵站","售價","面積","房型","用途","權屬","樓層","朝向",
"樓齡","有無電梯","裝修","諮詢時間","備註"};
//excel文件名
String fileName = "購房需求信息表"+System.currentTimeMillis()+".xls";
//sheet名
String sheetName = "購房需求信息表";
String[][] content = new String[list.size()+1][title.length];
for (int i = 0; i < list.size(); i++) {
Requirement r = list.get(i);
System.out.println(r.toString());
content[i][0] = r.getId()+"";
content[i][1] = r.getUsername();
content[i][2] = r.getPhone();
content[i][3] = r.getCity();
content[i][4] = r.getDistrict();
content[i][5] = r.getVillage();
content[i][6] = r.getLineNum();
content[i][7] = r.getStationName();
content[i][8] = r.getPrice();
content[i][9] = r.getSquareMeter();
content[i][10] = r.getHouseKind();
content[i][11] = r.getUasge();
content[i][12] = r.getOwnerShip();
content[i][13] = r.getFloor();
content[i][14] = r.getDirection();
content[i][15] = r.getAge();
content[i][16] = r.getElevator();
content[i][17] = r.getDecoration();
content[i][18] = sdf.format(r.getDate());
content[i][19] = r.getRemark();
}
//創建HSSFWorkbook
HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
//響應到客戶端
try {
this.setResponseHeader(response, fileName);
OutputStream os = response.getOutputStream();
wb.write(os);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//發送響應流方法
public void setResponseHeader(HttpServletResponse response, String fileName) {
try {
try {
fileName = new String(fileName.getBytes(),"ISO8859-1");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.setContentType("application/octet-stream;charset=ISO8859-1");
response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
} catch (Exception ex) {
ex.printStackTrace();
}
}
部署Java Web後直接訪問就可以生成並下載Excel表格了。So easy !