天天看點

從資料庫表導出為excel表格

package com.test.daotest;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.Iterator;

import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFRow;

import org.apache.poi.hssf.usermodel.HSSFSheet;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.hibernate.Session;

import org.hibernate.Transaction;

import com.test.model.Question;

import com.test.until.HibernateSessionFactory;

public class ExportQuestion {

    public static void main(String[] args) {

        int id=14;

         try {

            HSSFWorkbook wb=new HSSFWorkbook();

             FileOutputStream fileout = new FileOutputStream("test"+id+".xls");

             wb.write(fileout);

             HSSFSheet sheet=wb.createSheet("new sheet");

             //通過Hibernate來查詢addressbook_table表中的資料,将其存儲在List中

                 Session s=HibernateSessionFactory.getSession();

             Transaction tx = s.beginTransaction();

             org.hibernate.Query query= s.createQuery("from Question q where q.majorId="+id);

             List list = query.list();

             tx.commit();

             int k =0;

             //建立表格,建立表格行和單元格,将資料庫中表的字段存儲在單元格中.

             for(Iterator it=list.iterator();it.hasNext();){

             Question q =(Question)it.next();

             HSSFRow row=sheet.createRow((short)k);

             row.createCell((short)0).setCellValue(1);

             row.createCell((short)1).setCellValue(q.getQuestion());

             row.createCell((short)2).setCellValue(q.getOptionA());

             row.createCell((short)3).setCellValue(q.getOptionB());

             row.createCell((short)4).setCellValue(q.getOptionC());

             row.createCell((short)5).setCellValue(q.getOptionD());

             row.createCell((short)6).setCellValue(q.getAnswer());

             row.createCell((short)7).setCellValue(q.getMajorId());

             row.createCell((short)8).setCellValue(0);

             row.createCell((short)9).setCellValue(0);

             k++;

             }

             FileOutputStream fileout1 = new FileOutputStream("test"+id+".xls");

             wb.write(fileout1);

             fileout1.close();

        } catch (FileNotFoundException e) {

            e.printStackTrace();

        } catch (IOException e) {

        }

    }

}