java导出功能(多个sheet页数据导出)
JavaWeb-封装工具类
前言
大概内容:
自定义格式的标题,及对应的数据,每个sheet页的表头及数据都可以不同,具体根据实际业务去变更,可以仿照这个例子去编写,这里提供的是最基础的多sheet页导出,如果需要多行表头复杂业务的多sheet页导出可参考我另一篇
复杂表头,多行表头导出
,如果导出不确定行数列数跟随业务的增长而变动的导出参考另一篇
不确定行数列数数据的工具类
2023.3.29补充
上面两个链接老是失效,在我主页搜索对应的名称就能找到
提示:以下是导出到本地,工具类也有导出到浏览器的封装方法,可直接使用
提示:以下是导出到本地,工具类也有导出到浏览器的封装方法,可直接使用
提示:以下是导出到本地,工具类也有导出到浏览器的封装方法,可直接使用
一、实现的效果
本篇测试数据为两个sheet页的导出功能,测试中导出到本地,工具类有导出到浏览器的封装方法,可直接使用
二、调用工具类
业务层调用
//假设这是需要导出的数据
public static void main(String[] args) {
/** 第一页数据 */
List<String[]> dataAllOne = new ArrayList<>();
String[] data1 = (String[]) Arrays.asList("杨1", "18", "男").toArray();
String[] data2 = (String[]) Arrays.asList("杨2", "19", "女").toArray();
dataAllOne.add(data1);
dataAllOne.add(data2);
/** 第二页数据 */
List<String[]> dataAllTwo = new ArrayList<>();
String[] data3 = (String[]) Arrays.asList("驾照", "2022年9月5日10:08:46", "是").toArray();
String[] data4 = (String[]) Arrays.asList("户口本", "2022-9-5 10:09:01", "否").toArray();
dataAllTwo.add(data3);
dataAllTwo.add(data4);
ArrayList<ExcelExp> list = new ArrayList<>();
ExcelExp excelExp1 = new ExcelExp("存放人员信息", (String[]) Arrays.asList("姓名", "年龄", "性别").toArray(), dataAllOne, "人员信息");
ExcelExp excelExp2 = new ExcelExp("存放文件信息", (String[]) Arrays.asList("文件名称", "上传时间", "是否上传到FDFS").toArray(), dataAllTwo, "文件上传情况");
list.add(excelExp1);
list.add(excelExp2);
Workbook workbook = ExcelExportUtil.exportManySheetExcel(list);
//导出数据到excel
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream("F:/新建文件夹/demo.xls");
workbook.write(fileOutputStream);
fileOutputStream.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fileOutputStream != null){
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
三、详细工具类
直接copy改吧改吧就可以使用,有详细注释
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* @Description: java导出功能(多个sheet页数据导出)
*
* @Author: 杨永卓
* @Date: 2022/9/5 10:31
*/
public final class ExcelExportUtil {
private ExcelExportUtil (){}
private static ExcelExportUtil excelExportUtil = null;
static{
/** 类加载时创建,只会创建一个对象 */
if(excelExportUtil == null) excelExportUtil = new ExcelExportUtil ();
}
/**
* @param @param file 导出文件路径
* @param @param mysheets
* @return void
* @throws
* @Title: exportManySheetExcel
* @Description: 可生成单个、多个sheet
*/
public static Workbook exportManySheetExcel(List<ExcelExp> mysheets) {
HSSFWorkbook wb = new HSSFWorkbook();// 创建工作薄
List<ExcelExp> sheets = mysheets;
// 表头样式
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式
// 字体样式
HSSFFont fontStyle = wb.createFont();
fontStyle.setFontName("微软雅黑");
fontStyle.setFontHeightInPoints((short) 12);
// fontStyle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
style.setFont(fontStyle);
for (ExcelExp excel : sheets) {
// 新建一个sheet
HSSFSheet sheet = wb.createSheet(excel.getFileName());// 获取该sheet名称
String[] handers = excel.getHanders();// 获取sheet的标题名
HSSFRow tableName = sheet.createRow(0);
HSSFCell cellName = tableName.createCell(0);
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 9));
HSSFCellStyle titleStyle = wb.createCellStyle();
// 设置单元格样式
HSSFFont titleFont = wb.createFont(); // 标题字体
titleFont.setFontHeightInPoints((short) 16); // 字号
titleStyle.setFont(titleFont);
titleStyle.setAlignment(HorizontalAlignment.CENTER);
cellName.setCellStyle(titleStyle);
// 设置单元格内容
cellName.setCellValue(excel.getTableName());
HSSFRow rowFirst = sheet.createRow(1);// 第一个sheet的第一行为标题
// 写标题
for (int i = 0; i < handers.length; i++) {
// 获取第一行的每个单元格
HSSFCell cell = rowFirst.createCell(i);
// 往单元格里写数据
cell.setCellValue(handers[i]);
cell.setCellStyle(style); // 加样式
sheet.setColumnWidth(i, 4000); // 设置每列的列宽
}
// 写数据集
List<String[]> dataset = excel.getDataset();
for (int i = 0; i < dataset.size(); i++) {
String[] data = dataset.get(i);// 获取该对象
// 创建数据行
HSSFRow row = sheet.createRow(i + 2);
for (int j = 0; j < data.length; j++) {
// 设置对应单元格的值
row.createCell(j).setCellValue(data[j]);
}
}
}
return wb;
}
/**
* @Description: [方法1:导出到浏览器]
* @Param: [fileName, wb, response]
* @return: void
* @Author: yangyongzhuo
* @Date: 2022/7/25 9:40
*/
private static void buildExcelDocument(String fileName, Workbook wb, HttpServletResponse response) {
try {
response.setContentType("application/octet-stream");
// 可自行定义编码格式
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
// 清除jsp编译html文件的空白,防止excel出现空行
response.flushBuffer();
// 写出
wb.write(response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(wb);
}
}
/**
* @Description: [方法2:导出到浏览器]
* @Param: [fileName, wb, response,request]
* @return: void
* @Author: yangyongzhuo
* @Date: 2022/7/25 9:40
*/
public static void outputXls(Workbook workbook, String fileName, HttpServletResponse response,
HttpServletRequest request) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
workbook.write(os);
byte[] content = os.toByteArray();
InputStream is = new ByteArrayInputStream(content);
// 设置response参数,可以打开下载页面
response.reset();
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition",
"attachment;filename=" + encodeFileName(fileName + ".xls", request));
ServletOutputStream out = response.getOutputStream();
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(is);
bos = new BufferedOutputStream(out);
byte[] buff = new byte[2048];
int bytesRead;
// Simple read/write loop.
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
public static String encodeFileName(String fileName, HttpServletRequest request)
throws UnsupportedEncodingException {
String agent = request.getHeader("USER-AGENT");
if (null != agent && -1 != agent.indexOf("MSIE")) {
return URLEncoder.encode(fileName, "UTF-8");
} else if (null != agent && -1 != agent.indexOf("Mozilla")) {
return "=?UTF-8?B?"
+ (new String(org.apache.commons.codec.binary.Base64.encodeBase64(fileName.getBytes("UTF-8")))) + "?=";
} else {
return fileName;
}
}
/**
* 把list<map>封装成list<String[]> 由于我的结果集是List<Map<String,Object>>,所以我写了这个个方法,把它转换成List<String[]>
*
* @param list 要封装的list
* @param strKey String[]的长度
* @return
*/
public static List<String[]> listUtils(List<Map<String, Object>> list, String[] strKey) {
if (list != null && list.size() > 0) {// 如果list有值
List<String[]> strList = new ArrayList<String[]>();// 实例化一个list<string[]>
for (Map<String, Object> map : list) {// 遍历数组
String[] str = new String[strKey.length];// 实力一个string[]
Integer count = 0;// 作为str的下标,每次从0开始
for (String s : strKey) {// 遍历map中的key
if (map.get(s) != null) {
str[count] = map.get(s).toString();
} else {
str[count] = "";
}
// 把map的value赋值到str数组中
count++;// str的下标+1
}
if (str != null) {// 如果str有值,添加到strList
strList.add(str);
}
}
if (strList != null && strList.size() > 0) {// 如果strList有值,返回strList
return strList;
}
}
return null;
}
/**
* @Description: 导出对象
*
* @Author: 杨永卓
* @Date: 2022/9/5 10:34
*/
private static class ExcelExp {
private String fileName;// sheet的名称
private String[] handers;// sheet里的标题
private List<String[]> dataset;// sheet里的数据集
private String tableName;
public ExcelExp(String fileName, String[] handers, List<String[]> dataset, String tableName) {
this.fileName = fileName;
this.handers = handers;
this.dataset = dataset;
this.tableName = tableName;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String[] getHanders() {
return handers;
}
public void setHanders(String[] handers) {
this.handers = handers;
}
public List<String[]> getDataset() {
return dataset;
}
public void setDataset(List<String[]> dataset) {
this.dataset = dataset;
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
}
}
仰天大笑出门去,我辈岂是蓬蒿人
版权声明:本文为weixin_48207312原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。