SSM框架使用poi导入导出Excel的详细方法

yizhihongxing

下面我将为您提供关于“SSM框架使用poi导入导出Excel的详细方法”的完整攻略:

一、依赖导入

首先,在Maven中添加对poi、poi-ooxml和poi-ooxml-schemas等依赖的导入。具体代码如下:

<dependency>
   <groupId>org.apache.poi</groupId>
   <artifactId>poi</artifactId>
   <version>4.1.0</version>
</dependency>
<dependency>
   <groupId>org.apache.poi</groupId>
   <artifactId>poi-ooxml</artifactId>
   <version>4.1.0</version>
</dependency>
<dependency>
   <groupId>org.apache.poi</groupId>
   <artifactId>poi-ooxml-schemas</artifactId>
   <version>4.1.0</version>
</dependency>

二、读取Excel内容

假设有一个学生信息Excel表,我们需要读取这个Excel表格中的内容,并将数据导入到数据库中。首先定义一个学生信息模型:

public class Student {
    private String name;
    private String sex;
    private int age;
    // 省略get和set方法
}

然后,定义一个工具类ExcelUtil,用于读取Excel文件,并将文件中的数据转换为Java对象:

public class ExcelUtil {

    public static List<Student> readExcel(String filePath) throws IOException {
        FileInputStream fis = null;
        Workbook workbook = null;
        try {
            fis = new FileInputStream(filePath);
            workbook = WorkbookFactory.create(fis);
            Sheet sheet = workbook.getSheetAt(0);
            List<Student> studentList = new ArrayList<>();
            for (Row row : sheet) {
                if (row.getRowNum() == 0) {
                    continue;
                }
                Student student = new Student();
                student.setName(row.getCell(0).getStringCellValue());
                student.setSex(row.getCell(1).getStringCellValue());
                student.setAge((int) row.getCell(2).getNumericCellValue());
                studentList.add(student);
            }
            return studentList;
        } finally {
            if (workbook != null) {
                workbook.close();
            }
            if (fis != null) {
                fis.close();
            }
        }
    }
}

调用ExcelUtil.readExcel(filePath)方法即可读取Excel文件并返回学生信息列表。

三、导出Excel

下面以学生信息为例,演示如何将学生信息导出为Excel文件。同样的,先定义一个工具类ExcelUtil用于处理Excel文件。在ExcelUtil中,我们实现了将学生信息导出为Excel表格的方法writeExcel()。

public class ExcelUtil {

    public static void writeExcel(List<Student> studentList, String filePath) throws IOException {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet();
        Row rowHeader = sheet.createRow(0);
        rowHeader.createCell(0).setCellValue("姓名");
        rowHeader.createCell(1).setCellValue("性别");
        rowHeader.createCell(2).setCellValue("年龄");

        for (int i = 0; i < studentList.size(); i++) {
            Student student = studentList.get(i);
            Row row = sheet.createRow(i + 1);
            row.createCell(0).setCellValue(student.getName());
            row.createCell(1).setCellValue(student.getSex());
            row.createCell(2).setCellValue(student.getAge());
        }

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(filePath);
            workbook.write(fos);
        } finally {
            if (workbook != null) {
                workbook.close();
            }
            if (fos != null) {
                fos.close();
            }
        }
    }
}

调用ExcelUtil.writeExcel(studentList, filePath)方法即可将studentList中的信息导出为Excel文件,并保存到filePath中。

四、示例

示例1:将Excel表格中的学生信息导入到数据库中

假设我们已经通过ExcelUtil.readExcel(filePath)方法读取了学生信息Excel表格,并将其保存为List studentList。我们可以通过如下代码将studentList中的学生信息批量插入到数据库中:

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public void importStudent(List<Student> studentList) {
        studentMapper.batchInsert(studentList);
    }
}

示例2:将学生信息导出为Excel文件

@Controller
public class ExportController {

    @Autowired
    private StudentService studentService;

    @RequestMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        List<Student> studentList = studentService.getStudentList();
        ExcelUtil.writeExcel(studentList, "student.xlsx");
        File file = new File("student.xlsx");
        response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        FileInputStream fis = null;
        OutputStream os = null;
        try {
            fis = new FileInputStream(file);
            os = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
        } finally {
            if (fis != null) {
                fis.close();
            }
            if (os != null) {
                os.close();
            }
        }
    }
}

