通过xml配置实现数据动态导入导出Excel

spring-dj-excel-common.jar 一个可以通过动态配置 xml 建立 Excel 与数据关系现实数据导入导出的 spring 组件包,在 xml 配置文件里,你可以很方便的定义 Excel - sheet 表列头文本与数据表、数据实体属性的对应关系,对于创建 Excel 文件,你可以通过增加某一标签列的子项实现列头跨列展示效果,同时你也可以通过设置列头对应的样式属性 headStyle 来设置sheet表列头的文字、颜色、边框的展示效果,你也可以针对每一列进行单独的样式设置。

首先,为Excel文件与项目中的数据模型和数据表之间的关系创建一个配置文件,如果要将数据导入到Excel文件中,那么也可以在配置文件中对Excel文件进行基本的样式设置,例如,可以设置列宽, Excel 的文本大小、颜色、字体等。

单击此链接,可以下载资源编译代码生成的 JAR 包文件

单击此链接,可以下载 spring-dj-excel-common.jar 包的源代码

下面是一个简单的配置文件示例,配置文件名称可以根据实际业务进行命名,可以在源码包的 resources/excelconfigs 路径下看到示例配置文件。

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<FieldMappings table="UserInfo"
               title="User information"
               headStyle="text-align:center;text-valign:center;background-color:green;color:white;border-width:1px;border-color:yellow;">    
    <column alias="name" allowEmpty="false" columnWidth="100" length="5" name="name" text="Name" type="string" style=""/>
    <column alias="sex" allowEmpty="false" columnWidth="80" length="1" name="gender" text="Gender" type="string" style=""/>
    <column alias="age" allowEmpty="true" columnWidth="80" name="age" text="Age" type="int" style=""/>
    <column alias="phone" allowEmpty="false" columnWidth="180" length="20" name="phone" text="Phone" type="string" style=""/>
    <!--If the column has children, it means that the parent column needs to be displayed across columns-->
    <column alias="course" name="course" text="Course">
        <column index="1" alias="chinese" allowEmpty="false" columnWidth="120" length="0" name="chinese" text="Chinese" type="float" style=""/>
        <column index="2" alias="physics" allowEmpty="false" columnWidth="120" length="0" name="physics" text="Physics" type="float" style=""/>
    </column>
    <column alias="address" allowEmpty="true" width="300" length="100" name="address" text="Address" type="string" style=""/>
</FieldMappings>


FieldMapping 标签属性说明:
table - 表名称,程序中数据导入导出时在调用方法时作为参数使用
title - 标题,数据导入到 Excel 中时,数里该属性值不为空,sheet表的首行首列将显示该属性值
headStyle - 设置 Excel 中数据列头的显示效果,可以设置单元格背景颜色、单元格前景色、单元格边框线宽和边框线颜色、文本大小、文本在单元格中的位置、文本字体类型、文本粗体


column 标签属性说明:
name - 对相应数据表中的列的名称
index - 序号, 设置列在 Excel 表中显示顺序, 如果不设置按配置文件中从上至下顺序依次显示
alias - 列的别名(对应于数据模型的属性名称)
text - Excel 文件中表格的列标题文本
columnWidth - 设置 Excel 文件中表的列宽,也可以使用 width 属性
allowEmpty - 在将数据导入 Excel 时,是否允许数据为空, 设置为 true 表示允许为空
type - 数据类型, 类型范围: string, int, float, double, boolean, date
length - 数据允许的长度,类型为 string 时有效
style - 为指定列设置单独的样式,与 headStyle 类似,此属性优先级高于 FieldMapping 标签中的 headStyle 属性
headStyle - 单独设置当前列在 Excel 文件中标题样式,优先级高于 style 属性及 FieldMapping 标签中的 headStyle 属性,可以设置单元格背景颜色、单元格前景色、单元格边框线宽和边框线颜色、文本大小、文本在单元格中的位置、文本字体类型、文本粗体
dataStyle - 单独设置当前列在 Excel 文件中数据单元样式,优先级高于 style 属性

样式设置支持
字体样式color设置字体颜色,仅支持在色域范围内的值
font-family设置字体名称,默认“宋体”
font-italic设置字体是否为斜体,值为 true 时文本显示为斜体
font-weight设置字体需要加粗显示,值为 true 时加粗显示
font-size设置字体大小
text-underline设置文本是否需要加下划线,值为 true 时加下划线
常规text-align文本在单元格中水平显示位置,值:left, center, right
text-valign文本在单元格中垂直显示位置,值: top, center, bottom
background-color设置单元格背景色,仅支持在色域范围内的值
border-width设置单元格边框粗度,值域 0~13
border-color设置单元格边框颜色,仅支持在色域范围内的值

