在实际的项目开发中,很多地方都会用到一个功能,那就是数据的导出,而在数据导出时,大部分都是借用的框架,今天我给大家演示的就是基于SSM框架的数据导出功能。
POI介绍:
POI是 Apache 软件基金会用Java编写的免费开源的跨平台的 Java API,Apache POI 提供API给Java 程序对Microsoft Office格式档案读和写的功能。POI为“Poor Obfuscation Implementation”的首字母缩写,意为“简洁版的模糊实现”,我们一般用此工具来来操作Excel文件。
代码实现:
- 首先在基于maven工程的pom.xml中添加两个依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.2</version>
</dependency>
- 然后新建一个类WriteExcel.java,此类主要定义导出Excel的格式,以及创建Excel格式的输出流
package cn.ppdxzz.poi;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* Description:通用Excel输入流
*
* @Date: 2020/2/16 15:17
* @Author: PeiChen
*/
public class WriteExcel {
//导出表的列名
private String[] rowName;
//每行作为一个Object对象
private List<Object[]> dataList = new ArrayList<Object[]>();
//构造方法,传入要导出的数据:第一个参数传入一个列名数组,第二个参数传入一个list集合(Object对象数组)
public WriteExcel(String[] rowName,List<Object[]> dataList){
this.dataList = dataList;
this.rowName = rowName;
}
/*
* 导出数据
* */
public InputStream export() throws Exception{
HSSFWorkbook workbook = new HSSFWorkbook(); // 创建工作簿对象
HSSFSheet sheet = workbook.createSheet("sheet1"); // 创建工作表
// 设置sheet表样式
HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);//获取列头样式对象
HSSFCellStyle style = this.getColumnStyle(workbook); //单元格样式对象
// 定义所需列数
int columnNum = rowName.length;
HSSFRow rowRowName = sheet.createRow(0); // 在索引2的位置创建行(最顶端的行开始的第二行)
// 将列头设置到sheet的单元格中
for(int n=0;n<columnNum;n++){
HSSFCell cellRowName = rowRowName.createCell(n); //创建列头对应个数的单元格
cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); //设置列头单元格的数据类型
HSSFRichTextString text = new HSSFRichTextString(rowName[n]);
cellRowName.setCellValue(text); //设置列头单元格的值
cellRowName.setCellStyle(columnTopStyle); //设置列头单元格样式
}
//将查询出的数据设置到sheet对应的单元格中
for(int i=0;i<dataList.size();i++){
Object[] obj = dataList.get(i); //遍历每个对象
HSSFRow row = sheet.createRow(i+1); //创建所需的行数
for(int j=0; j<obj.length; j++){
HSSFCell cell = null; //设置单元格的数据类型
cell = row.createCell(j,HSSFCell.CELL_TYPE_STRING);
if(!"".equals(obj[j]) && obj[j] != null){
cell.setCellValue(obj[j].toString()); //设置单元格的值
}
cell.setCellStyle(style); //设置单元格样式
}
}
//让列宽随着导出的列长自动适应
for (int colNum = 0; colNum < columnNum; colNum++) {
int columnWidth = sheet.getColumnWidth(colNum) / 256;
for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
HSSFRow currentRow;
//如若当前行未被使用过,则新建一行
if (sheet.getRow(rowNum) == null) {
currentRow = sheet.createRow(rowNum);
} else {
currentRow = sheet.getRow(rowNum);
}
if (currentRow.getCell(colNum) != null) {
HSSFCell currentCell = currentRow.getCell(colNum);
if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
int length = currentCell.getStringCellValue().getBytes().length;
if (columnWidth < length) {
columnWidth = length;
}
}
}
}
if(colNum == 0){
sheet.setColumnWidth(colNum, (columnWidth-2) * 256);
}else{
sheet.setColumnWidth(colNum, (columnWidth+4) * 256);
}
}
String fileName = "Excel-" + String.valueOf(System.currentTimeMillis()).substring(4, 13) + ".xls";
String headStr = "attachment; filename=\"" + fileName + "\"";
ByteArrayOutputStream os=new ByteArrayOutputStream();
try {
workbook.write(os);
} catch (IOException e) {
e.printStackTrace();
}
byte[] content=os.toByteArray();
InputStream is=new ByteArrayInputStream(content);
return is;
}
/*
* 列头单元格样式
*/
public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {
// 设置字体
HSSFFont font = workbook.createFont();
//设置字体大小
font.setFontHeightInPoints((short)11);
//字体加粗
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//设置字体名字
font.setFontName("Courier New");
//设置样式;
HSSFCellStyle style = workbook.createCellStyle();
//设置底边框;
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
//设置底边框颜色;
style.setBottomBorderColor(HSSFColor.BLACK.index);
//设置左边框;
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
//设置左边框颜色;
style.setLeftBorderColor(HSSFColor.BLACK.index);
//设置右边框;
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
//设置右边框颜色;
style.setRightBorderColor(HSSFColor.BLACK.index);
//设置顶边框;
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
//设置顶边框颜色;
style.setTopBorderColor(HSSFColor.BLACK.index);
//在样式用应用设置的字体;
style.setFont(font);
//设置自动换行;
style.setWrapText(false);
//设置水平对齐的样式为居中对齐;
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
return style;
}
/*
* 列信息单元格样式
*/
public HSSFCellStyle getColumnStyle(HSSFWorkbook workbook) {
// 设置字体
HSSFFont font = workbook.createFont();
//设置字体名字
font.setFontName("Courier New");
//设置样式;
HSSFCellStyle style = workbook.createCellStyle();
//设置底边框;
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
//设置底边框颜色;
style.setBottomBorderColor(HSSFColor.BLACK.index);
//设置左边框;
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
//设置左边框颜色;
style.setLeftBorderColor(HSSFColor.BLACK.index);
//设置右边框;
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
//设置右边框颜色;
style.setRightBorderColor(HSSFColor.BLACK.index);
//设置顶边框;
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
//设置顶边框颜色;
style.setTopBorderColor(HSSFColor.BLACK.index);
//在样式用应用设置的字体;
style.setFont(font);
//设置自动换行;
style.setWrapText(false);
//设置水平对齐的样式为居中对齐;
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
return style;
}
}
- 接下来就是底层数据库访问层查询需要导出信息的一个类中的方法了,新建一个类VisitorDao.java,在类中添加查询所有信息的方法(该示例仅供参考,实际应用根据个人情况进行编写)。
@Select("select * from visitors order by begin_date desc")
List<Visitor> findAll() throws Exception;
- 下面是业务层的代码,新建一个接口VisitorService.java,创建该方法,返回一个输入流。
InputStream getInputStream() throws Exception;
- 下面是业务实现的具体代码,首先新建一个实现类VisitorServiceImpl.java,然后让它去实现业务层接口,重写getInputStream()方法。
/**
* 导出访客记录
* @return
* @throws Exception
*/
@Override
public InputStream getInputStream() throws Exception {
//Excel中的每列列名,依次对应数据库的字段
String[] title = new String[]{"ID","姓名","学号","联系方式","访问地址","来访时间","离开时间","来访原因"};
List<Visitor> visitors = visitorDao.findAll();//查询所有需要导出信息的数据
List<Object[]> datalist = new ArrayList<>();
for (int i = 0; i < visitors.size(); i++) {
Object[] obj = new Object[8];
obj[0] = visitors.get(i).getId();
obj[1] = visitors.get(i).getName();
obj[2] = visitors.get(i).getSno();
obj[3] = visitors.get(i).getPhone();
obj[4] = visitors.get(i).getPlace();
obj[5] = visitors.get(i).getBegin_date();
obj[6] = visitors.get(i).getEnd_date();
obj[7] = visitors.get(i).getVisit_result();
datalist.add(obj);
}
WriteExcel excel = new WriteExcel(title,datalist);
return excel.export();
}
- 最后就是表现层的代码,新建一个类VisitorController.java,创建该方法,具体使用比较简单,前台访问该方法即可。
/**
* 导出访客信息
* @param response
* @throws Exception
*/
@RequestMapping("/visitorInfo")
public void export(HttpServletResponse response) throws Exception {
InputStream is = visitorService.getInputStream();
response.setContentType("application/vnd.ms-excel");
response.setHeader("contentDisposition","attachment;filename=visitorInfo.xls");
ServletOutputStream outputStream = response.getOutputStream();
IOUtils.copy(is,outputStream);
}