ExcelWriter.java 2.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
package com.kwan.springbootkwan.utils;

import com.kwan.springbootkwan.entity.User;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ExcelWriter {

    private static List<String> header = Arrays.asList("1");

    public static void writeListToExcel(List<User> dataList, String filePath, String sheetName) {
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet(sheetName);

            // 创建标题行
            Row headerRow = sheet.createRow(0);
            for (int i = 0; i < dataList.size(); i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue("季节");
            }

            // 写入数据行
            int rowNum = 1;
            for (Object data : dataList) {
                Row row = sheet.createRow(rowNum++);
                CellStyle style = workbook.createCellStyle();
                style.setWrapText(true);
                Cell cell = row.createCell(0);
                cell.setCellValue(data.toString());
                cell.setCellStyle(style);
            }

            // 将Workbook写入文件
            try (FileOutputStream fileOut = new FileOutputStream(filePath)) {
                workbook.write(fileOut);
            }

            System.out.println("Excel文件成功创建!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        // 你的数据列表
        List<User> dataList = new ArrayList<>();
        User user1 = new User();
        user1.setId(1);
        user1.setName("张三");
        user1.setSex("男");
        dataList.add(user1);
        User user2 = new User();
        user2.setId(2);
        user2.setName("程满");
        user2.setSex("女");
        dataList.add(user2);

        User user3 = new User();
        user3.setId(3);
        user3.setName("禹辰");
        user3.setSex("男");
        dataList.add(user3);
        // Excel文件路径和工作表名称
        String filePath = "/Users/qinyingjie/Downloads/file.xlsx";
        String sheetName = "Sheet1";
        // 调用写入Excel的方法
        writeListToExcel(dataList, filePath, sheetName);
    }
}