当前位置: 首页 > news >正文

poi 的导入导出 报表

1、使用hutool poi 工具

https://www.hutool.cn/docs/#/poi/Excel%E5%B7%A5%E5%85%B7-ExcelUtil excel 工具类官网、

导入依赖:

<dependency>
  <groupId>cn.hutool</groupId>
  <artifactId>hutool-all</artifactId> 
</dependency>

使用步骤:

// 打开hutool poi excel工具
ExcelWriter writer = ExcelUtil.getWriter(true);
// 将所有的数据写出
writer.write(payOrderEntities,true);
// 设置excel文件浏览器的格式
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;chartset=utf-8");
// 设置文件响应头的名字
response.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode("党员费用支付表","UTF-8") + ".xlsx");

实例:
@RestController
@RequestMapping("/phhrm/pay")
public class ExcelExpotController {
    @Autowired
    PhPayOrderService phPayOrderService;
    @GetMapping("/export")
    @RequiresPermissions("phhrm:pay:list")
    public void ExcelExport(@RequestBody(required = false) String username,
                            @RequestBody(required = false) String paymentStatus,
                            @RequestBody(required = false) String noticeTime,
                            HttpServletResponse response) throws IOException {
//        打开hutool poi excel工具
        ExcelWriter writer = ExcelUtil.getWriter(true);
//        全部导出数据
        List<PhPayOrderEntity> payOrderEntities = new ArrayList<>();
//        判断是否是条件查询的导出
        if (StringUtils.isBlank(username)&&StringUtils.isBlank(paymentStatus)&&StringUtils.isBlank(noticeTime)){
            payOrderEntities = phPayOrderService.list();
        }
//        将所有的数据写出
        writer.write(payOrderEntities,true);
//        设置excel文件的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;chartset=utf-8");
        response.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode("党员费用支付表","UTF-8") + ".xlsx");
        ServletOutputStream outputStream = response.getOutputStream();
//        将当前的数据以流的新式传到前端
        writer.flush(outputStream,true);
//        关闭流
        writer.close();
        outputStream.flush();
        outputStream.close();

    }    

将导出的文件的表格头换位中文

在实体表的字段使用、
    @Alice("") 注解

public class PhPayFeeUserDto {
    /**
     * 缴费id
     */
    @Alias("序号")
    private BigInteger id;
}

#Apach POI 实现Excel 模板

依赖

<!-- Apache POI -->
<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi</artifactId>
  <version>5.2.3</version>
</dependency>

<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-ooxml</artifactId>
  <version>5.2.3</version> <!-- 版本号根据实际情况调整 -->
</dependency>

简单使用过程;

// 使用模板 HSSF 文件后缀为xls  Xssf 文件后缀为xlsx
XSSFWorkbook workbook = new XSSFWorkbook();
HSSFWorkbook workbook = new HSSFWorkbook();
//生成一个sheet页
Sheet sheet1 = workbook.crestSheet("sheet1");
Row titleRow = sheet.createRow(0);//括号填充行号
Cell cell = titleRow.createCell(i);//括号填充单元格
cell.setCellValue(heads[i]); 括号填充单元格内容

添加循环使用过程;

XSSFWorkbook workbook = new XSSFWorkbook();
HSSFWorkbook workbook = new HSSFWorkbook();

样式添加;

创建样式

CellStyle Style = workbook.createCellStyle();

合并单元格

 //   合并单元格并设置样式样式--指定那几个单元格
        CellRangeAddress mergedRegion = new CellRangeAddress(firstRow, endRow, firstCol, endCol);
        sheet.addMergedRegion(mergedRegion);

自定义浅灰色(RGB值)


// 自定义浅灰色(RGB值)
    byte[] rgb = {(byte) 230, (byte) 230, (byte) 230}; // 浅灰色
    XSSFColor lightGrayColor = new XSSFColor(rgb, null);
//设置颜色
    Style.setFillForegroundColor(lightGrayColor); // 浅灰色
    Style.setFillPattern(FillPatternType.SOLID_FOREGROUND);

设置字体

Font titleFont = workbook.createFont();
titleFont.setBold(true);           // 加粗
titleFont.setFontHeightInPoints((short) 10); // 字号
Style.setFont(titleFont);

设置位置

