参考博客:https://blog.csdn.net/chichuhanga/article/details/82223009
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.6</version>
</dependency>
HSSF(用于操作Excel的组件)提供给用户使用的对象在rg.apache.poi.hssf.usermodel包中,主要部分包括Excel对象,样式和格式,有以下几种常用的对象:
常用组件:
组件名 | 说明 |
---|---|
HSSFWorkbook | excel的文档对象 |
HSSFSheet | excel的表单 |
HSSFRow | excel的行 |
HSSFCell | excel的格子单元 |
HSSFFont | excel字体 |
HSSFCellStyle | cell样式 |
首先,我们应该要知道的是,一个Excel文件对应一个workbook,一个workbook中有多个sheet组成,一个sheet是由多个行(row)和列(cell)组成。那么我们用poi要导出一个Excel表格的正确顺序应该是:
1、用HSSFWorkbook打开或者创建“Excel文件对象”
2、用HSSFWorkbook对象返回或者创建Sheet对象
3、用Sheet对象返回行对象,用行对象得到Cell对象
4、对Cell对象读写。
5、将生成的HSSFWorkbook放入HttpServletResponse中响应到前端页面
这个工具类可以直接拿过去用。。。
package com.util;
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 {
/**
* 导出Excel
* @param sheetName sheet名称
* @param title 标题
* @param values 内容,可以修改为list 或者 map
* @param wb HSSFWorkbook对象
* @return
*/
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;
}
}
步骤:
1、查得数据
2、将数据转换成String [][] 二维数组(具体情况根据自身需求定)
3、设置excel标题
4、设置excel文件名
5、设置sheet名
6、调用工具类 ExcelUtil
7、输出流响应到前端
8、done
package com.controller;
import com.alibaba.fastjson.JSONObject;
import com.pojo.FlowInfoDay;
import com.service.FlowInfoDayService;
import com.util.ExcelUtil;
import com.util.LogMessage;
import com.util.ToPercentage;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.junit.Test;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @Auther: renxin.tang
* @Date: 2019/3/23 0024 22:07
* @Description:
*/
@Controller
@RequestMapping("/flow")
public class FlowInfoDayController {
@Resource
private FlowInfoDayService flowInfoDayService;
/**
* 下载指定月份的报表数据
* @param request
* @param response
* @return
* @throws ParseException
*/
@RequestMapping(value="/download",produces = "text/plain;charset=utf-8")
@ResponseBody
public String download (HttpServletRequest request, HttpServletResponse response) {
String year = request.getParameter("year");
String month = request.getParameter("month");
// 查到数据
List<FlowInfoDay> list = flowInfoDayService.findmonth(year,month);
sendExcel(list,response);
return "done";
}
public void sendExcel(List<FlowInfoDay> list, HttpServletResponse response){
DecimalFormat df = new DecimalFormat("#.00");
//excel标题
String[] title = {"编号","日期","当日UV","当日PV","人均PV","跳出率","注册量","用户UV","用户UV占比"};
//excel文件名
String fileName = "RX技术论坛流量分析"+System.currentTimeMillis()+".xls";
//sheet名
String sheetName = "RX技术论坛流量分析";
// 将数据转换成String [][] 二维数组(具体情况根据自身需求定)
String [][] content = new String[list.size()][title.length];
int id=1;
int i=0;
for (FlowInfoDay f: list) {
content[i][0] = String.valueOf(id);
content[i][1] = String.valueOf(f.getLogdate());
content[i][2] = String.valueOf((int) f.getdUv());
content[i][3] = String.valueOf(f.getPv());
content[i][4] = String.valueOf(df.format(f.getPerPv()));
content[i][5] = String.valueOf(ToPercentage.toPercentage(f.getLossRate()));
content[i][6] = String.valueOf(f.getRegister());
content[i][7] = String.valueOf(f.getuUv());
content[i][8] = String.valueOf(ToPercentage.toPercentage(f.getuUvPro()));
id++;
i++;
}
//创建HSSFWorkbook
HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
//响应到客户端
this.setResponseHeader(response, fileName);
OutputStream os = null;
try {
os = response.getOutputStream();
wb.write(os);
os.flush();
os.close();
} catch (IOException 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();
}
}
}
1、用HSSFWorkbook打开“Excel文件对象”
2、用HSSFWorkbook创建Sheet对象
3、用Sheet对象返回行对象,用行对象得到Cell对象
4、对Cell对象读写。
@Test
public void importExcel() throws Exception {
//1、用HSSFWorkbook打开“Excel文件对象”
HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream("g:/test.xls"));
//2、用HSSFWorkbook创建Sheet对象
HSSFSheet sheet = wb.getSheetAt(0);
//sheet.getLastRowNum() 行数
for(int j=0;j<sheet.getLastRowNum()+1;j++) {
//3、用Sheet对象返回行对象
HSSFRow row = sheet.getRow(j);
//row.getLastCellNum() 列数
for(int i=0; i<row.getLastCellNum(); i++) {
//3、用行对象得到Cell对象
HSSFCell cell = row.getCell(i);
//4、对Cell对象读写。
System.out.print(cell.getRichStringCellValue() +"\t");
}
System.out.println("");
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190324194005248.jpg