- 資訊首頁(yè) > 開(kāi)發(fā)技術(shù) > 編程語(yǔ)言 >
- Java中用POI實(shí)現將數據導出到Excel
數據導出為Excel在我們寫(xiě)項目的過(guò)程中經(jīng)常用到
需要用到的jar包 poi-3.17.jar
//第一步創(chuàng )建一個(gè)webbook,對應一個(gè)Excel文件 HSSFWorkbook wb=new HSSFWorkbook(); //第二步,在webbook中添加一個(gè)sheet,對應Excel文件中的sheet HSSFSheet sheet=wb.createSheet("食物信息數據"); //第三步,在sheet中添加表頭第0行 HSSFRow row = sheet.createRow(0); //第四步,創(chuàng )建單元格,并設置表頭居中 HSSFCellStyle style = wb.createCellStyle(); style.setAlignment(HorizontalAlignment.CENTER);//居中格式 HSSFCell cell = row.createCell(0); cell.setCellValue("編號"); cell.setCellStyle(style); cell=row.createCell((short)1); cell.setCellValue("名稱(chēng)"); cell.setCellStyle(style); cell=row.createCell((short)2); cell.setCellValue("類(lèi)型"); cell.setCellStyle(style); cell=row.createCell((short)3); cell.setCellValue("單價(jià)"); cell.setCellStyle(style); cell=row.createCell((short)4); cell.setCellValue("庫存"); cell.setCellStyle(style); //第五步,寫(xiě)入實(shí)體數據,從數據庫拿數據 FoodController controller=new FoodController(); List<Foods> foodsList = controller.foodsList(null, null); for (int i = 0; i < foodsList.size(); i++) { //創(chuàng )建單元格,并賦值 row=sheet.createRow(i+1); Foods foods = foodsList.get(i); row.createCell((short)0).setCellValue(foods.getId()); row.createCell((short)1).setCellValue(foods.getName()); row.createCell((short)2).setCellValue(foods.getType()); row.createCell((short)3).setCellValue(foods.getPrice()); row.createCell((short)4).setCellValue(foods.getNum()); } //第六步,下載Excel OutputStream out=null; out=response.getOutputStream(); String fileName="食物信息.xls"; response.setContentType("application/x-=msdownload"); response.setHeader("Content-Disposition", "attachment; filename=" +URLEncoder.encode(fileName, "UTF-8")); wb.write(out);
導出成功后數據成功顯示
到此這篇關(guān)于Java中用POI實(shí)現將數據導出到Excel的文章就介紹到這了,更多相關(guān)java數據導出到Excel內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自本網(wǎng)站內容采集于網(wǎng)絡(luò )互聯(lián)網(wǎng)轉載等其它媒體和分享為主,內容觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如侵犯了原作者的版權,請告知一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容,聯(lián)系我們QQ:712375056,同時(shí)歡迎投稿傳遞力量。
Copyright ? 2009-2022 56dr.com. All Rights Reserved. 特網(wǎng)科技 特網(wǎng)云 版權所有 特網(wǎng)科技 粵ICP備16109289號
域名注冊服務(wù)機構:阿里云計算有限公司(萬(wàn)網(wǎng)) 域名服務(wù)機構:煙臺帝思普網(wǎng)絡(luò )科技有限公司(DNSPod) CDN服務(wù):阿里云計算有限公司 百度云 中國互聯(lián)網(wǎng)舉報中心 增值電信業(yè)務(wù)經(jīng)營(yíng)許可證B2
建議您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流瀏覽器瀏覽本網(wǎng)站