日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java实现导出Excel的功能

發布時間:2024/9/20 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java实现导出Excel的功能 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

這篇文章主要為大家詳細介紹了java實現導出Excel的功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下

導出excel是咱Java開發的必備技能啦,之前項目有這個功能,現在將其獨立出來,分享一下。

所用技術就是SpringBoot,然后是MVC架構模式。

廢話不多說,直接上代碼了,源碼點末尾鏈接就可以下載。

(1)新建一個SpringBoot項目(可以官網https://start.spring.io/直接生成下載,然后導入eclipse),項目結構如下:

(2)修改pom文件,添加依賴;

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

<dependency>

?<groupId>org.springframework.boot</groupId>

?<artifactId>spring-boot-starter-web</artifactId>

?</dependency>

?<dependency>

?<groupId>org.springframework.boot</groupId>

?<artifactId>spring-boot-starter-test</artifactId>

?<scope>test</scope>

?</dependency>

?<!-- 導出excel -->

?<dependency>

?<groupId>org.apache.poi</groupId>

?<artifactId>poi</artifactId>

?<version>3.14</version>

?</dependency>

?<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->

?<dependency>

?<groupId>org.apache.poi</groupId>

?<artifactId>poi-ooxml</artifactId>

?<version>3.14</version>

?</dependency>

?<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-contrib -->

?<dependency>

?<groupId>org.apache.poi</groupId>

?<artifactId>poi-contrib</artifactId>

?<version>3.6</version>

?</dependency>

?<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->

?<dependency>

?<groupId>org.apache.poi</groupId>

?<artifactId>poi-ooxml-schemas</artifactId>

?<version>3.17</version>

?</dependency>

?<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad -->

?<dependency>

?<groupId>org.apache.poi</groupId>

?<artifactId>poi-scratchpad</artifactId>

?<version>3.17</version>

?</dependency>

(3)新建一個實體類,命名為User.java;

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

package com.twf.springcloud.ExportExcel.po;

import java.io.Serializable;

public class User implements Serializable{

?private static final long serialVersionUID = -9180229310895087286L;

?private String name; // 姓名

?private String sex; // 性別

?private Integer age; // 年齡

?private String phoneNo; // 手機號

?private String address; // 地址

?private String hobby; // 愛好

?public User(String name, String sex, Integer age, String phoneNo, String address, String hobby) {

?super();

?this.name = name;

?this.sex = sex;

?this.age = age;

?this.phoneNo = phoneNo;

?this.address = address;

?this.hobby = hobby;

?}

?public String getName() {

?return name;

?}

?public void setName(String name) {

?this.name = name;

?}

?public String getSex() {

?return sex;

?}

?public void setSex(String sex) {

?this.sex = sex;

?}

?public Integer getAge() {

?return age;

?}

?public void setAge(Integer age) {

?this.age = age;

?}

?public String getPhoneNo() {

?return phoneNo;

?}

?public void setPhoneNo(String phoneNo) {

?this.phoneNo = phoneNo;

?}

?public String getAddress() {

?return address;

?}

?public void setAddress(String address) {

?this.address = address;

?}

?public String getHobby() {

?return hobby;

?}

?public void setHobby(String hobby) {

?this.hobby = hobby;

?}

?@Override

?public String toString() {

?return "User [name=" + name + ", sex=" + sex + ", age=" + age + ", phoneNo=" + phoneNo + ", address=" + address

?+ ", hobby=" + hobby + "]";

?}

}

(4)新建一個excel樣式工具類;

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

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

package com.twf.springcloud.ExportExcel.utils;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;

import org.apache.poi.hssf.usermodel.HSSFFont;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.hssf.util.HSSFColor;

import org.apache.poi.ss.usermodel.CellStyle;

import org.apache.poi.ss.usermodel.Font;

import org.apache.poi.xssf.streaming.SXSSFCell;

import org.apache.poi.xssf.streaming.SXSSFRow;

import org.apache.poi.xssf.streaming.SXSSFSheet;

import org.apache.poi.xssf.streaming.SXSSFWorkbook;

/**

?* excle樣式工具類

?*/

public class ExcelFormatUtil {

?/**

?* 設置報表頭樣式

?* @param workbook

?* @return

?*/

?public static CellStyle headSytle(SXSSFWorkbook workbook){

?// 設置style1的樣式,此樣式運用在第二行

?CellStyle style1 = workbook.createCellStyle();// cell樣式

?// 設置單元格背景色,設置單元格背景色以下兩句必須同時設置

?style1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);// 設置填充樣式

?style1.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);// 設置填充色

?// 設置單元格上、下、左、右的邊框線

?style1.setBorderBottom(HSSFCellStyle.BORDER_THIN);

?style1.setBorderLeft(HSSFCellStyle.BORDER_THIN);

?style1.setBorderRight(HSSFCellStyle.BORDER_THIN);

?style1.setBorderTop(HSSFCellStyle.BORDER_THIN);

?Font font1 = workbook.createFont();// 創建一個字體對象

?font1.setBoldweight((short) 10);// 設置字體的寬度

?font1.setFontHeightInPoints((short) 10);// 設置字體的高度

?font1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 粗體顯示

?style1.setFont(font1);// 設置style1的字體

?style1.setWrapText(true);// 設置自動換行

?style1.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 設置單元格字體顯示居中(左右方向)

?style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 設置單元格字體顯示居中(上下方向)

?return style1;

?}

