java统计报表,导出excel,自定义存储目录

2023-02-03 21:06:28

java统计报表,导出excle,自定义存储目录

做一个将查询出来的数据写入excel,并且点击导出按钮是,可以选择导出路径
**直接上完整代码

1.utils工具类,里面可以自己设置样式,详细看注释

import java.io.File;
import java.io.FileOutputStream;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ExcelUtil {
	/*sheet Name表名, titleName标题名, file Name文件名,
    columnNumber列号, columnWidth列宽, columnName列名
    *
    */
    public static ResponseEntity<byte[]> ExportNoResponse(String sheetName, String titleName,String fileName, int columnNumber, int[] columnWidth,String[] columnName, String[][] dataList, HttpServletRequest request,HttpServletResponse response) throws Exception {

        if (columnNumber == columnWidth.length && columnWidth.length == columnName.length) {
            // 第一步,创建一个webbook,对应一个Excel文件
            HSSFWorkbook wb = new HSSFWorkbook();
            // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
            HSSFSheet sheet = wb.createSheet(sheetName);
            // sheet.setDefaultColumnWidth(15); //统一设置列宽
            for (int i = 0; i < columnNumber; i++) {
                for (int j = 0; j <= i; j++) {
                    if (i == j) {
                        sheet.setColumnWidth(i, columnWidth[j] * 256); // 单独设置每列的宽
                    }
                }
            }
            // 创建第0行 也就是标题
            HSSFRow row1 = sheet.createRow((int) 0);
            row1.setHeightInPoints(20);// 设备标题的高度
            // 第三步创建标题的单元格样式style2以及字体样式headerFont1
            HSSFCellStyle style2 = wb.createCellStyle();
            style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            style2.setFillForegroundColor(HSSFColor.LIGHT_TURQUOISE.index);
            style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            HSSFFont headerFont1 = (HSSFFont) wb.createFont(); // 创建字体样式
            headerFont1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字体加粗
            headerFont1.setFontName("黑体"); // 设置字体类型
            headerFont1.setFontHeightInPoints((short) 15); // 设置字体大小
            style2.setFont(headerFont1); // 为标题样式设置字体样式

            HSSFCell cell1 = row1.createCell(0);// 创建标题第一列
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0,
                    columnNumber - 1)); // 合并第0到第17列
            cell1.setCellValue(titleName); // 设置值标题
            cell1.setCellStyle(style2); // 设置标题样式

            // 创建第1行 也就是表头
            HSSFRow row = sheet.createRow((int) 1);
            row.setHeightInPoints(37);// 设置表头高度

            // 第四步,创建表头单元格样式 以及表头的字体样式
            HSSFCellStyle style = wb.createCellStyle();
            style.setWrapText(true);// 设置自动换行
            style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 创建一个居中格式

            style.setBottomBorderColor(HSSFColor.BLACK.index);
            style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            style.setBorderRight(HSSFCellStyle.BORDER_THIN);
            style.setBorderTop(HSSFCellStyle.BORDER_THIN);

            HSSFFont headerFont = (HSSFFont) wb.createFont(); // 创建字体样式
            headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字体加粗
            headerFont.setFontName("黑体"); // 设置字体类型
            headerFont.setFontHeightInPoints((short) 10); // 设置字体大小
            style.setFont(headerFont); // 为标题样式设置字体样式

            // 第四.一步,创建表头的列
            for (int i = 0; i < columnNumber; i++) {
                HSSFCell cell = row.createCell(i);
                cell.setCellValue(columnName[i]);
                cell.setCellStyle(style);
            }

            String code = createID2();
            // 第五步,创建单元格,并设置值
            for (int i = 0; i < dataList.length; i++) {
                row = sheet.createRow((int) i + 2);
                // 为数据内容设置特点新单元格样式1 自动换行 上下居中
                HSSFCellStyle zidonghuanhang = wb.createCellStyle();
                zidonghuanhang.setWrapText(true);// 设置自动换行
                zidonghuanhang
                        .setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 创建一个居中格式

                // 设置边框
                zidonghuanhang.setBottomBorderColor(HSSFColor.BLACK.index);
                zidonghuanhang.setBorderBottom(HSSFCellStyle.BORDER_THIN);
                zidonghuanhang.setBorderLeft(HSSFCellStyle.BORDER_THIN);
                zidonghuanhang.setBorderRight(HSSFCellStyle.BORDER_THIN);
                zidonghuanhang.setBorderTop(HSSFCellStyle.BORDER_THIN);

                // 为数据内容设置特点新单元格样式2 自动换行 上下居中左右也居中
                HSSFCellStyle zidonghuanhang2 = wb.createCellStyle();
                zidonghuanhang2.setWrapText(true);// 设置自动换行
                zidonghuanhang2
                        .setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 创建一个上下居中格式
                zidonghuanhang2.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中

                // 设置边框
                zidonghuanhang2.setBottomBorderColor(HSSFColor.BLACK.index);
                zidonghuanhang2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
                zidonghuanhang2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
                zidonghuanhang2.setBorderRight(HSSFCellStyle.BORDER_THIN);
                zidonghuanhang2.setBorderTop(HSSFCellStyle.BORDER_THIN);
                HSSFCell datacell = null;
                for (int j = 0; j < columnNumber; j++) {
                    datacell = row.createCell(j);
                    datacell.setCellValue(dataList[i][j]);
                    datacell.setCellStyle(zidonghuanhang2);
                }
            }
            // 第六步,将文件存到指定位置
            try {

                String path =  request.getServletContext().getRealPath("/upload/" + "测试报表" +code+ ".xls");

                File file = new File(path);
                if(!file.exists()){
                    //先得到文件的上级目录,并创建上级目录,在创建文件
                    file.getParentFile().mkdir();
                    try {
                        //创建文件
                        file.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                FileOutputStream fout = new FileOutputStream(file);//  new FileOutputStream("\\upload\\" + "测试报表" +code+ ".xls");
                wb.write(fout);
                fout.close();



                String fileName1 = "测试报表" +code+ ".xls";
                //fileName1 = fileName1.substring(1, fileName1.length());
                String dfileName = new String(fileName1.getBytes("gb2312"), "iso8859-1");
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                headers.setContentDispositionFormData("attachment", dfileName);

                String str = "导出" + "测试报表" + "成功!";
                System.out.println(str);
                //HttpStatus.OK兼容ie
                return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                        headers, HttpStatus.OK);
//					fout.close();
            } catch (Exception e) {
                e.printStackTrace();
                String str1 = "导出" + "测试报表" + "失败!";
                System.out.println(str1);
            }

        } else {
            System.out.println("失败,Game over");
        }
        return null;
    }
    
	public static String createID2(){
			      
		        //将Date类型转成String类型
		        Date now=new Date();
		        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		        String dateStr=dateFormat.format(now);
		        
		        byte[] lock = new byte[0];
				// 位数,默认是8位
				final long w = 100000000;
				
				long r = 0;
				synchronized (lock) {
					r = (long) ((Math.random() + 1) * w);
				}
		        
				return dateStr+String.valueOf(r).substring(1);
		       
		}
}

