专注Java教育14年 全国咨询/投诉热线:400-8080-105
动力节点LOGO图
始于2009,口口相传的Java黄埔军校
首页 hot资讯 Java导出Excel文件的方法

Java导出Excel文件的方法

更新时间:2022-04-14 09:06:34 来源:动力节点 浏览1382次

怎么才能用Java导出Excel文件?动力节点小编来告诉大家。

要求

将每个xmpp机房的在线/离线用户信息导出到Excel表格(定时任务+网页按钮),并在网页上提供下载按钮供下载。

效果预览

导出文件效果

点击下载弹出效果

代码结果概览

/*“....”是公司的业务代码,主要是从缓存或数据库中获取导出数据,不影响导出功能。/

i.工具类:生成excel对象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;
/**
 * Generate Excel file tool class
 * @author wxin
 *
 */
public class ExcelUtil {
    private static Logger logger = Logger.getInstance(ExcelUtil.class);
    /**
     * Export Excel
     * @param sheetName sheet Name
     * @param title Title
     * @param values content
     * @param wb HSSFWorkbook object
     * @return
     */
    public static HSSFWorkbook getHSSFWorkbook(String sheetName,String []title,List<UserInfo> valueList, HSSFWorkbook wb){
        // The first step is to create an HSSFWorkbook corresponding to an Excel file
        if(wb == null){
            wb = new HSSFWorkbook();
        }
        // Step 2: add a sheet in the workbook, corresponding to the sheet in the Excel file
        HSSFSheet sheet = wb.createSheet(sheetName);
        // Step 3: add row 0 of the header in the sheet. Note that the old version of poi has restrictions on the number of rows and columns in Excel
        HSSFRow row = sheet.createRow(0);
        // Step 4: create cells and set the value header to set the header Center
        HSSFCellStyle style = wb.createCellStyle();
        // Create a centered format
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); 
        //Declare column objects
        HSSFCell cell = null;
        //Create title
        for(int i=0;i<title.length;i++){
            cell = row.createCell((short) i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(style);
        }
        //Create content
        if (null != valueList && valueList.size() > 0) {
            for(int i=0;i<valueList.size();i++){
                row = sheet.createRow(i + 1);
                UserInfo userInfo = valueList.get(i);
                String []userInfoArray = {userInfo.getLoginName(),userInfo.getStbMac(),userInfo.getLoginIp(),
                        userInfo.getServerDomain(), userInfo.getTerminalModel(),userInfo.getTerminalVersion(),
                        userInfo.getServerIp(),    userInfo.getUpdateTime(),userInfo.getLoginTime()};
                for(int j=0;j<userInfoArray.length;j++){
                    //Assign content to corresponding column objects in order
                    row.createCell((short) j).setCellValue(userInfoArray[j]);
                }
            }
        } else {
            logger.error("No data for user information");
        }
        return wb;
    }
}

生成excel文件的方法

    public void run() throws InterruptedException, IOException {
         ExportExcel();
   }
    /**
     * Regularly export the information of online users in each machine room (a cluster) of XMPP
     * Export information: user account, mac address, login IP, login domain name, model and version of set-top box, and the IP of the node where the login is located,
     * Display the time of login and the time of login (the current time minus the time of login).
     */
    public  String ExportExcel() {
        String result = "";
        try {
            ...
            result = ImportDataExcel(offlineUserInfoList, serverName, false);
            logger.info("**The offline result of this processing is:"+result);
            ...            
        } catch (Exception e) {
            result = "failed";
            e.printStackTrace();
        }
        return result;
    }
    /**
     * Export user information data to Excel table
     * @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 = {"User account","mac address","Land IP","Login domain name","Set top box model", "Set top box version",
                "Log in to the IP", "Landing time", "Landing time"};
        //Format date
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        // new Date() to get the current system time, you can also use the current time stamp
        String date = df.format(new Date());
        if (isOnline) {
            fileName = serverName+"-online-usersInfo-"+date+".xls";
            sheetName = serverName+"Online user information form";
        } else {
            fileName = serverName+"-offline-usersInfo-"+date+".xls";
            sheetName = serverName+"Offline user information table";
        }
        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();
        //The location where Excel files are stored after they are generated.
        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("Generate user information Excel Form success:"+ fileName);
        }
        catch (Exception e){
            msg = "failed";
            logger.error("Generate user information Excel Form failure:"+ fileName);
            e.printStackTrace();
        }
        return msg;
    } 

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;
    }
...
}

配置文件

#Export file path: export the online user information Excel table of each machine room of XMPP,
#<require>
/spring/config.properties|xmpp.export.excel.path=D:\Doc\test111
#Scheduled task time: export the online user information Excel table of each machine room of XMPP,
#<require>
/spring/config.properties|xmpp.export.excel.time=0 44,45,46,47 20 11 * ?
<!-- Specify the target class and method to execute -->
    <bean id="autoSmsB2cJobDetail"  class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
             <!-- Specify task class -->
             <property name="targetObject" ref="contbiz.imoss.exportXMPPUserInfo" />
            <!--  Specify task method -->
             <property name="targetMethod" value="run" />
             <property name="concurrent" value="false" />
     </bean>
    <!-- Set the execution task and time -->
     <bean id="autoSmsB2cJobDetailCronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
             <property name="jobDetail">
                    <ref bean="autoSmsB2cJobDetail" />
             </property>
             <property name="cronExpression">
                    <value>${xmpp.export.excel.time}</value>
             </property>
      </bean>
      <!-- Start timer -->
      <bean id="ssschedulerFactory" class="org.springframework.scheduling.quartz.SchedulerFactoryBean" lazy-init="false">
             <property name="triggers">
                    <list>
                           <!-- <ref bean="autoSmsB2cJobDetailSimpleTrigger" /> -->
                           <ref bean="autoSmsB2cJobDetailCronTrigger" />
                    </list>
             </property>
       </bean>

前端

...
<input id="exportExcel" type="submit" value="export" />
...
<script>
    //Export excel
    W.$('exportExcel').on('click',function(e){    
        
        W.create('userLoginService/exportExcel').done(function(result){
            if (result == "success") {
                W.alert("Export all online/Offline user succeeded");
            } else {
                W.alert("Export all online/Offline user failed");
            }            
        });
    });
</script>

 

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>