?/**

?* 設置報表體樣式

?* @param wb

?* @return

?*/

?public static CellStyle contentStyle(SXSSFWorkbook wb){

?// 設置style1的樣式,此樣式運用在第二行

?CellStyle style1 = wb.createCellStyle();// cell樣式

?// 設置單元格上、下、左、右的邊框線

?style1.setBorderBottom(HSSFCellStyle.BORDER_THIN);

?style1.setBorderLeft(HSSFCellStyle.BORDER_THIN);

?style1.setBorderRight(HSSFCellStyle.BORDER_THIN);

?style1.setBorderTop(HSSFCellStyle.BORDER_THIN);

?style1.setWrapText(true);// 設置自動換行

?style1.setAlignment(HSSFCellStyle.ALIGN_LEFT);// 設置單元格字體顯示居中(左右方向)

?style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 設置單元格字體顯示居中(上下方向)

?return style1;

?}

?/**

?* 設置報表標題樣式

?* @param workbook

?* @return

?*/

?public static HSSFCellStyle titleSytle(HSSFWorkbook workbook,short color,short fontSize){

?// 設置style1的樣式,此樣式運用在第二行

?HSSFCellStyle style1 = workbook.createCellStyle();// cell樣式

?// 設置單元格背景色,設置單元格背景色以下兩句必須同時設置

?//style1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);// 設置填充樣式

?//short fcolor = color;

?if(color != HSSFColor.WHITE.index){

?style1.setFillForegroundColor(color);// 設置填充色

?}

?// 設置單元格上、下、左、右的邊框線

?style1.setBorderBottom(HSSFCellStyle.BORDER_THIN);

?style1.setBorderLeft(HSSFCellStyle.BORDER_THIN);

?style1.setBorderRight(HSSFCellStyle.BORDER_THIN);

?style1.setBorderTop(HSSFCellStyle.BORDER_THIN);

?HSSFFont font1 = workbook.createFont();// 創建一個字體對象

?font1.setBoldweight(fontSize);// 設置字體的寬度

?font1.setFontHeightInPoints(fontSize);// 設置字體的高度

?font1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 粗體顯示

?style1.setFont(font1);// 設置style1的字體

?style1.setWrapText(true);// 設置自動換行

?style1.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 設置單元格字體顯示居中(左右方向)

?style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 設置單元格字體顯示居中(上下方向)

?return style1;

?}

?/**

?*設置表頭

?* @param sheet

?*/

?public static void initTitleEX(SXSSFSheet sheet, CellStyle header,String title[],int titleLength[]) {

?SXSSFRow row0 = sheet.createRow(0);

?row0.setHeight((short) 800);

?for(int j = 0;j<title.length; j++) {

?SXSSFCell cell = row0.createCell(j);

?//設置每一列的字段名

?cell.setCellValue(title[j]);

?cell.setCellStyle(header);

?sheet.setColumnWidth(j, titleLength[j]);

?}

?}

}

(5)新建一個Service接口;

1

2

3

4

5

6

7

