SpringBoot導(dǎo)出數(shù)據(jù)為Excel

Excel導(dǎo)入請(qǐng)參考:SpringBoot讀取Excel并存入數(shù)據(jù)庫(kù)

  • 引入依賴(lài)
    這里我只是貼出了關(guān)鍵性的依賴(lài)~

        <!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.55</version>
        </dependency>

        <dependency>
            <groupId>net.sourceforge.jexcelapi</groupId>
            <artifactId>jxl</artifactId>
            <version>2.6.12</version>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.2</version>
        </dependency>
  • MyBatisPlusConfig
@Configuration
public class MyBatisPlusConfig {
    /**
     * mybatis-plus分頁(yè)插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        return paginationInterceptor;
    }
}
  • Swagger2
@Configuration
@EnableSwagger2
public class Swagger2 {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.booot.excel.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //設(shè)置文檔的標(biāo)題
                .title("APi")
                // 設(shè)置文檔的描述
                .description("接口測(cè)試")
                // 設(shè)置文檔的版本信息-> 1.0.0 Version information
                .version("1.0")
                // 設(shè)置文檔的License信息->1.3 License information
                .termsOfServiceUrl("www.756316064@qq.com")
                .build();
    }
}
  • ProfessionController
/**
 * (Profession)表控制層
 *
 * @author makejava
 * @since 2020-04-20 20:28:55
 */
@RestController
@Api("專(zhuān)業(yè)")
@RequestMapping("pro")
public class ProfessionController {
    /**
     * 服務(wù)對(duì)象
     */
    @Resource
    private ProfessionService professionService;

