導出excel功能,較通用的一種實現

作用:通過jxl包生成excel文件。示例請看main方法 

特點: 
1、通過java的反射特性,將jxl生成excel的邏輯,和業務數據解耦。在LinkedHashMap參數中定義每一列的標題以及對應的javabean屬性,生成excel時,就會根據map插入的先後順序,依次在excel中添加列,每列的標題爲map的value值,內容爲對應的javabean屬性。 

2、通過一個map,可以很方便地配置excel中每列的內容和順序 

3、優化顯示。數字用千分位格式,且右對齊;時間類型的值,轉成標準的yyyy-MM-dd HH:mm:ss形式;其他表格內容居中顯示;標題粗體;表格根據寬度自適應顯示

package mqq.sdet.rdm.common.util;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import jxl.CellView;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

public class ExportExcelUtil
{

	public static final int RESULT_SUCC = 0;
	public static final int RESULT_FAIL = -1;

	public static final String TYPE_YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

	/**
	 * 將數據轉成成excel。 特性: 1、將時間類型的值轉成yyyy-MM-dd HH:mm:ss 2、將數字類型的值轉成帶千分符的形式,並右對齊
	 * 3、除數字類型外,其他類型的值居中顯示
	 * 
	 * @param keyMap
	 *            定義標題及每一列對應的JavaBean屬性。標題的先後順序,對應keyMap的插入順序;
	 *            map中的key值爲JavaBean屬性,value爲標題
	 * @param listContent
	 *            表格內容,List中的每一個元素,對應到excel的每一行
	 * @param os
	 *            結果輸出流
	 * @return
	 */
	public final int export(LinkedHashMap<String, String> keyMap, List<Object> listContent, OutputStream os)
	{

		int rs = RESULT_SUCC;
		try
		{

			// 創建工作簿
			WritableWorkbook workbook = Workbook.createWorkbook(os);

			// 創建名爲sheet1的工作表
			WritableSheet sheet = workbook.createSheet("Sheet1", 0);

			// 設置字體
			WritableFont NormalFont = new WritableFont(WritableFont.ARIAL, 12);
			WritableFont BoldFont = new WritableFont(WritableFont.ARIAL, 12, WritableFont.BOLD);

			// 標題居中
			WritableCellFormat titleFormat = new WritableCellFormat(BoldFont);
			titleFormat.setBorder(Border.ALL, BorderLineStyle.THIN); // 線條
			titleFormat.setVerticalAlignment(VerticalAlignment.CENTRE); // 文字垂直對齊
			titleFormat.setAlignment(Alignment.CENTRE); // 文字水平對齊
			titleFormat.setWrap(false); // 文字是否換行

			// 正文居中
			WritableCellFormat contentCenterFormat = new WritableCellFormat(NormalFont);
			contentCenterFormat.setBorder(Border.ALL, BorderLineStyle.THIN);
			contentCenterFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
			contentCenterFormat.setAlignment(Alignment.CENTRE);
			contentCenterFormat.setWrap(false);

			// 正文右對齊
			WritableCellFormat contentRightFormat = new WritableCellFormat(NormalFont);
			contentRightFormat.setBorder(Border.ALL, BorderLineStyle.THIN);
			contentRightFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
			contentRightFormat.setAlignment(Alignment.RIGHT);
			contentRightFormat.setWrap(false);

			// 設置標題,標題內容爲keyMap中的value值,標題居中粗體顯示
			Iterator titleIter = keyMap.entrySet().iterator();
			int titleIndex = 0;
			while (titleIter.hasNext())
			{
				Map.Entry<String, String> entry = (Map.Entry<String, String>) titleIter.next();
				sheet.addCell(new Label(titleIndex++, 0, entry.getValue(), titleFormat));
			}

			// 設置正文內容
			for (int i = 0; i < listContent.size(); i++)
			{
				Iterator contentIter = keyMap.entrySet().iterator();
				int colIndex = 0;
				int listIndex = 0;
				while (contentIter.hasNext())
				{
					Map.Entry<String, String> entry = (Map.Entry<String, String>) contentIter.next();
					Object key = entry.getKey();

					Field field = listContent.get(i).getClass().getDeclaredField(key.toString());
					field.setAccessible(true);
					Object content = field.get(listContent.get(i));

					String contentStr = null != content ? content.toString() : "";

					WritableCellFormat cellFormat = contentCenterFormat;

					// 將數字轉變成千分位格式
					String numberStr = getNumbericValue(contentStr);
					// numberStr不爲空,說明是數字類型。
					if (null != numberStr && !numberStr.trim().equals(""))
					{
						contentStr = numberStr;
						// 數字要右對齊
						cellFormat = contentRightFormat;
					}
					else
					{
						// 如果是時間類型。要格式化成標準時間格式
						String timeStr = getTimeFormatValue(field, content);
						// timeStr不爲空,說明是時間類型
						if (null != timeStr && !timeStr.trim().equals(""))
						{
							contentStr = timeStr;
						}
					}

					sheet.addCell(new Label(colIndex++, i + 1, contentStr, cellFormat));

				}

			}

			// 寬度自適應。能夠根據內容增加寬度,但對中文的支持不好,如果內容中包含中文,會有部分內容被遮蓋
			for (int i = 0; i < keyMap.size(); i++)
			{
				CellView cell = sheet.getColumnView(i);
				cell.setAutosize(true);
				sheet.setColumnView(i, cell);
			}

			workbook.write();
			workbook.close();

		}
		catch (Exception e)
		{
			rs = RESULT_FAIL;
			e.printStackTrace();
		}
		return rs;
	};

