jfinal poi

2019獨角獸企業重金招聘Python工程師標準>>> hot3.png

最近項目采用jfinal的項目要對一些excel進行操作,經過考慮采用jfinal+poi,在一些學習,使用后總結并分享一些代碼片段。

導入excel========================================

    protected Workbook workbook =null;protected File file=null;public Object readExcel(UploadFile uploadFile) throws Exception{String path = uploadFile.getUploadPath() + "/" + System.currentTimeMillis() + uploadFile.getFileName();file = new File(path);uploadFile.getFile().renameTo(file);//文件是否存在this.fileCheck(path);//返回workbookworkbook=this.getWorkbook(path);if (validateData()){//解析excel讀取數據,并返回List<Record>List<Record> list = new ArrayList<>();String itemName =null;Date startTime = null;sheet = workbook.getSheetAt(0);int rows = sheet.getLastRowNum();//從0到最后一行非空rowfor (int i = 3; i <= rows; i++) {Row row = sheet.getRow(i);if (row != null) {int cells = row.getLastCellNum();//行中,從0到最后一個非空cellfor (int j = 0; j < cells; j++) {Cell cell = row.getCell(j);if (cell != null) {// 需驗證單元格里面的數據,""也會返回nullswitch (j) {case 0:cell.setCellType(Cell.CELL_TYPE_STRING);itemName= cell.getStringCellValue().trim();break;case 1:if(cell.getCellType()==HSSFCell.CELL_TYPE_NUMERIC && DateUtil.isCellDateFormatted(cell)){//日期也是數值類型startTime = cell.getDateCellValue();}else{throw new Exception("請輸入正確的日期!");}break;default:break;}}Record r = new Record();r.set("itemName", itemName);r.set("startTime", startTime);list.add(r);itemName=null;startTime=null;}workbook.close();file.delete();return list;}return null;};/***  文件常規檢查* @param filePath* @throws FileNotFoundException* @throws FileFormatException*/protected void fileCheck(String filePath) throws FileNotFoundException, FileFormatException {File file = new File(filePath);if (!file.exists()) {throw new FileNotFoundException("傳入的文件不存在:" + filePath);}//03 ,07if (!(filePath.endsWith(".xls") || filePath.endsWith(".xlsx"))) {throw new FileFormatException("傳入的文件不是excel");}}/*** 03或07excel**/protected Workbook getWorkbook(String filePath) throws IOException {Workbook workbook = null;InputStream is = new FileInputStream(filePath);if (filePath.endsWith(".xls")) {workbook = new HSSFWorkbook(is);} else if (filePath.endsWith(".xlsx")) {workbook = new XSSFWorkbook(is);}return workbook;}

導出excel數據===========================================

protected HSSFWorkbook workbook = new HSSFWorkbook();protected HSSFSheet sheet=workbook.createSheet();;protected HSSFRow row;protected HSSFCell cell;protected HSSFCellStyle style ;protected HSSFFont font ;protected List<Record> list;protected String[] headersId;protected String[] headersName;protected String title;protected String fileName;//以流的形式直接輸出excel到客戶端,在controller調用此方法后再次調用 renderNull()此方法即可。
//網上有的是生成excel file 再用renderFile()的方法輸出到客戶端,但我沒有采用這種方法。(注意:這種應該在文件輸出后將文件刪除)
public void writeExcel(List<Record> list,String title,String[] headersId,String[] headersName,String fileName,HttpServletResponse response) throws Exception{this.list=list;this.title=title;this.fileName=fileName;this.headersId=headersId;this.headersName=headersName;this.genTitle();this.genList();this.genFooter();OutputStream outputStream=response.getOutputStream();try {response.setContentType("application/vnd.ms-excel");response.setCharacterEncoding("utf-8");response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(fileName, "utf-8")+".xls");workbook.write(outputStream);outputStream.flush();}catch (Exception e) {throw new Exception("導出失敗!");}finally {outputStream.close();workbook.close();}}//生成title及標題行public void genTitle(){row = sheet.createRow(0);//題頭sheet.addMergedRegion(new CellRangeAddress(0, 2, 0, headersName.length-1));cell = row.createCell(0);cell.setCellStyle(genTitleStyle());cell.setCellValue(title);rowindex+=3;}//生成list數據public void genList(){//表格標題行row = sheet.createRow(rowindex);for(int i=0;i<headersName.length;i++){cell = row.createCell(i);cell.setCellStyle(genH2Style());cell.setCellValue(headersName[i]);}Record r=null;for(int i=0;i<list.size();i++){rowindex++;row = sheet.createRow(rowindex);r = list.get(i);//每行數據for(int j =0;j<headersId.length;j++){cell = row.createCell(j);if(r.get(headersId[j]) instanceof Date)cell.setCellValue(DateUtil.dateToStr((Date)r.get(headersId[j]), "yyyy-MM-dd"));else if(r.get(headersId[j]) instanceof String)cell.setCellValue((String)r.get(headersId[j])==null?"":(String)r.get(headersId[j]));else if(r.get(headersId[j]) instanceof Number)cell.setCellValue(r.get(headersId[j])==null?"":String.valueOf(r.get(headersId[j])));}}rowindex++;}

