在做管理系統的時候,我想Excel的導出是我們很難規避掉的,而且這也是個很實用很人性化的功能。
Java中對于Excel的支持有很多種,比如說JXL,POI等。我這邊使用的是POI進行一個Excel的操作,下面我會簡單分享下POI組件的使用,以及我使用比較多一個工具類。
poi組件是由Apache提供的組件包,主要職責是為我們的Java程序提供對于office文檔的相關操作。本文主要是它對于Excel操作的一個介紹。
官方主頁:http://poi.apache.org/index.html
API文檔:http://poi.apache.org/apidocs/index.html
使用的時候我們可以發現poi組件為我們提供的操作Excel的相關類都是HSSF開頭的,這些類主要是在org.apache.poi.hssf.usermodel這個包下面。里面包涵有像Excel的對象,單元格的樣式,字體樣式以及部分的工具類。一下介紹幾個我們常用的類:
- HSSFWorkbook:Excel對象,相當于一個 .xls/.xlsx 文件
- HSSFSheet:工作表對象,Excel文件包涵的sheet,一個對象代表一個表單
- HSSFRow:表示表格中的行對象。
- HSSFCell:表示表格中的單元格對象。
- HSSFHeader:Excel文檔Sheet的頁眉。
- HSSFFooter:Excel文檔Sheet的頁腳。
- HSSFDataFormat:日期格式。
- HSSFFont:字體對象。
- HSSFCellStyle:單元格樣式(對齊樣式、邊框等)
- HSSFComment:批注(注釋)。
- HSSFPatriarch:和HSSFComment用于創建注釋的位置。
- HSSFColor:顏色對象。
- HSSFDateUtil:日期輔助工具
- HSSFPrintSetup:打印輔助工具
- HSSFErrorConstants:錯誤信息表
1.HSSFWorkbook創建‘Excel文件對象'
//創建Excel對象 HSSFWorkbook workbook = new HSSFWorkbook();
2.使用workbook 對象創建工作表對象
//創建工作表單
HSSFSheet sheet = workbook.createSheet("對象報表");
3.創建行和操作單元格對象
//創建HSSFRow對象 (行)
HSSFRow row = sheet.createRow(0);
//創建HSSFCell對象 (單元格)
HSSFCell cell=row.createCell(0);
//設置單元格的值
cell.setCellValue("單元格中的中文");
4.保存Excel文件
//輸出Excel文件
FileOutputStream output=new FileOutputStream("d:\\workbook.xls");
workbook.write(output);
output.flush();
這邊我列舉出部分常用的樣式設置的方法!
1.合并單元格,設置寬、高
// 實例化樣式對象
HSSFCellStyle cellStyle = workbook.createCellStyle();
// 兩端對齊
cellStyle.setAlignment(HSSFCellStyle.ALIGN_JUSTIFY);
// 垂直居中
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
// 填充圖案---填充方式
cellStyle.setFillPattern(HSSFCellStyle.DIAMONDS);
// 設置前景色 (這個要寫在背景色的前面)
cellStyle.setFillForegroundColor(HSSFColor.RED.index);
// 設置背景顏色
cellStyle.setFillBackgroundColor(HSSFColor.LIGHT_YELLOW.index);
// 設置邊框
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_SLANTED_DASH_DOT);
// 邊框顏色
cellStyle.setBottomBorderColor(HSSFColor.DARK_RED.index);
// 日期展示格式
cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
//將樣式應用于單元格
cell.setCellStyle(cellStyle);
//將樣式應用到行
row.setRowStyle(cellStyle);
2.設置單元格樣式
// 實例化樣式對象
HSSFCellStyle cellStyle = workbook.createCellStyle();
// 兩端對齊
cellStyle.setAlignment(HSSFCellStyle.ALIGN_JUSTIFY);
// 垂直居中
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
// 填充圖案---填充方式
cellStyle.setFillPattern(HSSFCellStyle.DIAMONDS);
// 設置前景色 (這個要寫在背景色的前面)
cellStyle.setFillForegroundColor(HSSFColor.RED.index);
// 設置背景顏色
cellStyle.setFillBackgroundColor(HSSFColor.LIGHT_YELLOW.index);
// 設置邊框
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_SLANTED_DASH_DOT);
// 邊框顏色
cellStyle.setBottomBorderColor(HSSFColor.DARK_RED.index);
// 日期展示格式
cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
//將樣式應用于單元格
cell.setCellStyle(cellStyle);
//將樣式應用到行
row.setRowStyle(cellStyle);
3.設置字體
// 實例化字體對象
HSSFFont fontStyle = workbook.createFont();
// 字體
fontStyle.setFontName("宋體");
// 高度
fontStyle.setFontHeightInPoints((short)12);
// 字體
font.setColor(HSSFColor.BLUE.index);
// 加粗
fontStyle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 斜體
font.setItalic(true);
// 下劃線
font.setUnderline(HSSFFont.U_SINGLE);
// 將字體應用于單元格樣式中
cellStyle.setFont(font);
下面給大家分享下個人的整體使用過程!

處理的action
//用于導出的數據集合
List<PBillBean> dataset = new ArrayList<PBillBean>();
//填充dataset
for (int i = 0; i < 10; i++) {
PBillBean bean = new PBillBean();
dataset.add(bean);
}
//臨時文件
File tempFile = null;
try {
//Excel導出工具類
ExportExcel<PBillBean> ex = new ExportExcel<PBillBean>();
//導出的標題列
String[] headers = { "標題1", "標題2", "標題3", "標題4", "標題5", "標題6" };
//時間格式化
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
//要保存的文件名
String filename = "bill_" + format.format(new Date()) + ".xls";
//要保存的根目錄
String rootDir = request.getSession().getServletContext().getRealPath("/");
//要保存的目錄路徑
String path = rootDir + File.separator + "tempfile";
File saveDir = new File(path);
if (!saveDir.exists()) {
saveDir.mkdirs();// 如果文件不存在則創建文件夾
}
//文件路徑
path = path + File.separator + filename;
tempFile = new File(path); //初始化臨時文件
//輸出流
OutputStream out = new FileOutputStream(tempFile);
//實例化Excel表格
HSSFWorkbook workbook = new HSSFWorkbook();
//創建工作表單
String[] sheetNames = { "對賬報表" };
for (int i = 0; i < sheetNames.length; i++) {
workbook.createSheet(sheetNames[i]);
}
//導出到Excel
ex.exportExcel(sheetNames[0], headers, dataset, out,
"yyyy-MM-dd HH:mm", workbook);
try {
//保存文件
workbook.write(out);
} catch (IOException e) {
e.printStackTrace();
}
out.close();
// 以流的形式下載文件。
BufferedInputStream fis = new BufferedInputStream(
new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 設置response的Header
response.addHeader("Content-Disposition", "attachment;filename="
+ new String(filename.getBytes()));
response.addHeader("Content-Length", "" + tempFile.length());
OutputStream toClient = new BufferedOutputStream(
response.getOutputStream());
response.setContentType("application/vnd.ms-excel;charset=utf-8");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (tempFile != null && tempFile.exists()) {
tempFile.delete();// 刪除臨時文件
}
}
導出Excel工具類
public void exportExcel(String title, String[] headers, Collection<T> dataset, OutputStream out, String pattern,HSSFWorkbook workbook)
{
// 聲明一個工作薄 生成一個表格
HSSFSheet sheet = workbook.getSheet(title);
// 設置表格默認列寬度為15個字節
sheet.setDefaultColumnWidth((short) 15);
// 生成一個樣式
HSSFCellStyle style = workbook.createCellStyle();
// 設置這些樣式
style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 生成一個字體
HSSFFont font = workbook.createFont();
font.setColor(HSSFColor.VIOLET.index);
font.setFontHeightInPoints((short) 12);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 把字體應用到當前的樣式
style.setFont(font);
// 生成并設置另一個樣式
HSSFCellStyle style2 = workbook.createCellStyle();
style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
// 生成另一個字體
HSSFFont font2 = workbook.createFont();
font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
// 把字體應用到當前的樣式
style2.setFont(font2);
// 聲明一個畫圖的頂級管理器
HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
// 定義注釋的大小和位置,詳見文檔
HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5));
// 設置注釋內容
comment.setString(new HSSFRichTextString("可以在POI中添加注釋!"));
// 設置注釋作者,當鼠標移動到單元格上是可以在狀態欄中看到該內容.
comment.setAuthor("leno");
// 產生表格標題行
HSSFRow row = sheet.createRow(0);
for (short i = 0; i < headers.length; i++)
{
HSSFCell cell = row.createCell(i);
cell.setCellStyle(style);
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
// 遍歷集合數據,產生數據行
Iterator<T> it = dataset.iterator();
int index = 0;
while (it.hasNext())
{
index++;
row = sheet.createRow(index);
T t = (T) it.next();
// 利用反射,根據javabean屬性的先后順序,動態調用getXxx()方法得到屬性值
Field[] fields = t.getClass().getDeclaredFields();
for (short i = 0; i < fields.length; i++)
{
HSSFCell cell = row.createCell(i);
cell.setCellStyle(style2);
Field field = fields[i];
String fieldName = field.getName();
String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
try
{
Class tCls = t.getClass();
Method getMethod = tCls.getMethod(getMethodName, new Class[] {});
Object value = getMethod.invoke(t, new Object[] {});
// 判斷值的類型后進行強制類型轉換
String textValue = null;
if (value instanceof Boolean)
{
boolean bValue = (Boolean) value;
textValue = "男";
if (!bValue)
{
textValue = "女";
}
}
else if (value instanceof Date)
{
Date date = (Date) value;
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
textValue = sdf.format(date);
}
else if (value instanceof byte[])
{
// 有圖片時,設置行高為60px;
row.setHeightInPoints(60);
// 設置圖片所在列寬度為80px,注意這里單位的一個換算
sheet.setColumnWidth(i, (short) (35.7 * 80));
// sheet.autoSizeColumn(i);
byte[] bsValue = (byte[]) value;
HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0,1023, 255, (short) 6, index, (short) 6, index);
anchor.setAnchorType(2);
patriarch.createPicture(anchor, workbook.addPicture(bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG));
}
else
{
// 其它數據類型都當作字符串簡單處理
textValue = value == null? "": value.toString();
}
// 如果不是圖片數據,就利用正則表達式判斷textValue是否全部由數字組成
if (textValue != null)
{
Pattern p = Pattern.compile("^//d+(//.//d+)?$");
Matcher matcher = p.matcher(textValue);
if (matcher.matches())
{
// 是數字當作double處理
cell.setCellValue(Double.parseDouble(textValue));
}
else
{
HSSFRichTextString richString = new HSSFRichTextString(textValue);
HSSFFont font3 = workbook.createFont();
font3.setColor(HSSFColor.BLUE.index);
richString.applyFont(font3);
cell.setCellValue(richString);
}
}
}
catch (SecurityException e)
{
e.printStackTrace();
}
catch (NoSuchMethodException e)
{
e.printStackTrace();
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
catch (InvocationTargetException e)
{
e.printStackTrace();
}
finally
{
// 清理資源
}
}
}
}
Excel數據的導出大功告成了,個人感覺這個導出的工具類還是很好用的,希望大家能喜歡!
更多關于Java使用poi組件導出Excel格式數據文章請查看下面的相關鏈接
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。