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

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

@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

#导出文件路径:导出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
<!-- 指定执行的目标类、方法 -->
    <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

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

...
<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)

Hot Topics

Java Tutorial
1658
14
PHP Tutorial
1257
29
C# Tutorial
1231
24
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

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

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

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles