Java实现将数据库数据导入到excel表格中

1.简易spring boot项目创建

controller层 service层 mapper层 pojo层创建 

数据库表一张

pom文件添加两个依赖

        <!--使用POI读取文件-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>

2.编写pojo层

我用的lombok插件(使用方法很简单,哪里都有讲解)

@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class StudentInformation implements Serializable {

    private Long id;
    private String name;
    private  Integer age;
}

3.编写mapper层

@Mapper
public interface StudentMapper {

    @Select("select * from student_information")
    List<StudentInformation> selectList();

}

4.编写service层

package com.st.service.impl;

import com.st.mapper.StudentMapper;
import com.st.pojo.StudentInformation;
import com.st.service.StudentService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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



@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;


    public String createExcel() {
        //第一步创建workbook
        HSSFWorkbook workbook = new HSSFWorkbook();

        //第二步创建sheet TODO 不知道这个的作用
        HSSFSheet sheet = workbook.createSheet("基本信息栏");//相当于定义一个白板吧,excel表的左下方就是一个sheet 一个excel可以有多个sheet

        //第三步创建行,添加表头0行
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2));
        HSSFRow row = sheet.createRow(0);


        //设置格式(水平垂直都居中)
        HSSFCellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);;//水平居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中

        HSSFCell cell1 = row.createCell(0);
        cell1.setCellValue("学生信息表");
        cell1.setCellStyle(style);

        HSSFRow row1 = sheet.createRow(1);

        //第四步创建单元格
        HSSFCell cell = row1.createCell(0);
        cell.setCellValue("学生id");
        cell.setCellStyle(style);

        cell = row1.createCell(1);
        cell.setCellValue("姓名");
        cell.setCellStyle(style);

        cell=row1.createCell(2);
        cell.setCellValue("年龄");
        cell.setCellStyle(style);

        //第五步插入数据
        List<StudentInformation> informations = studentMapper.selectList();
        for (int i=0;i<informations.size();i++){
            //创建行
            row = sheet.createRow(i+2);
            //创建单元格并添加数据
            HSSFCell cell2 = row.createCell(0);
            cell2.setCellStyle(style);
            cell2.setCellValue(informations.get(i).getId());

            cell2 = row.createCell(1);
            cell2.setCellStyle(style);
            cell2.setCellValue(informations.get(i).getName());

            cell2=row.createCell(2);
            cell2.setCellStyle(style);
            cell2.setCellValue(informations.get(i).getAge());
        }

       try {
           File file = new File("E:/project3/excel/学生信息表.xls");
           if (!file.exists()){
               FileOutputStream fileOutputStream = new FileOutputStream("E:/project3/excel/学生信息表.xls");
               workbook.write(fileOutputStream);
               fileOutputStream.close();
           }else {
               FileOutputStream fileOutputStream = new FileOutputStream("E:/project3/excel/学生信息表(1).xls");
               workbook.write(fileOutputStream);
               fileOutputStream.close();
           }
       }catch (Exception e){
           e.printStackTrace();
       }finally {
           System.out.println("文件生成成功");
           return "文件生成成功";

       }

    }
}

5.编写controller层

package com.st.controller;

import com.st.pojo.StudentInformation;
import com.st.service.impl.StudentServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
//@CrossOrigin
public class StudentController {
    @Autowired
    private StudentServiceImpl studentService;

    @PostMapping(value = "/createExcel")
    public String createExcel(){
        return studentService.createExcel();
    }

}

6.yml文件内容

server:
  port: 8888
spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/student?serverTimezone=Asia/Shanghai
    driver-class-name: com.mysql.cj.jdbc.Driver
mybatis-plus:
  type-aliases-package: com.st.pojo
  #将所有的映射文件全部加载
  mapper-locations: classpath:/mappers/*.xml
  #开启驼峰映射
  configuration:
    map-underscore-to-camel-case: true

7.测试

(1)启动服务

(2)postman调用接口

不用担心404问题,只要控制台输出文件上传成功字样,到相应的位置找到文件即可

8.结果

一个简单的小功能就实现了

  • 2
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用Apache POI库来实现Java数据导入Excel功能。具体实现代码可以参考以下示例: ```java import java.io.FileOutputStream; import java.io.IOException; import java.util.List; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelWriter { public static void writeData(List<String[]> data, String filePath) throws IOException { Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet(); int rowCount = 0; for (String[] rowData : data) { Row row = sheet.createRow(rowCount++); int columnCount = 0; for (String value : rowData) { Cell cell = row.createCell(columnCount++); if (value instanceof String) { cell.setCellValue((String) value); } else if (value instanceof Double) { cell.setCellValue((Double) value); } else if (value instanceof Integer) { cell.setCellValue((Integer) value); } } } FileOutputStream outputStream = new FileOutputStream(filePath); workbook.write(outputStream); outputStream.close(); workbook.close(); } public static void main(String[] args) throws IOException { List<String[]> data = getData(); writeData(data, "output.xlsx"); } private static List<String[]> getData() { // TODO: 实现获取数据的方法 } } ``` 此代码演示了如何使用Apache POI库创建一个Excel工作簿,并将Java数据写入Excel文件。如果需要导入已有的Excel文件,可以使用相似的代码读取Excel文件数据

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值