/**
* 调用导出工具类,设置表头,设置表格内容
*
*/
public void export( HttpServletResponse response) {
List<List<String>> returnList = new ArrayList<>();
//设置表头
List<String> rowList = new ArrayList<>();
rowList.add("序号");
rowList.add("名字");
rowList.add("性别");
returnList.add(rowList);
//设置表格内容
for (int i = 0; i < 10; i++) {
List<String> newRowList = new ArrayList<>();
newRowList.add(i + 1 + "");//序号
newRowList.add("xxx");//名字
newRowList.add("23");//性别
returnList.add(newRowList);
}
//导出标记信息
try {
exportExcel(response, "导出名称excel的文件名", returnList);
} catch (Exception e) {
log.error("导出时发生错误", e);
}
}
/**
* 导出excel
*
* @param response
* @param title
* @param dataList
* @throws Exception
*/
public static void exportExcel(HttpServletResponse response, String title, List<List<String>> dataList) throws Exception {
//获取一个HSSFWorkbook对象
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFCellStyle style = getHSSFCellStyle(workbook);
//创建一个sheet
HSSFSheet sheet = workbook.createSheet("Sheet1");
//表头
HSSFRow row = sheet.createRow(0);
//数据
for (int i = 0; i < dataList.size(); i++) {
row = sheet.createRow(i);
for (int j = 0; j < dataList.get(i).size(); j++) {
if (dataList.get(i).get(j) != null && dataList.get(i).get(j).length() > 0 && dataList.get(i).get(j).trim().length() > 0) {
HSSFCell cell = row.createCell(j);
HSSFCellStyle cellStyle = workbook.createCellStyle();
HSSFFont font = workbook.createFont();
if (i == 0) {
// 加粗
font.setBold(true);
font.setFontHeightInPoints((short) 13);
cellStyle.setFont(font);
sheet.setColumnWidth(j, 5000);
}
cellStyle.setWrapText(true);
cell.setCellStyle(cellStyle);
cell.setCellValue(dataList.get(i).get(j));
}
}
}
OutputStream outputStream = response.getOutputStream();
//设置页面不缓存
response.reset();
String filename = title + ".xls";
//设置返回文件名的编码格式
response.setCharacterEncoding("utf-8");
filename = URLEncoder.encode(filename, "utf-8");
response.setHeader("Content-disposition", "attachment;filename=" + filename);
response.setContentType("application/vnd.ms-excel");
workbook.write(outputStream);
outputStream.close();
}
/**
* 创建一个style
*
* @param workbook
* @return
*/
private static HSSFCellStyle getHSSFCellStyle(HSSFWorkbook workbook) {
HSSFCellStyle cellStyle = workbook.createCellStyle();
//居中
cellStyle.setAlignment(CENTER);
return cellStyle;
}
java导出excel表格
最新推荐文章于 2023-05-04 14:40:44 发布