package com.twf.springcloud.ExportExcel.sevice;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.springframework.http.ResponseEntity;

public interface ExportService {

?ResponseEntity<byte[]> exportExcel(HttpServletRequest request, HttpServletResponse response);

}

(6)新建一個Service接口實現類;

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

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

package com.twf.springcloud.ExportExcel.sevice.impl;

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.util.ArrayList;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.CellStyle;

import org.apache.poi.xssf.streaming.SXSSFCell;

import org.apache.poi.xssf.streaming.SXSSFRow;

import org.apache.poi.xssf.streaming.SXSSFSheet;

import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.http.ResponseEntity;

import org.springframework.stereotype.Service;

import com.twf.springcloud.ExportExcel.controller.BaseFrontController;

import com.twf.springcloud.ExportExcel.po.User;

import com.twf.springcloud.ExportExcel.sevice.ExportService;

import com.twf.springcloud.ExportExcel.utils.ExcelFormatUtil;

@Service

public class ExportServiceImpl implements ExportService{

?Logger logger = LoggerFactory.getLogger(ExportServiceImpl.class);

?@Override

?public ResponseEntity<byte[]> exportExcel(HttpServletRequest request, HttpServletResponse response) {

?try {

?logger.info(">>>>>>>>>>開始導出excel>>>>>>>>>>");

??

?// 造幾條數據

?List<User> list = new ArrayList<>();

?list.add(new User("唐三藏", "男", 30, "13411111111", "東土大唐", "取西經"));

?list.add(new User("孫悟空", "男", 29, "13411111112", "菩提院", "打妖怪"));

?list.add(new User("豬八戒", "男", 28, "13411111113", "高老莊", "偷懶"));

?list.add(new User("沙悟凈", "男", 27, "13411111114", "流沙河", "挑擔子"));

??

?BaseFrontController baseFrontController = new BaseFrontController();

?return baseFrontController.buildResponseEntity(export((List<User>) list), "用戶表.xls");

?} catch (Exception e) {

?e.printStackTrace();

?logger.error(">>>>>>>>>>導出excel 異常,原因為:" + e.getMessage());

?}

?return null;

?}

?private InputStream export(List<User> list) {

?logger.info(">>>>>>>>>>>>>>>>>>>>開始進入導出方法>>>>>>>>>>");

?ByteArrayOutputStream output = null;

?InputStream inputStream1 = null;

?SXSSFWorkbook wb = new SXSSFWorkbook(1000);// 保留1000條數據在內存中

?SXSSFSheet sheet = wb.createSheet();

?// 設置報表頭樣式

?CellStyle header = ExcelFormatUtil.headSytle(wb);// cell樣式

?CellStyle content = ExcelFormatUtil.contentStyle(wb);// 報表體樣式

??

?// 每一列字段名

?String[] strs = new String[] { "姓名", "性別", "年齡", "手機號", "地址","愛好" };

??

?// 字段名所在表格的寬度

?int[] ints = new int[] { 5000, 5000, 5000, 5000, 5000, 5000 };

??

?// 設置表頭樣式

?ExcelFormatUtil.initTitleEX(sheet, header, strs, ints);

?logger.info(">>>>>>>>>>>>>>>>>>>>表頭樣式設置完成>>>>>>>>>>");

??

?if (list != null && list.size() > 0) {

?logger.info(">>>>>>>>>>>>>>>>>>>>開始遍歷數據組裝單元格內容>>>>>>>>>>");

?for (int i = 0; i < list.size(); i++) {

?User user = list.get(i);

?SXSSFRow row = sheet.createRow(i + 1);

?int j = 0;

?SXSSFCell cell = row.createCell(j++);

?cell.setCellValue(user.getName()); // 姓名

?cell.setCellStyle(content);

?cell = row.createCell(j++);

?cell.setCellValue(user.getSex()); // 性別

?cell.setCellStyle(content);

?cell = row.createCell(j++);

?cell.setCellValue(user.getAge()); // 年齡

?cell.setCellStyle(content);

?cell = row.createCell(j++);

?cell.setCellValue(user.getPhoneNo()); // 手機號

?cell.setCellStyle(content);

?cell = row.createCell(j++);

?cell.setCellValue(user.getAddress()); // 地址

?cell.setCellStyle(content);

??

?cell = row.createCell(j++);

?cell.setCellValue(user.getHobby()); // 愛好

?cell.setCellStyle(content);

?}

?logger.info(">>>>>>>>>>>>>>>>>>>>結束遍歷數據組裝單元格內容>>>>>>>>>>");

?}

?try {

?output = new ByteArrayOutputStream();

?wb.write(output);

?inputStream1 = new ByteArrayInputStream(output.toByteArray());

?output.flush();

?} catch (Exception e) {

?e.printStackTrace();

?} finally {

?try {

?if (output != null) {

?output.close();

?if (inputStream1 != null)

?inputStream1.close();

?}

?} catch (IOException e) {

?e.printStackTrace();

?}

?}

?return inputStream1;

?}

}

