Excel 导出功能简单可用CV直接用

 maven 导入:

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.3.3</version>
        </dependency>
@Data
@ExcelIgnoreUnannotated // 只针对字段上是否有@ExcelProperty字段 才会导出来过滤条件注解
public class ExcelRepsVo{

    @ExcelProperty("序号") // 导出Excel字段
    private Long id;

    @ExcelProperty("名称")
    private String name;

    @ExcelProperty("编码")
    private String code;

}

每个字段上,添加 @ExcelProperty (opens new window)注解,声明 Excel Head 头部的名字。每个字段的,就是它对应的 Excel Row 行的数据值。 

在类上,添加 @ExcelIgnoreUnannotated (opens new window)注解,表示未添加 @ExcelProperty 的字段,不进行导出。

 贡献大家工具类

public class ExcelUtils {
    /**
     * 将列表以 Excel 响应给前端
     *
     * @param response  响应
     * @param filename  文件名
     * @param sheetName Excel sheet 名
     * @param head      Excel head 头
     * @param data      数据列表哦
     * @param <T>       泛型,保证 head 和 data 类型的一致性
     * @throws IOException 写入失败的情况
     */
    public static <T> void write(HttpServletResponse response, String filename, String sheetName,Class<T> head, List<T> data) throws IOException {
        // 输出 Excel
        EasyExcel.write(response.getOutputStream(), head)
                .autoCloseStream(false) // 不要自动关闭,交给 Servlet 自己处理
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 基于 column 长度,自动适配。最大 255 宽度
                .registerWriteHandler(new SelectSheetWriteHandler(head)) // 基于固定 sheet 实现下拉框
                .registerConverter(new LongStringConverter()) // 避免 Long 类型丢失精度
                .sheet(sheetName).doWrite(data);
        // 设置 header 和 contentType。写在最后的原因是,避免报错时,响应 contentType 已经被修改了
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8.name()));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
    }

    public static <T> List<T> read(MultipartFile file, Class<T> head) throws IOException {
        return EasyExcel.read(file.getInputStream(), head, null)
                .autoCloseStream(false)  // 不要自动关闭,交给 Servlet 自己处理
                .doReadAllSync();
    }

}

测试:

 @GetMapping("/export")
 public void exportExampleExcel(@Valid ExcelRepsVo pageReqVO,
 HttpServletResponse response) throws IOException {
        List<ExcelRepsVo> list = new ArrayList<ExcelRepsVo>();//你的数据 对应泛型ExcelRepsVo.class类。
        // 导出 Excel
        ExcelUtils.write(response, "ExcelRepsVo.xls", sheet页名字, ExcelRepsVo.class,
                        list);
    }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Java中的Apache POI来读取Excel文件,并结合JDBC连接数据库将数据导入到数据库中。 以下是一个简单的示例代码,假设你要将Excel中的数据导入到名为"table_name"的数据库表中: ```java import java.io.FileInputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelToDatabase { public static void main(String[] args) { String jdbcURL = "jdbc:mysql://localhost:3306/database_name"; String username = "username"; String password = "password"; String excelFilePath = "path/to/excel/file.xlsx"; try (Connection connection = DriverManager.getConnection(jdbcURL, username, password); FileInputStream inputStream = new FileInputStream(excelFilePath); XSSFWorkbook workbook = new XSSFWorkbook(inputStream)) { Sheet sheet = workbook.getSheetAt(0); String sql = "INSERT INTO table_name (column1, column2, column3) VALUES (?, ?, ?)"; PreparedStatement statement = connection.prepareStatement(sql); for (int i = 1; i <= sheet.getLastRowNum(); i++) { Row currentRow = sheet.getRow(i); Cell cell1 = currentRow.getCell(0); statement.setString(1, cell1.getStringCellValue()); Cell cell2 = currentRow.getCell(1); statement.setString(2, cell2.getStringCellValue()); Cell cell3 = currentRow.getCell(2); statement.setString(3, cell3.getStringCellValue()); statement.executeUpdate(); } System.out.println("Data imported successfully"); } catch (SQLException e) { System.out.println("Database error: " + e.getMessage()); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } } } ``` 请替换代码中的数据库连接信息、Excel文件路径、表名和列名等信息,以适应你的情况。注意,代码中默认将Excel文件的第一行视为表头,因此从第二行开始读取数据。 另外,需要在项目中引入Apache POI和MySQL JDBC驱动的依赖。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值