公共POI導(dǎo)出Excel方法詳解
最早開(kāi)始的時(shí)候做過(guò)一些數(shù)據(jù)Excel導(dǎo)出的功能,但是到后期每一次導(dǎo)出都需要寫一些差不多類似的代碼,稍微研究了一下寫了個(gè)公共的導(dǎo)出方法。
這里用的是POI,然后寫成了一個(gè)公共類,傳入設(shè)置好格式的數(shù)據(jù),就能彈出下載框。
(補(bǔ)充下getResponse的方法,之前沒(méi)注意這個(gè)有繼承!)
package com.hwt.glmf.common;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.hssf.util.HSSFColor;
/**
* 導(dǎo)出Excel公共方法
* @version 1.0
*
* @author wangcp
*
*/
public class ExportExcel extends ActionSupport implements ServletRequestAware{
//顯示的導(dǎo)出表的標(biāo)題
private String title;
//導(dǎo)出表的列名
private String[] rowName ;
private List<Object[]> dataList = new ArrayList<Object[]>();
HttpServletResponse response;
//構(gòu)造方法,傳入要導(dǎo)出的數(shù)據(jù)
public ExportExcel(String title,String[] rowName,List<Object[]> dataList){
this.dataList = dataList;
this.rowName = rowName;
this.title = title;
}
/*
* 導(dǎo)出數(shù)據(jù)
* */
public void export() throws Exception{
try{
HSSFWorkbook workbook = new HSSFWorkbook(); // 創(chuàng)建工作簿對(duì)象
HSSFSheet sheet = workbook.createSheet(title); // 創(chuàng)建工作表
// 產(chǎn)生表格標(biāo)題行
HSSFRow rowm = sheet.createRow(0);
HSSFCell cellTiltle = rowm.createCell(0);
//sheet樣式定義【getColumnTopStyle()/getStyle()均為自定義方法 - 在下面 - 可擴(kuò)展】
HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);//獲取列頭樣式對(duì)象
HSSFCellStyle style = this.getStyle(workbook); //單元格樣式對(duì)象
sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length-1)));
cellTiltle.setCellStyle(columnTopStyle);
cellTiltle.setCellValue(title);
// 定義所需列數(shù)
int columnNum = rowName.length;
HSSFRow rowRowName = sheet.createRow(2); // 在索引2的位置創(chuàng)建行(最頂端的行開(kāi)始的第二行)
// 將列頭設(shè)置到sheet的單元格中
for(int n=0;n<columnNum;n++){
HSSFCell cellRowName = rowRowName.createCell(n); //創(chuàng)建列頭對(duì)應(yīng)個(gè)數(shù)的單元格
cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); //設(shè)置列頭單元格的數(shù)據(jù)類型
HSSFRichTextString text = new HSSFRichTextString(rowName[n]);
cellRowName.setCellValue(text); //設(shè)置列頭單元格的值
cellRowName.setCellStyle(columnTopStyle); //設(shè)置列頭單元格樣式
}
//將查詢出的數(shù)據(jù)設(shè)置到sheet對(duì)應(yīng)的單元格中
for(int i=0;i<dataList.size();i++){
Object[] obj = dataList.get(i);//遍歷每個(gè)對(duì)象
HSSFRow row = sheet.createRow(i+3);//創(chuàng)建所需的行數(shù)
for(int j=0; j<obj.length; j++){
HSSFCell cell = null; //設(shè)置單元格的數(shù)據(jù)類型
if(j == 0){
cell = row.createCell(j,HSSFCell.CELL_TYPE_NUMERIC);
cell.setCellValue(i+1);
}else{
cell = row.createCell(j,HSSFCell.CELL_TYPE_STRING);
if(!"".equals(obj[j]) && obj[j] != null){
cell.setCellValue(obj[j].toString()); //設(shè)置單元格的值
}
}
cell.setCellStyle(style); //設(shè)置單元格樣式
}
}
//讓列寬隨著導(dǎo)出的列長(zhǎng)自動(dòng)適應(yīng)
for (int colNum = 0; colNum < columnNum; colNum++) {
int columnWidth = sheet.getColumnWidth(colNum) / 256;
for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
HSSFRow currentRow;
//當(dāng)前行未被使用過(guò)
if (sheet.getRow(rowNum) == null) {
currentRow = sheet.createRow(rowNum);
} else {
currentRow = sheet.getRow(rowNum);
}
if (currentRow.getCell(colNum) != null) {
HSSFCell currentCell = currentRow.getCell(colNum);
if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
int length = currentCell.getStringCellValue().getBytes().length;
if (columnWidth < length) {
columnWidth = length;
}
}
}
}
if(colNum == 0){
sheet.setColumnWidth(colNum, (columnWidth-2) * 256);
}else{
sheet.setColumnWidth(colNum, (columnWidth+4) * 256);
}
}
if(workbook !=null){
try
{
String fileName = "Excel-" + String.valueOf(System.currentTimeMillis()).substring(4, 13) + ".xls";
String headStr = "attachment; filename=\"" + fileName + "\"";
response = getResponse();
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", headStr);
OutputStream out = response.getOutputStream();
workbook.write(out);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}catch(Exception e){
e.printStackTrace();
}
}
/**
* 獲取response
**/
private HttpServletResponse getResponse(){
HttpServletResponse response = ServletActionContext.getResponse();
return response;
}
/*
* 列頭單元格樣式
*/
public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {
// 設(shè)置字體
HSSFFont font = workbook.createFont();
//設(shè)置字體大小
font.setFontHeightInPoints((short)11);
//字體加粗
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//設(shè)置字體名字
font.setFontName("Courier New");
//設(shè)置樣式;
HSSFCellStyle style = workbook.createCellStyle();
//設(shè)置底邊框;
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
//設(shè)置底邊框顏色;
style.setBottomBorderColor(HSSFColor.BLACK.index);
//設(shè)置左邊框;
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
//設(shè)置左邊框顏色;
style.setLeftBorderColor(HSSFColor.BLACK.index);
//設(shè)置右邊框;
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
//設(shè)置右邊框顏色;
style.setRightBorderColor(HSSFColor.BLACK.index);
//設(shè)置頂邊框;
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
//設(shè)置頂邊框顏色;
style.setTopBorderColor(HSSFColor.BLACK.index);
//在樣式用應(yīng)用設(shè)置的字體;
style.setFont(font);
//設(shè)置自動(dòng)換行;
style.setWrapText(false);
//設(shè)置水平對(duì)齊的樣式為居中對(duì)齊;
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//設(shè)置垂直對(duì)齊的樣式為居中對(duì)齊;
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
return style;
}
/*
* 列數(shù)據(jù)信息單元格樣式
*/
public HSSFCellStyle getStyle(HSSFWorkbook workbook) {
// 設(shè)置字體
HSSFFont font = workbook.createFont();
//設(shè)置字體大小
//font.setFontHeightInPoints((short)10);
//字體加粗
//font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//設(shè)置字體名字
font.setFontName("Courier New");
//設(shè)置樣式;
HSSFCellStyle style = workbook.createCellStyle();
//設(shè)置底邊框;
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
//設(shè)置底邊框顏色;
style.setBottomBorderColor(HSSFColor.BLACK.index);
//設(shè)置左邊框;
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
//設(shè)置左邊框顏色;
style.setLeftBorderColor(HSSFColor.BLACK.index);
//設(shè)置右邊框;
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
//設(shè)置右邊框顏色;
style.setRightBorderColor(HSSFColor.BLACK.index);
//設(shè)置頂邊框;
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
//設(shè)置頂邊框顏色;
style.setTopBorderColor(HSSFColor.BLACK.index);
//在樣式用應(yīng)用設(shè)置的字體;
style.setFont(font);
//設(shè)置自動(dòng)換行;
style.setWrapText(false);
//設(shè)置水平對(duì)齊的樣式為居中對(duì)齊;
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//設(shè)置垂直對(duì)齊的樣式為居中對(duì)齊;
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
return style;
}
}
這個(gè)導(dǎo)出用到的方法,組裝數(shù)據(jù)的如下:
String title = Message.getString("manifestIExportTitle");
String[] rowsName = new String[]{"序號(hào)","貨物運(yùn)輸批次號(hào)","提運(yùn)單號(hào)","狀態(tài)","錄入人","錄入時(shí)間"};
List<Object[]> dataList = new ArrayList<Object[]>();
Object[] objs = null;
for (int i = 0; i < manifestIMainList.size(); i++) {
ManifestIMain man = manifestIMainList.get(i);
objs = new Object[rowsName.length];
objs[0] = i;
objs[1] = man.getTranNo();
objs[2] = man.getBillNo();
objs[3] = man.getStatusFlagCnName();
objs[4] = man.getLoginName();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = df.format(man.getModiDate());
objs[5] = date;
dataList.add(objs);
}
ExportExcel ex = new ExportExcel(title, rowsName, dataList);
ex.export();
是通過(guò)組裝一個(gè)List<Object>的類型(里面是一些列的導(dǎo)出數(shù)據(jù),可以為String/int/long等全部數(shù)據(jù)類型)。數(shù)組rowsName是指導(dǎo)出數(shù)據(jù)的欄位名稱,title是指導(dǎo)出excel的標(biāo)題和sheet名。
以以上的數(shù)據(jù)為例,導(dǎo)出的結(jié)果顯示如下(只是做了簡(jiǎn)單的處理,有一些合并行與excel的樣式問(wèn)題沒(méi)有涉及):