	/**
	 * 獲取格式化後的時間串
	 * 
	 * @param field
	 * @param content
	 * @return
	 */
	private String getTimeFormatValue(Field field, Object content)
	{
		String timeFormatVal = "";
		if (field.getType().getName().equals(java.sql.Timestamp.class.getName()))
		{
			Timestamp time = (Timestamp) content;
			timeFormatVal = longTimeTypeToStr(time.getTime(), TYPE_YYYY_MM_DD_HH_MM_SS);
		}
		else if (field.getType().getName().equals(java.util.Date.class.getName()))
		{
			Date time = (Date) content;
			timeFormatVal = longTimeTypeToStr(time.getTime(), TYPE_YYYY_MM_DD_HH_MM_SS);
		}

		return timeFormatVal;
	}

	/**
	 * 獲取千分位數字
	 * 
	 * @param str
	 * @return
	 */
	private String getNumbericValue(String str)
	{
		String numbericVal = "";
		try
		{
			Double doubleVal = Double.valueOf(str);
			numbericVal = DecimalFormat.getNumberInstance().format(doubleVal);
		}
		catch (NumberFormatException e)
		{
			// if exception, not format
		}
		return numbericVal;
	}

	/**
	 * 格式化時間
	 * 
	 * @param time
	 * @param formatType
	 * @return
	 */
	public String longTimeTypeToStr(long time, String formatType)
	{

		String strTime = "";
		if (time >= 0)
		{
			SimpleDateFormat sDateFormat = new SimpleDateFormat(formatType);

			strTime = sDateFormat.format(new Date(time));

		}

		return strTime;

	}

	public static class TestBean
	{
		private String strTest;
		private int intTest;
		private Timestamp timeTest;

		public String getStrTest()
		{
			return strTest;
		}

		public void setStrTest(String strTest)
		{
			this.strTest = strTest;
		}

		public int getIntTest()
		{
			return intTest;
		}

		public void setIntTest(int intTest)
		{
			this.intTest = intTest;
		}

		public Timestamp getTimeTest()
		{
			return timeTest;
		}

		public void setTimeTest(Timestamp timeTest)
		{
			this.timeTest = timeTest;
		}
	}

	public static void main(String[] args)
	{
		long start = System.currentTimeMillis();

		List<Object> li = new ArrayList<Object>();

		TestBean testBean = new TestBean();
		testBean.setIntTest(8888);
		testBean.setStrTest("88888.888");
		testBean.setTimeTest(new Timestamp(System.currentTimeMillis()));

		for (int i = 0; i < 1000; i++)
		{
			li.add(testBean);
		}

		LinkedHashMap<String, String> keyMap = new LinkedHashMap<String, String>();
		keyMap.put("timeTest", "time類型");
		keyMap.put("intTest", "int類型");
		keyMap.put("strTest", "string類型");

		OutputStream out;
		try
		{
			ExportExcelUtil util = new ExportExcelUtil();
			out = new FileOutputStream("d:/exportExcel/test28.xls");
			util.export(keyMap, li, out);
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}

		long end = System.currentTimeMillis();
		System.out.println(end - start);

	}

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章