Style.setAlignment(HorizontalAlignment.CENTER);//水平居中
Style.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中

设置边框

style.setBorderTop(BorderStyle.THIN);//设置单元格的上边框为细线。
style.setBorderBottom(BorderStyle.THIN);//设置单元格的下边框为细线。
style.setBorderLeft(BorderStyle.THIN);//设置单元格的左边框为细线。
style.setBorderRight(BorderStyle.THIN);//设置单元格的右边框为细线。

使用样式

//在创建的单元格下使用
cell0.setCellStyle(style);

数据校验;

创建检验:

//XSSF需要验证工具
// 创建数据验证辅助工具
DataValidationHelper validationHelper = new XSSFDataValidationHelper((XSSFSheet) sheet);
// 校验的生效范围(哪个单元格)
CellRangeAddressList Range = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
//验证内容
DataValidationConstraint Constraint = validationHelper.createNumericConstraint(
                DataValidationConstraint.ValidationType.INTEGER,
                DataValidationConstraint.OperatorType.BETWEEN,
                "-100000", "999999999" // 限制数字编号为-100000到999999999的整数
);
//绑定验证值
XSSFDataValidation Validation =  validationHelper.createValidation(Constraint, numberRange);
//处理Excel兼容性问题
if(Validation instanceof XSSFDataValidation) {
   Validation.setSuppressDropDownArrow(true);
    Validation.setShowErrorBox(true);
}else {
    Validation.setSuppressDropDownArrow(false);
}
//单元格输入错误盒子。
Validation.createErrorBox("输入错误", "员工编号必须是数字!");
// 显示错误提示
Validation.setShowErrorBox(true); 
//获得焦点(鼠标点击),弹窗的文本
Validation.createPromptBox("提示", "员工编号必须是数字");
//开启盒子
Validation.setShowPromptBox(true);
//HSSF 不需要验证工具

使用校验股则