系统支持色域范围:
BLACK1, WHITE1, RED1, BRIGHT_GREEN1, BLUE1, YELLOW1, PINK1, TURQUOISE1, BLACK, WHITE, RED, BRIGHT_GREEN, BLUE, YELLOW, PINK, TURQUOISE, DARK_RED, GREEN, DARK_BLUE, DARK_YELLOW, VIOLET, TEAL, GREY_25_PERCENT, GREY_50_PERCENT, CORNFLOWER_BLUE, MAROON, LEMON_CHIFFON, LIGHT_TURQUOISE1, ORCHID, CORAL, ROYAL_BLUE, LIGHT_CORNFLOWER_BLUE, SKY_BLUE, LIGHT_TURQUOISE, LIGHT_GREEN, LIGHT_YELLOW, PALE_BLUE, ROSE, LAVENDER, TAN, LIGHT_BLUE, AQUA, LIME, GOLD, LIGHT_ORANGE, ORANGE, BLUE_GREY, GREY_40_PERCENT, DARK_TEAL, SEA_GREEN, DARK_GREEN, OLIVE_GREEN, BROWN, PLUM, INDIGO, GREY_80_PERCENT

通常,配置文件位于项目的资源目录中:
main
--java
--resources
----excelconfig
------excel-user-info.xml
----application.yml

向启动类添加 @EnableExcelConfigScan 注解,并指定 XML 配置文件目录位置。
示例:

  @SpringBootApplicatio
  @EnableExcelConfigScan(configPackages = {"excelconfig"})
  public class UserInformationApplication {
      public static void main(String[] args) {
          SpringApplication.run(UserInformationApplication.class, args);
      }
  }

如何使用该组件呢?

该组件支持xls和xlsx文件格式两种格式的数据导入和导出,在程序中,Excel2003表示后缀为xls文件格式,Excel2007表示xlsx文件格式后缀。

1、从 Excel 文件获取数据

@Autowired
private IExcel2003Export excel2003Export;
@Autowired
private IExcel2007Import excel2007Import;

@Test
void getDataFromExcel() throws Exception {        
    String fPath = "D:\\user-info.xls";
    //The third parameter value 'UserInfo', corresponds to the value of the table attribute in the xml configuration file
    excel2003Export.exportToEntityFromFile(fPath, "Sheet1", "UserInfo", UserInfo.class, ((entity, rowIndex) -> {
        //Get the data for each row in the Excel file
        System.out.println("row: " + rowIndex + ", data: " + entity.toString());
        return true;
    }));
}

2、把数据导入到 Excel 中

@Autowired
private IExcel2003Import excel2003Import;
@Autowired
private IExcel2007Import excel2007Import;

private byte[] createExcel(IExcelImport excelImport) {
    String extName = "xls";
    if (IExcel2007Import.class.isAssignableFrom(excelImport.getClass())) extName = "xlsx";   
    try {
        //Getting an IExcelBuilder interface object is equivalent to creating a new sheet form
        IExcelBuilder builder = excelImport.createBuilder("UserInfo");
        UserInfo userInfo = new UserInfo();
        userInfo.setName("DJ").setAge(18).setPhone("1231456789").setGender(1).setUid("admin")
                .setPwd("admin").setEmail("dj@qq.com").setAddress("China")
                .setOrder_by(1).setIs_enabled(true);
        builder.createRow(userInfo, UserInfo.class);

        //Here we get another IExcelBuilder interface object, and we create a new sheet again
        builder = excelImport.createBuilder("UserInfo");
        builder.setSheetName("UserInfoQueryDTO");
        //Here's how to get the UserInfo data from the database and import it into the newly created sheet table
        List<UserInfoQueryDTO> dtos = findUserInfoByName("allan");
        builder.createRows(dtos, UserInfoQueryDTO.class);

        byte[] datas = excelImport.getBytes();
        //You can also choose to save the created Excel file to a specified disk location
        //excelImport.save("D:\\user-info." + extName);
        return datas;
    } catch (Exception e) {
        System.out.println("Excel import exception: " + e);
    } finally {
        try {
            excelImport.close();
        } catch (Exception e) {
            //
        }
    }
    return new byte[0];
}

//使用 IExcel2003Import 去调用 createExcel 方法
byte[] data = createExcel(excel2003Import);

//使用 IExcel2007Import 去调用 createExcel 方法
byte[] data = createExcel(excel2007Import);

  • 14
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值