1. 首先添加pom依赖
org.apache.poi
poi
3.15
org.apache.poi
poi-ooxml
3.15
2. 贴代码
/**
* 导出到Excel表格,本地或者网络均可,取决于提供什么样的输出流
*
* @param title 表格标题名
* @param dataset 需要显示的数据集合,链表元素为数组,该数组代表一行数据
* @param out 与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
* @throws Exception 自定义异常
*/
public void exportExcel(String title, List> dataset, OutputStream out) throws IOException {
// 声明一个工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
// 生成一个表格
HSSFSheet sheet = workbook.createSheet(title);
// 设置表格默认列宽度为15个字节
sheet.setDefaultColumnWidth(15);
// 生成一个样式
HSSFCellStyle style = workbook.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 生成一个字体
HSSFFont font = workbook.createFont();
font.setColor(HSSFColor.BLACK.index);
font.setFontHeightInPoints((short) 10);
font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
//生成一个文本格式
HSSFDataFormat format = workbook.createDataFormat();
// 把字体应用到当前的样式
style.setFont(font);
style.setDataFormat(format.getFormat("@"));
HSSFRow row = null;
//循环取出dataSet的数据填入表格
for (int iRow = 0; iRow < dataset.size(); iRow++) {
row = sheet.createRow(iRow);
int colls = dataset.get(iRow).size();
for (int jColl = 0; jColl < colls; jColl++) {
HSSFCell cell = row.createCell(jColl);
cell.setCellStyle(style);
String textValue = dataset.get(iRow).get(jColl);
if (textValue != null) {
cell.setCellValue(textValue);
}
}
}
//写入操作,到输出流out
try {
workbook.write(out);
} catch (IOException ex) {
// 用Exception而不是IOException的目的是?
throw ex;
}
}
3. 调用方法
//设置response并获得网络输出流
response.reset();
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
String fileName ="文件名.xls";
String header = request.getHeader("User-Agent").toUpperCase();
if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
fileName = URLEncoder.encode(fileName, "utf-8");
fileName = fileName.replace("+", "%20"); //IE下载文件名空格变+号问题
} else {
fileName = new String(fileName.getBytes(), "ISO8859-1");
}
//response.setHeader("Content-Disposition", "attachment;filename=" + fileName );
response.setHeader("Content-disposition", "attachment; filename=\"" + fileName + "\"");
ServletOutputStream servletout = response.getOutputStream();
exportExcel("测试", lists, servletout);