Table of Contents
Code Overview
Home Java javaTutorial Introduction to the method of exporting excel files in Java (code example)

Introduction to the method of exporting excel files in Java (code example)

Dec 14, 2018 am 10:03 AM
java

This article brings you an introduction to the method of exporting excel files in Java (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. helped.

Requirements

Export the online/offline user information of each xmpp computer room to an Excel table (scheduled task web button) , and provide a download button on the web page for downloading.

Effect preview

Introduction to the method of exporting excel files in Java (code example)

Export file effect

Introduction to the method of exporting excel files in Java (code example)

Code Overview

/**"..." is the company's business code, which mostly obtains export data from cache or database, and does not affect the export function.

  • The front-end writing method is the company framework, just understand the general meaning.

*/
1. Tool class: Generate excel object wb

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

127

128

129

package com.onewaveinc.utils;

 

import java.util.List;

 

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

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

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

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

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

 

import com.onewaveinc.mip.log.Logger;

import com.onewaveinc.user.entity.UserInfo;

/**

 * 生成Excel文件工具类

 * @author wxin

 *

 */

public class ExcelUtil {

 

    private static Logger logger = Logger.getInstance(ExcelUtil.class);

    /**

     * 导出Excel

     * @param sheetName sheet名称

     * @param title 标题

     * @param values 内容

     * @param wb HSSFWorkbook对象

     * @return

     */

    public static HSSFWorkbook getHSSFWorkbook(String sheetName,String []title,List<userinfo> valueList, HSSFWorkbook wb){

 

        // 第一步,创建一个HSSFWorkbook,对应一个Excel文件

        if(wb == null){

            wb = new HSSFWorkbook();

        }

 

        // 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet

        HSSFSheet sheet = wb.createSheet(sheetName);

 

        // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制

        HSSFRow row = sheet.createRow(0);

 

        // 第四步,创建单元格,并设置值表头 设置表头居中

        HSSFCellStyle style = wb.createCellStyle();

        // 创建一个居中格式

        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); 

 

        //声明列对象

        HSSFCell cell = null;

 

        //创建标题

        for(int i=0;i<title.length> 0) {

            for(int i=0;i<valuelist.size><p>2. Generate excel file method</p>

<pre class="brush:php;toolbar:false">    public void run() throws InterruptedException, IOException {

         ExportExcel();

   }

 

    /**

     * 定时导出XMPP每个机房(一个集群)的在线用户的信息

     * 导出信息:用户账号,mac地址,登陆的IP,登陆域名,机顶盒的型号,版本,和以及登陆所在节点的ip,

     * 显示 登陆的时间,登陆的时长(现在的时间减去登陆的时间)。

     */

    public  String ExportExcel() {

        String result = "";

        try {

            ...

            result = ImportDataExcel(offlineUserInfoList, serverName, false);

            logger.info("**此次处理离线结果为:"+result);

            ...

             

        catch (Exception e) {

            result = "failed";

            e.printStackTrace();

        }

        return result;

         

    }

    /**

     * 导出用户信息数据到Excel表格

     * @param userInfoList

     * @return msg “failed” or “success”

     */

    public String ImportDataExcel(List<userinfo> userInfoList, String serverName , boolean isOnline) {

        String msg = "";

        String fileName = "";

        String sheetName = "";

        String[] title = {"用户账号","mac地址","登陆IP","登陆域名","机顶盒型号""机顶盒版本",

                "登录所在节点的IP""登陆时间""登陆时长"};

        //设置日期格式

        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");

        // new Date()为获取当前系统时间,也可使用当前时间戳

        String date = df.format(new Date());

        if (isOnline) {

            fileName = serverName+"-online-usersInfo-"+date+".xls";

            sheetName = serverName+"在线用户信息表";

        else {

            fileName = serverName+"-offline-usersInfo-"+date+".xls";

            sheetName = serverName+"离线用户信息表";

        }

        HSSFWorkbook wb = new HSSFWorkbook();

        wb = ExcelUtil.getHSSFWorkbook(sheetName, title, userInfoList, null);

        ByteArrayOutputStream os = new ByteArrayOutputStream();

        try{

            wb.write(os);

        }

        catch (IOException e){

            msg = "failed";

            e.printStackTrace();

        }

        byte[] content = os.toByteArray();

        //Excel文件生成后存储的位置。

        File file = new File(path+"/"+fileName);

        OutputStream fos  = null;

        try{

            fos = new FileOutputStream(file);

            fos.write(content);

            os.close();

            fos.close();

            if ("".equals(msg)) {

                msg = "success";

            }

            logger.info("生成用户信息Excel表格成功:"+ fileName);

        }

        catch (Exception e){

            msg = "failed";

            logger.error("生成用户信息Excel表格失败:"+ fileName);

            e.printStackTrace();

        }

        return msg;

    }</userinfo>

Copy after login

3. SpringMVC

1

2

3

4

5

6

7

8

9

10

11

12

13

14

@SuppressWarnings("deprecation")

@Resource("userLoginService")

@Bean("contbiz.imoss.userloginservice")

public class UserChannelLoginService {

...

    @Post

    @Path("exportExcel")

    public String ExportExcel() {

        String result = "";

        result = exportXMPPUserInfo.ExportExcel();

        return result;

    }

...

}

Copy after login

4. Configuration file

1

2

3

4

5

6

7

#导出文件路径:导出XMPP各个机房的在线用户信息Excel表,

#<require>

/spring/config.properties|xmpp.export.excel.path=D:\Doc\test111

 

#定时任务时间:导出XMPP各个机房的在线用户信息Excel表,

#<require>

/spring/config.properties|xmpp.export.excel.time=0 44,45,46,47 20 11 * ?</require></require>

Copy after login

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

<!-- 指定执行的目标类、方法 -->

    <bean>

             <!-- 指定任务类 -->

             <property></property>

            <!--  指定任务方法 -->

             <property></property>

             <property></property>

     </bean>

    <!-- 设置执行任务以及时间 -->

     <bean>

             <property>

                    <ref></ref>

             </property>

             <property>

                    <value>${xmpp.export.excel.time}</value>

             </property>

      </bean>

      <!-- 启动定时器 -->

      <bean>

             <property>

                    <list>

                           <!-- <ref bean="autoSmsB2cJobDetailSimpleTrigger" /> -->

                           <ref></ref>

                    </list>

             </property>

       </bean>

Copy after login

5. Front-end

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

/**前端写法为公司框架,理解大致意思就好。*/

 

...

<input>

...

<script>

    //导出excel

    W.$(&#39;exportExcel&#39;).on(&#39;click&#39;,function(e){   

         

        W.create(&#39;userLoginService/exportExcel&#39;).done(function(result){

            if (result == "success") {

                W.alert("导出所有在线/离线用户成功");

            } else {

                W.alert("导出所有在线/离线用户失败");

            }

             

        });

    });

</script>

Copy after login


##

The above is the detailed content of Introduction to the method of exporting excel files in Java (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles