1. 程式人生 > >java使用POI,以excel文件的形式,導出前端表格數據

java使用POI,以excel文件的形式,導出前端表格數據

finally ioutils load exc npoi fin 火狐 XML utf

知識點:前端表格數據,調用後臺接口,導出excel文件數據,使用到Apache POI接口

POI提供API給Java程序對Microsoft Office格式檔案讀和寫的功能。

(1)在pom.xml中引入POI和文件讀寫相關的包

<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>

<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
</dependency>

(2)Controller層,表格導出接口

/**
* 導出數據
*/
@RequestMapping("/Export")
public void export(HttpServletRequest request,HttpServletResponse response){
Export<Equipment> ee = new Export<Equipment>();//equipment實體類
List<Equipment> equiplist = equipmentService.getEquipmentList(); //equiplist是查詢的數據集合

String [] headers = {"e_id","e_code","e_location","e_ip","e_attend_code","cruser","crtime","upuser","uptime"};//表格頭數據設置
String fileName = "設備列表數據"; //excel表格名稱
response.setContentType("application/x-msdownload");
ServletOutputStream outputStream = null; //outputStream文件輸出流
try
{
fileName = fileName + ".xls";// 定義文件格式

if (request.getHeader("USER-AGENT").toLowerCase().contains("firefox"))// 火狐
{
response.setHeader("Content-Disposition",
"attachment;fileName=" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
}
else
{
response.setHeader("Content-Disposition",
"attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
}
outputStream = response.getOutputStream();
try {
ee.Export(headers, fileName, equiplist, outputStream);//表格導出工具類
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
catch (UnsupportedEncodingException e)
{
throw new BusinessException("導出失敗!");
}
catch (IOException e)
{
throw new BusinessException("導出失敗!");
}
catch (NoSuchMethodException e)
{
LOGGER.error(e.getMessage());
}
catch (IllegalAccessException e)
{
LOGGER.error(e.getMessage());
} finally
{
IOUtils.closeQuietly(outputStream);//
}
}

(3)Export.java 表格導出工具類
package com.agesun.attendance.common;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;

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.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

/**
* <一句話功能簡述> <功能詳細描述>
*
* @author nishuai
* @version [版本號, 2018年06月14日]
* @see [相關類/方法]
* @since [產品/模塊版本]
*/
public class Export<T>
{
public void Export(String[] headers, String fileName, List<T> dataset, OutputStream outputStream)
throws NoSuchMethodException, InvocationTargetException, IllegalAccessException
{
// 聲明一個工作薄
HSSFWorkbook wb = new HSSFWorkbook();
// 聲明一個單子並命名
HSSFSheet sheet = wb.createSheet(fileName);

/****************** 頭部樣式 ***********************/
HSSFFont font = wb.createFont();
font.setFontName("微軟雅黑");
font.setFontHeightInPoints((short)14);// 設置字體大小
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 給單子名稱一個長度
sheet.setDefaultColumnWidth((short)16);
// 生成一個樣式
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中
style.setFont(font);
/********************* 數據單元格樣式 **************************/
HSSFFont rowFont = wb.createFont();
rowFont.setFontName("宋體");
rowFont.setFontHeightInPoints((short)14);// 設置字體大小
// 給單子名稱一個長度
sheet.setDefaultColumnWidth((short)16);
// 生成一個樣式
HSSFCellStyle rowStyle = wb.createCellStyle();
rowStyle.setFont(rowFont);
// 樣式字體居中
rowStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);

// 創建第一行(也可以稱為表頭)
HSSFRow row = sheet.createRow(0);
row.setHeight((short)500);
// 給表頭第一行一次創建單元格
for (short i = 0; i < headers.length; i++)
{
HSSFCell cell = row.createCell(i);
cell.setCellValue(headers[i]);
cell.setCellStyle(style);
}

// 遍歷集合數據,產生數據行
Iterator<T> it = dataset.iterator();
int index = 0;
while (it.hasNext())
{
index++;
row = sheet.createRow(index);
row.setHeight((short)500);
T t = it.next();
// 利用反射,根據javabean屬性的先後順序,動態調用getXxx()方法得到屬性值
Field[] fields = t.getClass().getDeclaredFields();
for (short i = 0; i < headers.length; i++)
{
Field field = fields[i];
String fieldName = field.getName();
String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
Class tCls = t.getClass();
Method getMethod = tCls.getMethod(getMethodName, new Class[] {});
Object value = getMethod.invoke(t, new Object[] {});
// 判斷值的類型後進行強制類型轉換
String textValue = null;
// 其它數據類型都當作字符串簡單處理
if (value != null && !"".equals(value))
{
textValue = value.toString();
}
if (textValue != null)
{
HSSFCell cell = row.createCell(i);
cell.setCellStyle(rowStyle);
cell.setCellValue(textValue);
}
}
}

java使用POI,以excel文件的形式,導出前端表格數據