- POI操作excel的教程:http://poi.apache.org/
- excel分为两种格式:HSSF,XSSF / SXSSF,如果在一个程序中想要操作两种格式的,需要导入以下依赖包
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-excelant</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-examples</artifactId>
<version>3.16</version>
</dependency>
- 在POI包中有如下几个主要对象和excel的几个对象对应:
HSSFWorkbook Excel 工作簿workbook
HSSFSheet Excel 工作表 sheet
HSSFRow Excel 行
HSSFCell Excel 单元格 - 导出excel
利用异步交换传输数据
function exportExcel() {
$.ajax({
type:"GET",
url:"${pageContext.request.contextPath}/cust/exportExcel",
success:function(msg){
if(msg.code==200){
alert(msg.message);
}
}
})
}
后端:
//导出excel
@RequestMapping(value = "/exportExcel",method = RequestMethod.GET)
@ResponseBody
public Map<String,Object> exportExcel(){
Workbook wb=new HSSFWorkbook();
//创建sheet对象
Sheet sheet1 = wb.createSheet("customers");
//第一行为标题行
Row row=sheet1.createRow(0);
//第一行有5列
Cell[] cell=new HSSFCell[5];
for(int i=0;i<5;i++){
cell[i]=row.createCell(i);
}
cell[0].setCellValue("ID");
cell[1].setCellValue("联系人");
cell[2].setCellValue("公司名称");
cell[3].setCellValue("添加时间");
cell[4].setCellValue("联系电话");
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
List<Customer> customerList = customerService.getCustomerList();
for (int i = 0; i <customerList.size() ; i++) {
Customer customer=customerList.get(i);
Row row1 = sheet1.createRow(i + 1);
Cell[] cell1=new HSSFCell[5];
for(int j=0;j<5;j++){
cell[j]=row1.createCell(j);
}
cell1[0].setCellValue(customer.getId());
cell1[1].setCellValue(customer.getCompanyperson());
cell1[2].setCellValue(customer.getComname());
//时间转成字符串
Date addtime = customer.getAddtime();
String s = sdf.format(addtime);
cell1[3].setCellValue(s);
cell1[4].setCellValue(customer.getComphone());
}
FileOutputStream fos=null;
try {
fos=new FileOutputStream(new File("d:\\Desktop\\customers.xls"));
wb.write(fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}finally {
if (fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Map<String,Object> map=new HashMap<String, Object>();
map.put("code",200);
map.put("message","下载成功");
return map;
}