(7)新建一個下載文件的通用controller;

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

package com.twf.springcloud.ExportExcel.controller;

import java.io.InputStream;

import java.net.URLEncoder;

import java.util.HashMap;

import java.util.Map;

import org.apache.poi.util.IOUtils;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.http.HttpHeaders;

import org.springframework.http.HttpStatus;

import org.springframework.http.ResponseEntity;

import org.springframework.util.StringUtils;

import org.springframework.validation.annotation.Validated;

@Validated

public class BaseFrontController {

??

?/**

?* slf4j 日志 logger

?*/

?protected final Logger logger = LoggerFactory.getLogger(this.getClass());

?/**

?* 下載文件,純SpringMVC的API來完成

?*

?* @param is 文件輸入流

?* @param name 文件名稱,帶后綴名

?*

?* @throws Exception

?*/

?public ResponseEntity<byte[]> buildResponseEntity(InputStream is, String name) throws Exception {

?logger.info(">>>>>>>>>>>>>>>>>>>>開始下載文件>>>>>>>>>>");

?if (this.logger.isDebugEnabled())

?this.logger.debug("download: " + name);

?HttpHeaders header = new HttpHeaders();

?String fileSuffix = name.substring(name.lastIndexOf('.') + 1);

?fileSuffix = fileSuffix.toLowerCase();

??

?Map<String, String> arguments = new HashMap<String, String>();

?arguments.put("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

?arguments.put("xls", "application/vnd.ms-excel");

??

?String contentType = arguments.get(fileSuffix);

?header.add("Content-Type", (StringUtils.hasText(contentType) ? contentType : "application/x-download"));

?if(is!=null && is.available()!=0){

?header.add("Content-Length", String.valueOf(is.available()));

?header.add("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + URLEncoder.encode(name, "UTF-8"));

?byte[] bs = IOUtils.toByteArray(is);

?logger.info(">>>>>>>>>>>>>>>>>>>>結束下載文件-有記錄>>>>>>>>>>");

?logger.info(">>>>>>>>>>結束導出excel>>>>>>>>>>");

?return new ResponseEntity<>(bs, header, HttpStatus.OK);

?}else{

?String string="數據為空";

?header.add("Content-Length", "0");

?header.add("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + URLEncoder.encode(name, "UTF-8"));

?logger.info(">>>>>>>>>>>>>>>>>>>>結束下載文件-無記錄>>>>>>>>>>");

?logger.info(">>>>>>>>>>結束導出excel>>>>>>>>>>");

?return new ResponseEntity<>(string.getBytes(), header, HttpStatus.OK);

?}

?}

}

(8)新建一個controller,作為請求的入口;

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

package com.twf.springcloud.ExportExcel.controller;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.ResponseEntity;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import com.twf.springcloud.ExportExcel.sevice.ExportService;

@RestController

@RequestMapping("/exportExcel/")

public class ExportController {

??

?@Autowired

?private ExportService exportService;

?// 導出excel

?@RequestMapping("exportExcel")

?public ResponseEntity<byte[]> exportExcel(HttpServletRequest request, HttpServletResponse response) {

?return exportService.exportExcel(request,response);

?}

}

(9)運行ExportExcelApplication,瀏覽器訪問http://localhost:8080/exportExcel/exportExcel,可以下載excel,打開如下:

(10)項目源碼

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

來源:https://www.jb51.net/article/161337.htm

總結

以上是生活随笔為你收集整理的java实现导出Excel的功能的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。