?

?

?

?

轉載于:https://my.oschina.net/WWWW23223/blog/725664

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/542798.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/542798.shtml
英文地址,請注明出處:http://en.pswp.cn/news/542798.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

python 函數 類 模塊

python基礎語法5函數作用域函數參數函數對象無名函數回調函數函數嵌套類類的創建類的調用初始化方法類的繼承類的定制模塊使用模塊函數 封裝好&#xff0c;進行某種功能 del 函數名(參數)&#xff1a;函數體return 返回值&#xff08;可以沒有return語句&#xff09;作用域 …

activemq nodejs stomp 重連機制_5分鐘優劣分析 Kafka、RabbitMQ、RocketMQ、ActiveMQ消息隊列...

一、資料文檔Kafka&#xff1a;中&#xff0c;有kafka作者自己寫的書&#xff0c;網上資料也有一些。 rabbitmq&#xff1a;有一些不錯的書&#xff0c;網上資料多。 zeromq&#xff1a;少。沒有專門寫zeromq的書&#xff0c;網上的資料多是一些代碼的實現和簡單介紹。 rocketm…

excel保存快捷鍵_干貨 | 快速提高工作效率的電腦快捷鍵!

點擊標題下「藍色微信名」可快速關注隨著科學技術的發展&#xff0c;電腦已經成為每個人生活和工作的必備工具。然而&#xff0c;很多人在使用電腦的過程中非常依賴鼠標&#xff0c;導致雙手需要頻繁離開鍵盤&#xff0c;造成工作間歇中斷&#xff0c;導致用電腦處理工作的效率…

16位的數字高字節和低字節_掩蓋8位數字的較低和較高半字節| 8085微處理器

16位的數字高字節和低字節Problem statement: 問題陳述&#xff1a; To mask lower and higher nibble of 8-bit number using 8085 Microprocessor. 使用8085微處理器掩蓋8位數字的較低和較高半字節。 Algorithm: 算法&#xff1a; Load the content of accumulator A with…

釘釘 ISV 應用開發的一些心得

1. 背景 前段時間從前到后完整地做完了一個簡單的釘釘上的 ISV 應用 —— 猿活動。 最開始想做這么一個小工具&#xff0c;是想到&#xff0c;平時部門中經常會組織一些分享活動&#xff0c;但是這些分享活動卻沒有一個比較直觀的“站點”來記錄一次又一次的&#xff0c;很多人…

mcq 隊列_MCQ | 8086微處理器中的字符串操作指令

mcq 隊列Question 1: 問題1&#xff1a; A string is a collection of characters. Each Character is an of byte length which is stored at successive locations. In the 8086 microprocessor, which characters are considered in the string? 字符串是字符的集合。 每…

python 編碼 解碼 讀寫文件

python基礎語法6編碼解碼encode編碼與decode解碼讀寫文件編碼解碼 計算機是以二進制&#xff08;0或1&#xff09;存儲的&#xff0c;以字節為單位&#xff0c;1byte8bit&#xff0c;1KB1024B&#xff1b;1MB1024KB&#xff1b;1GB1024MB 編碼表&#xff1a;ASCII碼&#xff0…

電腦如何設置不休眠_電腦休眠了卻沒法喚醒?設置一下就好!

關注全新【HP惠課廳】&#xff0c;惠普消費新品全知曉逐步復工&#xff0c;辦公室環境又漸漸熟悉了起來午休外出吃飯、忙里偷閑散步、下班不想關電腦……隨手就把電腦休眠了開機也快&#xff0c;網頁和工作內容也不會被關掉休眠功能是挺好用的可有時候&#xff0c;無論怎么點開…

node+bower+gulp+webpack初見