    /**
     * @Description: 導(dǎo)出
     * @params: [response, pageNo, pageSize]
     * @return: void
     * @Date: 2020/3/5 10:11 AM
     */
    @ApiOperation(value = "excel導(dǎo)出")
    @GetMapping("/export")
    public void exportSign(HttpServletResponse response, @RequestParam("page") Integer page,
                           @RequestParam("limit") Integer limit ) {
        WritableWorkbook workbook = null;
        try {
            //導(dǎo)出的文件名
            String fileName = "專(zhuān)業(yè)信息-" + System.currentTimeMillis() + ".xls";
            //從數(shù)據(jù)庫(kù)中查詢(xún)出來(lái)的數(shù)據(jù)
            Page<Profession> professionPage = new Page<>(page,limit);
            Page<Profession> professionIPage = this.professionService.page(professionPage);
            List<Profession> professions = professionIPage.getRecords();

            response.reset();
            // vnd.ms-excel
            response.setContentType("application/x-xls");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            workbook = Workbook.createWorkbook(response.getOutputStream());
            //創(chuàng)建sheet
            WritableSheet profession = workbook.createSheet("專(zhuān)業(yè)信息", 0);
            profession.setColumnView(0, 20);
            profession.setColumnView(1, 20);
            profession.setColumnView(2, 20);

            profession.setRowView(0, 450, false);

            //設(shè)置標(biāo)題
            WritableCellFormat titleCellFormat = setTitleCellFormat(true);
            profession.addCell(new Label(0, 0, "專(zhuān)業(yè)名稱(chēng)", titleCellFormat));
            profession.addCell(new Label(1, 0, "學(xué)院", titleCellFormat));
            profession.addCell(new Label(2, 0, "學(xué)校", titleCellFormat));

            //存放數(shù)據(jù)
            WritableCellFormat contentCellFormat = setContentCellFormat();
            for (int i = 0; i < professions.size(); i++) {
                profession.addCell(new Label(0, i + 1, professions.get(i).getProfessionName(), contentCellFormat));
                profession.addCell(new Label(1, i + 1, professions.get(i).getApartment(), contentCellFormat));
                profession.addCell(new Label(2, i + 1, professions.get(i).getSchool(), contentCellFormat));
            }
            response.flushBuffer();
            workbook.write();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //如果判斷workbook是否為空,不為空->關(guān)閉鏈接
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (WriteException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 設(shè)置導(dǎo)出表格的標(biāo)題欄單元格樣式
     * @param hasBorder
     * @return
     * @throws WriteException
     */
    private WritableCellFormat setTitleCellFormat(boolean hasBorder) throws WriteException {
        WritableFont titleFont = new WritableFont(WritableFont.createFont("黑體"), 11, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE,
                Colour.BLACK);

        WritableCellFormat titleCellFormat = new WritableCellFormat();
        titleCellFormat.setFont(titleFont);
        titleCellFormat.setAlignment(jxl.format.Alignment.CENTRE);
        titleCellFormat.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
        if (hasBorder) {
            titleCellFormat.setBorder(Border.BOTTOM, BorderLineStyle.DOUBLE, Colour.BLACK);
        }
        return titleCellFormat;
    }

    /**
     * 設(shè)置導(dǎo)出表格的內(nèi)容單元格樣式
     * @return
     * @throws WriteException
     */
    private WritableCellFormat setContentCellFormat() throws WriteException {
        WritableCellFormat contentCellFormat = new WritableCellFormat();
        contentCellFormat.setFont(new WritableFont(WritableFont.createFont("宋體"), 10, WritableFont.NO_BOLD, false));
        contentCellFormat.setAlignment(jxl.format.Alignment.CENTRE);
        contentCellFormat.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
        contentCellFormat.setWrap(true);
        return contentCellFormat;
    }

}
  • ProfessionDao
@Mapper
public interface ProfessionDao extends BaseMapper<Profession> {
}
  • Profession
@Data
@TableName("profession")
public class Profession implements Serializable {
    private static final long serialVersionUID = 217915017239376333L;

    @TableId(value = "profession_id",type = IdType.AUTO)
    private Integer professionId;

    @TableField("profession_name")
    private String professionName;

    @TableField("apartment")
    private String apartment;

    @TableField("school")
    private String school;

    @TableField("create_time")
    private Date createTime;
}
  • ProfessionService
public interface ProfessionService extends IService<Profession> {

}
@Service("professionService")
public class ProfessionServiceImpl extends ServiceImpl<ProfessionDao,Profession> implements ProfessionService {
    @Resource
    private ProfessionDao professionDao;
}
  • ExcelApplication
@SpringBootApplication
@MapperScan("com.booot.excel.dao")
@EnableSwagger2
public class ExcelApplication {
    public static void main(String[] args) {
        SpringApplication.run(ExcelApplication.class, args);
    }

}
  • ProfessionDao.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.booot.excel.dao.ProfessionDao">

    <resultMap type="com.booot.excel.entity.Profession" id="ProfessionMap">
        <result property="professionId" column="profession_id" jdbcType="INTEGER"/>
        <result property="professionName" column="profession_name" jdbcType="VARCHAR"/>
        <result property="apartment" column="apartment" jdbcType="VARCHAR"/>
        <result property="school" column="school" jdbcType="VARCHAR"/>
        <result property="createTime" column="create_time" jdbcType="TIMESTAMP"/>
    </resultMap>
</mapper>
  • application.yml
spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/appdemo?useUnicode=true&characterEncoding=UTF-8
    username: root
    password: 123456
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 100MB
mybatis-plus:
  mapper-locations: classpath:/mapper/*Dao.xml
  typeAliasesPackage: com.booot.excel.entity
  configuration:
    map-underscore-to-camel-case: true
    cache-enabled: true
    lazyLoadingEnabled: true
    multipleResultSetsEnabled: true

測(cè)試

PS:本人較懶壕探,不喜歡多解釋~??

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請(qǐng)通過(guò)簡(jiǎn)信或評(píng)論聯(lián)系作者苗沧。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市粥烁,隨后出現(xiàn)的幾起案子箭阶,更是在濱河造成了極大的恐慌晌端,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,548評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件婉陷,死亡現(xiàn)場(chǎng)離奇詭異帚称,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)憨攒,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,497評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門(mén)世杀,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人肝集,你說(shuō)我怎么就攤上這事瞻坝。” “怎么了杏瞻?”我有些...
    開(kāi)封第一講書(shū)人閱讀 167,990評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵所刀,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我捞挥,道長(zhǎng)浮创,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 59,618評(píng)論 1 296
  • 正文 為了忘掉前任砌函,我火速辦了婚禮斩披,結(jié)果婚禮上溜族,老公的妹妹穿的比我還像新娘。我一直安慰自己垦沉,他們只是感情好煌抒,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,618評(píng)論 6 397
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著厕倍,像睡著了一般寡壮。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上讹弯,一...
    開(kāi)封第一講書(shū)人閱讀 52,246評(píng)論 1 308
  • 那天况既,我揣著相機(jī)與錄音,去河邊找鬼组民。 笑死棒仍,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的邪乍。 我是一名探鬼主播降狠,決...
    沈念sama閱讀 40,819評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼庇楞!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起否纬,我...
    開(kāi)封第一講書(shū)人閱讀 39,725評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤吕晌,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后临燃,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體睛驳,經(jīng)...
    沈念sama閱讀 46,268評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,356評(píng)論 3 340
  • 正文 我和宋清朗相戀三年膜廊,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了乏沸。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,488評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡爪瓜,死狀恐怖蹬跃,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情铆铆,我是刑警寧澤蝶缀,帶...
    沈念sama閱讀 36,181評(píng)論 5 350
  • 正文 年R本政府宣布,位于F島的核電站薄货,受9級(jí)特大地震影響翁都,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜谅猾,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,862評(píng)論 3 333
  • 文/蒙蒙 一柄慰、第九天 我趴在偏房一處隱蔽的房頂上張望鳍悠。 院中可真熱鬧,春花似錦坐搔、人聲如沸贼涩。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,331評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)遥倦。三九已至,卻和暖如春占锯,著一層夾襖步出監(jiān)牢的瞬間袒哥,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,445評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工消略, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留堡称,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,897評(píng)論 3 376
  • 正文 我出身青樓艺演,卻偏偏與公主長(zhǎng)得像却紧,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子胎撤,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,500評(píng)論 2 359