在这个示例中,我们首先通过studentService.getStudentList()方法获取学生信息列表,然后调用ExcelUtil.writeExcel(studentList, "student.xlsx")方法将列表导出为Excel文件,并将文件输出到response的输出流中,这样就实现了导出Excel文件的功能。

希望以上内容能对您有所帮助。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:SSM框架使用poi导入导出Excel的详细方法 - Python技术站

(0)
上一篇 2023年5月20日
下一篇 2023年5月20日

相关文章

  • IDEA实现 springmvc的简单注册登录功能的示例代码

    以下是“IDEA实现 springmvc的简单注册登录功能的示例代码”的完整攻略: 创建 Maven Web 项目 首先,在 IDEA 中创建一个 Maven Web 项目,选择 Spring MVC。 配置 pom.xml 文件 在 pom.xml 文件中添加 Spring 相关的依赖,包括 spring-webmvc、spring-orm、spring-…

    Java 2023年5月16日
    00
  • SpringBoot中支持Https协议的实现

    SpringBoot是一个非常流行的Java开发框架,支持各种协议,如Http、Https等。本篇攻略将详细讲解SpringBoot中支持Https协议的实现方法。 准备工作 在SpringBoot中支持Https协议,需要准备三个文件: SSL证书文件(如:keystore.jks或server.crt) SSL证书密码(如:123456) 修改appli…

    Java 2023年5月20日
    00
  • 简单了解Spring Boot及idea整合jsp过程解析

    下面我来详细讲解一下“简单了解SpringBoot及idea整合jsp过程解析”的完整攻略。 什么是SpringBoot? SpringBoot 是一个基于 Spring 框架的全新框架,旨在简化 Spring 应用程序的创建和开发过程,它采用约定大于配置的原则,自动配置 Spring 和第三方库,提供了一组默认的 Starter 依赖项,可以快速搭建起基于…

    Java 2023年5月15日
    00
  • SpringBoot定制化Starter实现方法

    让我详细讲解SpringBoot定制化Starter实现方法的完整攻略。 什么是 SpringBoot Starter SpringBoot Starter 是一个提供很多开箱即用功能的集成包(或者说是依赖包)。通常情况下,我们只需要引入这个 Starter,配置一下参数即可,相关的依赖和配置都已经自动完成了。 SpringBoot Starter 的作用 …

    Java 2023年5月19日
    00
  • java如何完成输出语句实例详解

    下面是Java如何完成输出语句的攻略: 1. 输出语句的基本格式 Java中的输出语句使用System.out.print()和System.out.println(),其中print()可以输出字符串,并且不换行,println()则会在输出后换行。 下面是输出字符串的基本格式: System.out.print("Hello World&quo…

    Java 2023年5月23日
    00
  • Maven 项目用Assembly打包可执行jar包的方法

    下面是详细的“Maven 项目用 Assembly 打包可执行 jar 包的方法”的攻略: 一、前提条件 已安装 Maven 并配置环境变量 已经有一个 Maven 项目 二、添加 Assembly 插件到 Maven 项目中 在项目的 pom.xml 文件中添加以下插件配置: <build> <plugins> <plugin…

    Java 2023年6月2日
    00
  • Java中的异常处理如何提高程序可读性?

    Java中的异常处理可以提高程序的可读性和可维护性,让程序更加健壮。下面是具体的攻略: 为什么需要异常处理 在Java编程中,我们常常会遇到各种错误和异常的情况,例如空指针、数组越界、文件不存在等等。这些错误和异常都需要被处理,否则就会导致程序崩溃。而异常处理就是为了保证程序在遇到异常时能够正确地响应和处理,从而保证程序的健壮性和可靠性。 异常处理的语法 J…

    Java 2023年4月27日
    00
  • idea2020.3测试评价及感受

    IDEA 2020.3测试评价及感受 概述 IntelliJ IDEA 2020.3是一款集成开发环境,旨在提供给Java、Kotlin等开发者使用。本文将深入探讨该版本的测试评价及感受。 安装及配置 在官方网站(https://www.jetbrains.com/idea/)下载.idea2020.3版本软件,然后按照提示进行安装。如若使用社区版则无需激活…

    Java 2023年5月26日
    00
合作推广
合作推广
分享本页
返回顶部