java生成excel表格

1.需求

将从数据库查询出来的数据,以报表生成到本地

2实现

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.hssf.util.HSSFColor;
import org.springframework.stereotype.Service;

import com.jf.cloud.model.common.PoiReportExcel;
import com.jf.cloud.service.intf.common.ExportService;
@SuppressWarnings("deprecation")
@Service
public class ExportServiceImpl implements ExportService {

    // 报表导出 导出成功返回地址,否则返回null
    @Override
    public String generateExcel(String sheetName, String titleName,
            int[] columnWidth, String fileName, String[] columnName,
            List<List<String>> dataList) {

        if (columnWidth.length != columnName.length) {

            return "列数和表头数不相等";
        }

        // 创建一个webbook,对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();

        // 在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet(sheetName);

        // 设定列数
        int columnNumber = columnWidth.length;

        // 设置每一列的宽度
        for (int i = 0; i < columnWidth.length; i++) {

            for (int j = 0; j <= i; j++) {

                if (i == j) {

                    sheet.setColumnWidth(i, columnWidth[j] * 256); // 单独设置每列的宽
                }
            }
        }

        // 设置标题
        HSSFRow row1 = sheet.createRow(0);

        // 设置标题的高度
        row1.setHeightInPoints(50);

        // 创建标题单元格样式以及字体样式
        HSSFCellStyle style = wb.createCellStyle();

        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        style.setFillForegroundColor(HSSFColor.LIGHT_TURQUOISE.index);

        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

        // 创建字体样式
        HSSFFont headerFont1 = (HSSFFont) wb.createFont();

        // 字体加粗
        headerFont1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

        // 设置字体类型
        headerFont1.setFontName("黑体");

        // 设置字体大小
        headerFont1.setFontHeightInPoints((short) 15);

        // 为标题样式设置字体样式
        style.setFont(headerFont1);

        // 创建第一列
        HSSFCell cell1 = row1.createCell(0);

        // 合并所有列并居中
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, columnNumber - 1));

        // 设置值标题
        cell1.setCellValue(titleName);

        // 设置标题样式
        cell1.setCellStyle(style);

        // 设置表头
        HSSFRow row = sheet.createRow(1);

        // 设置表头高度
        row.setHeightInPoints(37);

        // 创建表头单元格样式 以及表头的字体样式
        HSSFCellStyle style1 = wb.createCellStyle();

        // 设置自动换行
        style1.setWrapText(true);

        style1.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        // 居中格式
        style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        style1.setBottomBorderColor(HSSFColor.BLACK.index);

        style1.setBorderBottom(HSSFCellStyle.BORDER_THIN);

        style1.setBorderLeft(HSSFCellStyle.BORDER_THIN);

        style1.setBorderRight(HSSFCellStyle.BORDER_THIN);

        style1.setBorderTop(HSSFCellStyle.BORDER_THIN);

        // 创建字体样式
        HSSFFont headerFont = (HSSFFont) wb.createFont();

        // 字体加粗
        headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

        // 设置字体类型
        headerFont.setFontName("黑体");

        // 设置字体大小
        headerFont.setFontHeightInPoints((short) 10);

        // 为标题样式设置字体样式
        style1.setFont(headerFont);

        // 创建表头的列
        for (int i = 0; i < columnNumber; i++) {
            HSSFCell cell = row.createCell(i);

            cell.setCellValue(columnName[i]);

            cell.setCellStyle(style1);
        }

        // 创建单元格,并设置值 `

        for (int i = 0; i < dataList.size(); i++) {

            // 创建行
            row = sheet.createRow(i + 2);

            // 设置为自动换行并居中
            HSSFCellStyle lineBreak = wb.createCellStyle();

            // 设置自动换行
            lineBreak.setWrapText(true);

            // 创建一个居中格式
            lineBreak.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

            // 设置边框
            lineBreak.setBottomBorderColor(HSSFColor.BLACK.index);

            lineBreak.setBorderBottom(HSSFCellStyle.BORDER_THIN);

            lineBreak.setBorderLeft(HSSFCellStyle.BORDER_THIN);

            lineBreak.setBorderRight(HSSFCellStyle.BORDER_THIN);

            lineBreak.setBorderTop(HSSFCellStyle.BORDER_THIN);

            HSSFCellStyle lineBreak2 = wb.createCellStyle();

            lineBreak2.setWrapText(true);// 设置自动换行
            lineBreak2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 创建一个上下居中格式
            lineBreak2.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中

            // 设置边框
            lineBreak2.setBottomBorderColor(HSSFColor.BLACK.index);

            lineBreak2.setBorderBottom(HSSFCellStyle.BORDER_THIN);

            lineBreak2.setBorderLeft(HSSFCellStyle.BORDER_THIN);

            lineBreak2.setBorderRight(HSSFCellStyle.BORDER_THIN);

            lineBreak2.setBorderTop(HSSFCellStyle.BORDER_THIN);

            HSSFCell datacell = null;

            for (int j = 0; j < columnNumber; j++) {

                datacell = row.createCell(j);

                datacell.setCellValue(dataList.get(i).get(j));

                datacell.setCellStyle(lineBreak2);
            }

        }

        // 文件夹路径
        String fileth1 = "E://ExcelReport/" ;
        
        //子文件夹名称
        String fileth2 =new Date().getTime()+"/";

        // 获取文件夹
        File file = new File(fileth1+fileth2+fileName+".xls");
        
        //获取上级文件夹
        File parentFile = file.getParentFile();
        
        if (!parentFile.exists() && !parentFile.isDirectory()) {
            
            parentFile.mkdirs();
        }
        
        
        FileOutputStream fout = null;
        
        try {
            
            fout = new FileOutputStream(file);

            wb.write(fout);

        } catch (Exception e) {
            
            return null;

        } finally {

            try {
                
                fout.close();
                
            } catch (IOException e) {
                
                return null ;
            }

        }
        return  输出地址 + fileth2+fileName;

    }

}

3调用

//数据格式化
                    List<List<String>> dataResource = new ArrayList<List<String>>();
           

                     //dataResource 加些数据
                    
                    String sheetName = "报表";
                    String[] headers = {  "学院", "课程数", "评分" };
                    String fileName = "学院报表";
                    int[] columnWidth = { 10, 10, 10 };
                    String result = exprot.generateExcel(sheetName, fileName, columnWidth,
                            fileName, headers, dataResource);
                    ResultData resultData = new ResultData();

                    if (StringUtils.isBlank(result)) {

                        resultData.setMessage("导出失败");
                    } else {

                        resultData.setMessage("导出成功");

                        resultData.setData(result);
                    }

 4结果

在我指定的位置生成了excel

代码简单,样式也丑,喜欢的可以自己去调

猜你喜欢

转载自blog.csdn.net/zzqtty/article/details/82589257
今日推荐