1. 程式人生 > >將從資料庫中獲取的資料寫入到Excel表中

將從資料庫中獲取的資料寫入到Excel表中


pom.xml檔案寫入程式碼,maven自動載入poi-3.1-beta2.jar


<!-- https://mvnrepository.com/artifact/poi/poi -->
        <dependency>
            <groupId>poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.1-beta2</version>
        </dependency>


將資料寫入Excel表中


public class DateToExcelUtil {

    public static void getExcel(List<User> list){
        //第一步:建立一個workbook對應一個Excel檔案
        HSSFWorkbook workbook=new HSSFWorkbook();
        //第二部:在workbook中建立一個sheet對應Excel中的sheet
        HSSFSheet sheet=workbook.createSheet("使用者表一");
        //第三部:在sheet表中新增表頭第0行,老版本的poi對sheet的行列有限制
        HSSFRow row=sheet.createRow(0);
        //第四部:建立單元格,設定表頭
        HSSFCell cell=row.createCell((short) 0);
        cell.setCellValue("使用者名稱");
        cell=row.createCell((short) 1);
        cell.setCellValue("密碼");

        //第五部:寫入實體資料,實際應用中這些 資料從資料庫得到,物件封裝資料,集合包物件。物件的屬性值對應表的每行的值
        for(int i=0;i<list.size();i++){
            HSSFRow row1=sheet.createRow(i+1);
            User user=list.get(i);
            //建立單元格設值
            row1.createCell((short)0).setCellValue(user.getUserAccount());
            row1.createCell((short)1).setCellValue(user.getPassword());
        }
        //將檔案儲存到指定的位置
        try {
            FileOutputStream fos=new FileOutputStream("G:\\user.xls");
            workbook.write(fos);
            System.out.println("寫入成功");
            fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    //測試
    public static void main(String[] args) {
        User user=new User();
        List<User> list=new ArrayList<User>();
        user.setUserAccount("admin");
        user.setPassword("admin");
        list.add(user);
        User user1=new User();
        user1.setUserAccount("commonuser");
        user1.setPassword("123456");
        list.add(user1);
        getExcel(list);
    }

}