jlx 支持Excel 95-2000的所有版本、生成Excel 2000標準格式、支持字體、數字、日期操作
能夠修飾單元格屬性、 支持圖像和圖表,這裏只簡單實現一下把數據庫表中的信息導出到excel中。記住一定要導入jlx的類包。具體代碼如下:
- import java.io.File;
- import java.io.IOException;
- import java.lang.reflect.Field;
- import java.util.ArrayList;
- import java.util.Iterator;
- import java.util.List;
- import com.ecshop.dao.Goodsdao;
- import com.ecshop.vo.EcsGoods;
- import jxl.Workbook;
- import jxl.write.Label;
- import jxl.write.WritableSheet;
- import jxl.write.WritableWorkbook;
- import jxl.write.WriteException;
- import jxl.write.biff.RowsExceededException;
- import com.ecshop.common.HibernateUtil;
- public class GoodsOutToExecl {
- /**
- * @param args
- * 實現將數據庫表EcsGoods中的字段信息導出到Execl文件中
- */
- public static void main(String[] args) {
- int row = 0;// 記錄寫入Execl操作的當前行
- try {
- // 打開文件
- WritableWorkbook book = Workbook.createWorkbook(new File(
- "goods.xls"));
- // 生成名爲“sheet1”的工作表,參數0表示這是工作部的第一個sheet表格
- WritableSheet sheet = book.createSheet("sheet1", 0);
- List<EcsGoods> list = new ArrayList<EcsGoods>();
- // 查詢數據庫內容保存到List中
- Session session = HibernateUtil.getSessionFactory().getCurrentSession();
- session.beginTransaction();
- Query query = session.createQuery("from EcsGoods where isReal = 1 and isDelete = 0");
- list = query.list();
- session.getTransaction().commit();
- // 使用List的迭代器循環輸出
- Iterator<EcsGoods> it = list.iterator();
- while (it.hasNext()) {
- EcsGoods good = it.next();
- // 使用反射機制獲取Class類
- Class cl = Class.forName("com.ecshop.vo.EcsGoods");
- // 獲取class類的所有成員變量
- Field[] f = cl.getDeclaredFields();
- if (row == 0) {
- // 輸出表的字段名
- for (int i = 0; i < f.length; i++) {
- f[i].setAccessible(true);
- // 在Label對象的構造子中指名單元格位置是第i列第row行(i,row)
- // 以及單元格內容爲 f[i].getName()即成員變量的名字的名稱
- Label label = new Label(i, row, f[i].getName());
- sheet.addCell(label);
- }
- row++;
- } else {
- // 輸出每條記錄的值
- for (int i = 0; i < f.length; i++) {
- f[i].setAccessible(true);
- /*
- * 在Label對象的構造子中指名單元格位置是第i列第row行(i,row) 以及單元格內容爲
- * f[i].get(good).toString()即good對象每個字段的值,這裏需要注意一下,如果表中
- * 字段爲Null時就報錯,所以要將f[i].get(good).toString()改爲:
- * f[i].get(good) == null ? "":
- * f[i].get(good).toString() 這樣的話如果值爲Null時就 導出空字符即可。
- */
- Label label = new Label(i, row,
- f[i].get(good) == null ? "" : f[i].get(good)
- .toString());
- sheet.addCell(label);
- }
- row++;
- }
- }
- book.write();
- book.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (RowsExceededException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (WriteException e) {
- e.printStackTrace();
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- }
- }
- }