//对存在的单元格生效
sheet.addValidationData(Validation

对单元格上锁–保护表;

CellStyle unlockStyle = workbook.createCellStyle();
//打开所锁
unlockStyle.setlouck(true)
//关闭锁
unlockStyle.setlouck(true)
//打开sheet 保护生效
sheet.protectSheet("密码");
//使用
在单元格下使用--设置样式
cell.setCellStyle(unlockStyle);

基本的命令使用;

创建 excel

        // 创建新的工作簿
        Workbook workbook = new XSSFWorkbook();
        // 创建一个工作表
        Sheet sheet = workbook.createSheet("Sheet1");

        // 创建行和单元格
        Row row = sheet.createRow(0);
        Cell cell = row.createCell(0);
        cell.setCellValue("Hello, POI!");

        // 写入文件
        try (FileOutputStream fileOut = new FileOutputStream("example.xlsx")) {
            workbook.write(fileOut);
            System.out.println("Excel 文件已创建!");
        }

        // 关闭工作簿
        workbook.close();

读取 Excel 文件

  // 打开 Excel 文件
        try (FileInputStream file = new FileInputStream("example.xlsx")) {
            Workbook workbook = new XSSFWorkbook(file);
            Sheet sheet = workbook.getSheetAt(0);

            // 遍历行和单元格
            for (Row row : sheet) {
                for (Cell cell : row) {
                    // 根据单元格类型获取值
                    switch (cell.getCellType()) {
                        case STRING:
                            System.out.print(cell.getStringCellValue() + "\t");
                            break;
                        case NUMERIC:
                            System.out.print(cell.getNumericCellValue() + "\t");
                            break;
                        case BOOLEAN:
                            System.out.print(cell.getBooleanCellValue() + "\t");
                            break;
                        default:
                            System.out.print("UNKNOWN\t");
                    }
                }
                System.out.println();
            }

            // 关闭工作簿
            workbook.close();

设置样式

  Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");

        // 创建单元格并设置值
        Row row = sheet.createRow(0);
        Cell cell = row.createCell(0);
        cell.setCellValue("Styled Cell");

        // 创建样式
        CellStyle style = workbook.createCellStyle();
        style.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        // 设置字体
        Font font = workbook.createFont();
        font.setBold(true);
        font.setColor(IndexedColors.RED.getIndex());
        style.setFont(font);

        // 应用样式
        cell.setCellStyle(style);

        // 写入文件
        try (FileOutputStream fileOut = new FileOutputStream("styled_example.xlsx")) {
            workbook.write(fileOut);
            System.out.println("带样式的 Excel 文件已创建!");
        }

        workbook.close();
设置样式
  Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");

        // 创建单元格并设置值
        Row row = sheet.createRow(0);
        Cell cell = row.createCell(0);
        cell.setCellValue("Styled Cell");

        // 创建样式
        CellStyle style = workbook.createCellStyle();
        style.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        // 设置字体
        Font font = workbook.createFont();
        font.setBold(true);
        font.setColor(IndexedColors.RED.getIndex());
        style.setFont(font);

        // 应用样式
        cell.setCellStyle(style);

        // 写入文件
        try (FileOutputStream fileOut = new FileOutputStream("styled_example.xlsx")) {
            workbook.write(fileOut);
            System.out.println("带样式的 Excel 文件已创建!");
        }

        workbook.close();

创建 Word

//  HWPF(用于操作 Word 97-2003 格式的 .doc)和 XWPF(用于操作 Word 2007+ 格式的 .docx)两种 API。
        XWPFDocument document = new XWPFDocument();

        // 创建段落并设置文本
        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun run = paragraph.createRun();
        run.setText("Hello, POI!");

        // 写入文件
        try (FileOutputStream out = new FileOutputStream("example.docx")) {
            document.write(out);
            System.out.println("Word 文件已创建!");
        }

        document.close();

读取 Word

  // 打开 Word 文档
        try (FileInputStream file = new FileInputStream("example.docx")) {
            XWPFDocument document = new XWPFDocument(file);

            // 提取文档内容
            XWPFWordExtractor extractor = new XWPFWordExtractor(document);
            System.out.println("文档内容:");
            System.out.println(extractor.getText());

            extractor.close();
            document.close();

设置word 样式

 // 创建段落并设置文本
        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun run = paragraph.createRun();
        run.setText("Styled Text");

        // 设置样式
        run.setBold(true);
        run.setColor("FF0000"); // 红色
        run.setFontSize(16);

        // 写入文件
        try (FileOutputStream out = new FileOutputStream("styled_example.docx")) {
            document.write(out);
            System.out.println("带样式的 Word 文件已创建!");
        }

        document.close();

创建 Word

//  HWPF(用于操作 Word 97-2003 格式的 .doc)和 XWPF(用于操作 Word 2007+ 格式的 .docx)两种 API。
        XWPFDocument document = new XWPFDocument();

        // 创建段落并设置文本
        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun run = paragraph.createRun();
        run.setText("Hello, POI!");

        // 写入文件
        try (FileOutputStream out = new FileOutputStream("example.docx")) {
            document.write(out);
            System.out.println("Word 文件已创建!");
        }

        document.close();

相关文章:

  • 聊聊istio服务网格
  • leetcode_位运算 191.位1的个数
  • 网络安全知识:网络安全网格架构
  • List的基本功能(1)
  • Java List 自定义对象排序 Java 8 及以上版本使用 Stream API
  • 服务器释放screen资源(Detached状态并不会释放资源)
  • C++ 设计模式 - 策略模式
  • 【SQL实验】触发器
  • 矩阵-矩阵置零
  • 并查集算法篇上期:并查集原理及实现
  • FreeSWITCH Alpine 安装
  • 【股票数据API接口35】如何获取股票当天分价成交占比数据之Python、Java等多种主流语言实例代码演示通过股票数据接口获取数据
  • 亚马逊的API服务怎么使用?
  • 力扣每日一题【算法学习day.131】
  • 【Erdas实验教程】009:非监督分类及分类后评价
  • TypeScript - 属性修饰符
  • Python 单例模式笔记
  • RFID测温技术:电力设备安全监测的新利器
  • 深入解析Textual库:打造现代化的终端用户界面(TUI)
  • 【Python爬虫(37)】解锁分布式爬虫:原理与架构全解析
  • 网站做外链/惠东seo公司
  • 找网络公司做网站/百度手机助手app下载
  • 网站怎么做才被收录快/国家再就业免费培训网
  • 网站简介如何做的有创意/西安百度首页优化
  • 南宁有什么做网站的好公司/泉州百度开户
  • 小企业网站免费建设/山东关键词优化联系电话