以上所述是小編給大家介紹的公共POI導(dǎo)出Excel方法詳解整合,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
SpringBoot實(shí)現(xiàn)接口冪等性的4種方案
這篇文章主要介紹了SpringBoot實(shí)現(xiàn)接口冪等性的4種方案,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03
spring學(xué)習(xí)之創(chuàng)建項(xiàng)目 Hello Spring實(shí)例代碼
這篇文章主要介紹了spring學(xué)習(xí)之創(chuàng)建項(xiàng)目 Hello Spring實(shí)例代碼,小編覺(jué)得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01
SpringBoot的WebSocket實(shí)現(xiàn)單聊群聊
這篇文章主要為大家詳細(xì)介紹了SpringBoot的WebSocket實(shí)現(xiàn)單聊群聊,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-02-02
使用Shiro實(shí)現(xiàn)登錄成功后跳轉(zhuǎn)到之前的頁(yè)面
這篇文章主要介紹了如何使用Shiro實(shí)現(xiàn)不同用戶登錄成功后跳轉(zhuǎn)到不同主頁(yè),實(shí)現(xiàn)此功能目前比較好的方法是用ajax的方法登錄,第二種方法是把用戶未登錄前的url存在session中,需要的朋友可以參考下2015-07-07
Mybatis-Plus開(kāi)發(fā)提速器mybatis-plus-generator-ui詳解
這篇文章主要介紹了Mybatis-Plus開(kāi)發(fā)提速器mybatis-plus-generator-ui,本文簡(jiǎn)要介紹一款基于Mybatis-Plus的代碼自助生成器,文章通過(guò)實(shí)例集成的方式來(lái)詳細(xì)講解mybatis-plus-generator-ui,從相關(guān)概念到實(shí)際集成案例,以及具體的擴(kuò)展開(kāi)發(fā)介紹,需要的朋友可以參考下2022-11-11
java中給實(shí)體對(duì)象屬性的空值賦默認(rèn)值
這篇文章主要介紹了java中給實(shí)體對(duì)象屬性的空值賦默認(rèn)值,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03