3.请求方法

@RequestMapping(value = "/toFile")
    public ResponseEntity<byte[]> uploadFile(
                                             HttpServletRequest request,
                                             HttpServletResponse response) throws Exception {
        
        List<IsOrRe> list = isOrReService.slectByParam();

        String sheetName = "测试统计表单";
        String titleName =  "清城测试订单报表";
        String fileName = "测试报表XXX";
        //columnWidth columnName 长度等于columnNumber
        int columnNumber = 8;
        int[] columnWidth = {6, 12,10, 15, 15, 12, 10,, 15};
        String[] columnName = {"序号", "XX公司", "产品名称", "方案XX", "订单号", "XX号", "XX1", "XX2"};
        //将List转换为二维数组String[][]
        String[][] ss = new String[list.size()][columnNumber];
        for (int i = 0; i < list.size(); i++) {
            ss[i] = new String[]{String.valueOf(i+1),list.get(i).getInCony(),
                    list.get(i).getPrName(), list.get(i).getPlName(),
                    list.get(i).getOrNo(), list.get(i).getPoNo(),
                    list.get(i).getAppName(),list.get(i).getAppMobile() };
        }
        ResponseEntity<byte[]> res = ExportNoResponse(sheetName, titleName, fileName,
                columnNumber, columnWidth, columnName, ss, request, response);
        return res;
    }

浏览器点击导出按钮导出效果:这就可以选择导出路径了
在这里插入图片描述

xls内容样式
在这里插入图片描述

  • 作者:Mr.qingcheng
  • 原文链接:https://blog.csdn.net/weixin_49462255/article/details/109463405
    更新时间:2023-02-03 21:06:28