將從數據庫中獲取的數據寫入到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);
    }

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM