大战熟女丰满人妻av-荡女精品导航-岛国aaaa级午夜福利片-岛国av动作片在线观看-岛国av无码免费无禁网站-岛国大片激情做爰视频

專注Java教育14年 全國咨詢/投訴熱線:400-8080-105
動力節點LOGO圖
始于2009,口口相傳的Java黃埔軍校
首頁 hot資訊 Java導出Excel文件的方法

Java導出Excel文件的方法

更新時間:2022-04-14 09:06:34 來源:動力節點 瀏覽1780次

怎么才能用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>

 

提交申請后,顧問老師會電話與您溝通安排學習

免費課程推薦 >>
技術文檔推薦 >>
主站蜘蛛池模板: 久久www香蕉免费人成 | 在线观看欧洲成人免费视频 | 视频一区色眯眯视频在线 | 日本欧美一区二区三区 | 久草视频播放 | 99成人| 免费91视频| 一区二区三区四区国产精品 | 欧美中文字幕视频 | 激情午夜婷婷 | 久久er99热精品一区二区 | 在线观看国产一区二区三区99 | 精品久久久久久久中文字幕 | 九九九热在线精品免费全部 | 亚洲国产天堂久久九九九 | 国产一区二区不卡免费观在线 | 亚洲毛片免费看 | 国产精品第一页爽爽影院 | 欧美成人se01短视频在线看 | 一区二区三区高清在线 | 最新久久免费视频 | 欧美极品妇xxxxxbbbbb | 98色花堂国产精品首页 | 青草视频在线 | 国产青草 | 国产一区二区免费在线观看 | 在线一级毛片 | 尤物视频在线观看视频 | japanese国产高清麻豆 | 久久不卡| 午夜小网站 | 成人牲交一极毛片 | 亚洲欧美精品天堂久久综合一区 | 99热久久国产精品这里 | 男人猛桶女人下面视频国产 | 国产一区二区三区精品久久呦 | 久久综合日韩亚洲精品色 | 伊人色综合久久天天网 | 色综合久久综合网欧美综合网 | 免费国产午夜高清在线视频 | 国产精品久久亚洲不卡4k岛国 |