一、概述
在工作过程中,都会遇到这样一个需求,就是将相关的数据列表导出成excel,这里写成通用的导出Excel的工具。
二、项目实现
1、构建pom.xml
我的工程是利用Maven来构建的,这里仅给出最核心的包
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.11-beta2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.11-beta2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.11-beta2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-excelant</artifactId>
<version>3.11-beta2</version>
</dependency>
<!--jxi导出-->
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12</version>
</dependency>
2、编写PoiUtils类
这个类是整个工具的核心,它实现了Excel文件的导出功能,具体代码如下:
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xssf.usermodel.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
/**
* @Auther: admin
* @Date: 2018/10/4 12:54
* @Description: 导出excel 2003和2007通用工具类
*/
public class ExcelUtils {
/**
* 2003 导出Excel
*
* @param fileName 文件名
* @param titles 导出excel标题
* @param data 需要显示的数据集合
* @param hashMapKeys 导出excel显示的列头(对应pojo里面的属性)
* @Description: 2003版本最大支持65536行
*/
public static void exportExcel2003(String fileName, String[] titles, String[] hashMapKeys,
List<Map> data, HttpServletResponse response) throws IOException{
// 1.创建工作簿
HSSFWorkbook workbook = new HSSFWorkbook();
// 2.在workbook中添加一个sheet,对应Excel文件中的fileName
HSSFSheet sheet = workbook.createSheet(fileName);
//样式1:定义列宽
// for (int i = 0; i < 12; i++) {
// sheet.setColumnWidth(i, 4000);
// }
//样式2:定义第一行单元格样式
HSSFCellStyle cellStyle = workbook.createCellStyle();
// 设置字体
HSSFFont font = workbook.createFont();
font.setFontName("微软雅黑");
font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
// 字体大小
font.setFontHeightInPoints((short) 12);
cellStyle.setFont(font);
//设置单元格居中
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
//样式3:定义标题栏单元格样式
HSSFCellStyle cellStyle1 = workbook.createCellStyle();
//设置字体,第一行
HSSFFont font1 = workbook.createFont();
// font1.setFontName("微软雅黑");
// font1.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
// // 字体大小
// font1.setFontHeightInPoints((short) 12);
// cellStyle1.setFont(font1);
//设置单元格居中
c