2019獨角獸企業重金招聘Python工程師標準>>> node node模塊管理是通過NPM&#xff08;即 Node Package Manage&#xff0c;是 NodeJS 模塊管理工具&#xff09;來處理各模塊之間的依賴。NPM按樹狀結構來管理的&#xff0c;支持某模塊的不同版本。 [前提是本機已安裝…

Java LinkedList公共布爾boolean offerFirst(Object o)方法(帶示例)

LinkedList公共布爾布爾offerFirst(Object o)方法 (LinkedList public boolean offerFirst(Object o) method) This method is available in package java.util.LinkedList.offerFirst(Object o). 軟件包java.util.LinkedList.offerFirst(Object o)中提供了此方法。 This metho…

hbuilder php mysql_xampp本地服務器+HBuilder配置php環境

HBuilder配置PHP環境&#xff1a;下載&#xff0c;運行HBuilder編輯器打開右側小窗口&#xff0c;點擊設置圖標—>設置web服務器—>外置web服務器輸入你想要瀏覽器運行的URL&#xff0c;點擊兩個確定&#xff0c;再重新點擊設置web服務器&#xff0c;選擇PHP類文件(選擇之…

百度地圖手機和電腦不一致_你可能不知道的電腦手機冷知識

各位好久不見呀&#xff0c;自科部科科又回來了&#xff01;平時我們經常使用電腦&#xff0c;你可能以為你對電腦和手機了如指掌&#xff0c;然而下面的冷知識你知道多少個&#xff1f;01一臺電腦可以有多個桌面如果你熟練的使用多個桌面這個技巧那么就可以躲著家長領導偷懶了…

嵌套字典|python_Python | 如果不是,則使用嵌套,根據銷售額計算折扣

嵌套字典|pythonInput same amount and calculate discount based on the amount and given discount rate in Python. 輸入相同的金額&#xff0c;并根據Python中的金額和給定的折扣率計算折扣。 The discount rates are: 折扣率是&#xff1a; Amount Discount0-5000…

RHEL 7 中 systemctl 的用法(替代service 和 chkconfig)

2019獨角獸企業重金招聘Python工程師標準>>> 1、systemctl是RHEL 7 的服務管理工具中主要的工具&#xff0c;它融合之前service和chkconfig的功能于一體。可以使用它永久性或只在當前會話中啟用/禁用服務。 systemctl可以列出正在運行的服務狀態&#xff0c;如圖&am…

python實戰——發郵件

from email import encoders#負責編碼 from email.header import Header#負責處理郵件頭 from email.mime.text import MIMEText#構造郵件內容 from email.utils import parseaddr, formataddr#將輸入內容格式化 import smtplib#發送郵件模塊def _format_addr(s):#處理格式化文…

js 刷新div_vue.js備忘記錄(五) vue-router

如果我們采用SPA(單網頁應用)的設計方式,服務器會把前端文件一次性發過來,前端通過監聽url的改變,選擇展示那些內容,也就是前端路由一. 如何改變url但是頁面不刷新?方式一: 改變哈希值hash比如,我們隨便找一個網頁我們在瀏覽器控制臺輸入發現網站的url有了些改變查看network卻…

css div撐滿窗口高度_如何使用CSS將div的高度設置為窗口的100%?

css div撐滿窗口高度Introduction: 介紹&#xff1a; Hello there developers! Well, certainly if you are reading this article then that means that you have run into some trouble while creating your web page or website and if you are a beginner in this field, …

.net core image怎么保存_輕量級Vue圖片上傳插件——Vue-core-image-Upload

介紹vue-core-image-upload 是一款輕量級的 Vue.js 上傳插件&#xff0c;它可以支持的圖片的上傳&#xff0c;裁剪&#xff0c;壓縮。它同樣也支持在移動端的圖片處理&#xff0c;它定義了諸多上傳周期&#xff0c;你可以自由的進行流程控制。Githubhttps://github.com/Vanthin…

mysql確認半同步命令_怎么判斷mysql是否是半同步復制

AFTER_COMMIT(5.6默認值)master將每個事務寫入binlog ,傳遞到slave 刷新到磁盤(relay log)&#xff0c;同時主庫提交事務。master等待slave 反饋收到relay log&#xff0c;只有收到ACK后master才將commit OK結果反饋給客戶端。AFTER_SYNC(5.7默認值&#xff0c;但5.6中無此模式…

stl iterator_在C ++ STL中使用const_iterator訪問字符列表的元素

stl iteratorIn this example, we are declaring a character list and pushing the characters from A to Z using a for loop and push_back() function and then accessing the elements using const_iterator. 在此示例中&#xff0c;我們聲明一個字符列表&#xff0c;并使…