這篇文章主要介紹了Java如何導出excel文件,具有一定借鑒價值,需要的朋友可以參考下。希望大家閱讀完這篇文章后大有收獲。下面讓小編帶著大家一起了解一下。
需求
將每個xmpp機房的在線/離線用戶信息導出到Excel表格中(定時任務+網頁按鈕),并在網頁上提供下載按鈕進行下載。
效果預覽

導出文件效果

/** "..."為公司業務代碼,大多為從緩存或者數據庫中獲取導出數據,不影響導出功能。
前端寫法為公司框架,理解大致意思就好。
*/
一、工具類:生成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;
/**
* 生成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;i++){
cell = row.createCell((short) i);
cell.setCellValue(title[i]);
cell.setCellStyle(style);
}
//創建內容
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++){
//將內容按順序賦給對應的列對象
row.createCell((short) j).setCellValue(userInfoArray[j]);
}
}
} else {
logger.error("用戶信息無數據");
}
return wb;
}
}二、生成excel文件方法
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;
}三、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;
}
...
}四、配置文件
#導出文件路徑:導出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 * ?
<!-- 指定執行的目標類、方法 -->
<bean id="autoSmsB2cJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<!-- 指定任務類 -->
<property name="targetObject" ref="contbiz.imoss.exportXMPPUserInfo" />
<!-- 指定任務方法 -->
<property name="targetMethod" value="run" />
<property name="concurrent" value="false" />
</bean>
<!-- 設置執行任務以及時間 -->
<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>
<!-- 啟動定時器 -->
<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="導出" />
...
<script>
//導出excel
W.$('exportExcel').on('click',function(e){
W.create('userLoginService/exportExcel').done(function(result){
if (result == "success") {
W.alert("導出所有在線/離線用戶成功");
} else {
W.alert("導出所有在線/離線用戶失敗");
}
});
});
</script>感謝你能夠認真閱讀完這篇文章,希望小編分享Java如何導出excel文件內容對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,遇到問題就找億速云,詳細的解決方法等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。