【java】反射+poi 導出excel

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

反射 導出的數組轉變成對象

private static  Object expexcelMaptobean(Class<?> cobj,Map<String,String> map,int[] expColums,String[] params) throws InstantiationException, IllegalAccessException{Object t=cobj.newInstance();Set<Entry<String, String>> set=map.entrySet();int i=0;for(Entry<String, String> s:set){String field=s.getKey();field=field.substring(0,1).toUpperCase()+field.substring(1);try {Method m = null ;for(Class<?> clazz = cobj; clazz != Object.class ; clazz = clazz.getSuperclass()) {Method[] mehhods= clazz.getDeclaredMethods();for(Method md:mehhods){if(("set"+field).equals(md.getName())){Type[] paramclass=md.getParameterTypes();for(Type paramType:paramclass){String paramval=params[expColums[i]]+"";m =clazz.getDeclaredMethod("set"+field,(Class[])paramclass) ;if(paramType.getTypeName().equals("java.math.BigDecimal") ){boolean isNum = paramval.matches("\\d+(\\.\\d+)?");if(!isNum){m.invoke(t,new BigDecimal(0));}else{m.invoke(t,new BigDecimal(paramval));}}else{m.invoke(t,paramval);}}}}}} catch (Exception e) {e.printStackTrace();}if(expColums[i]>params.length-1){break;}if(i==expColums.length-1 && (params.length>=expColums.length)){break;}i++;}return t;}

測試

public static void main(String[] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {String[] params={"100","10000","ccc","dddd","eeee"};int[] expColums={1,2};Map<String,String> titleMap = new LinkedHashMap<String,String>();titleMap.put("ackAmt", "產品代碼"); titleMap.put("appno", "產品代碼"); Bean f=(Bean )expexcelMaptobean(Bean.class,titleMap,expColums,params);System.out.println(f.getAckAmt());}

導出excel 工具類


import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;public final  class ExportExcel {public static  String saveExpExcelDir; //導出excel保存位置private ExportExcel() {}static{Map<String,String> map = System.getenv();saveExpExcelDir="C:\\Users"+File.separator+map.get("USERNAME")+File.separator+"Desktop"+File.separator+"ccjj";}/**** 工作簿*/private static HSSFWorkbook workbook;/**** sheet*/private static HSSFSheet sheet;/**** 標題行開始位置*/private static final int TITLE_START_POSITION = 0;/**** 時間行開始位置*/private static final int DATEHEAD_START_POSITION = 0;/**** 表頭行開始位置*/private static final int HEAD_START_POSITION = 0;/**** 文本行開始位置*/private static final int CONTENT_START_POSITION = 1;/*** * @param dataList*        對象集合* @param titleMap*        表頭信息(對象屬性名稱->要顯示的標題值)[按順序添加]* @param sheetName*        sheet名稱和表頭值*/public static void excelExport(List<?> dataList, Map<String, String> titleMap, String sheetName,String filepathandname) {initHSSFWorkbook(sheetName);// 初始化workbook//		createTitleRow(titleMap, sheetName);// 標題行//		createDateHeadRow(titleMap);// 時間行createHeadRow(titleMap);// 表頭行createContentRow(dataList, titleMap);// 文本行//		autoSizeColumn(100);//設置自動伸縮try {OutputStream out = new FileOutputStream(filepathandname);workbook.write(out);out.close();}catch (Exception e) {e.printStackTrace();}}/**** * @param sheetName*        sheetName*/private static void initHSSFWorkbook(String sheetName) {workbook = new HSSFWorkbook();sheet = workbook.createSheet(sheetName);}/*** 生成標題(第零行創建)* @param titleMap 對象屬性名稱->表頭顯示名稱* @param sheetName sheet名稱*/private static void createTitleRow(Map<String, String> titleMap, String sheetName) {CellRangeAddress titleRange = new CellRangeAddress(0, 0, 0, titleMap.size() - 1);sheet.addMergedRegion(titleRange);HSSFRow titleRow = sheet.createRow(TITLE_START_POSITION);HSSFCell titleCell = titleRow.createCell(0);titleCell.setCellValue(sheetName);}/*** 創建時間行(第一行創建)* @param titleMap 對象屬性名稱->表頭顯示名稱*/private static void createDateHeadRow(Map<String, String> titleMap) {CellRangeAddress dateRange = new CellRangeAddress(1, 1, 0, titleMap.size() - 1);sheet.addMergedRegion(dateRange);HSSFRow dateRow = sheet.createRow(DATEHEAD_START_POSITION);HSSFCell dateCell = dateRow.createCell(0);   dateCell.setCellValue(new SimpleDateFormat("yyyy年MM月dd日").format(new Date()));}/*** 創建表頭行(第二行創建)* @param titleMap 對象屬性名稱->表頭顯示名稱*/private static void createHeadRow(Map<String, String> titleMap) {// 第1行創建HSSFRow headRow = sheet.createRow(HEAD_START_POSITION);int i = 0;for (String entry : titleMap.keySet()) {HSSFCell headCell = headRow.createCell(i);headCell.setCellValue(titleMap.get(entry));i++;}}/*** * @param dataList 對象數據集合* @param titleMap 表頭信息*/private static void createContentRow(List<?> dataList, Map<String, String> titleMap) {try {int i=0;for (Object obj : dataList) {HSSFRow textRow = sheet.createRow(CONTENT_START_POSITION + i);int j = 0;for (String entry : titleMap.keySet()) {String method = "get" + entry.substring(0, 1).toUpperCase() + entry.substring(1);Method m = null ;for(Class<?> clazz = obj.getClass(); clazz != Object.class ; clazz = clazz.getSuperclass()) {try {    m = clazz.getDeclaredMethod(method, null) ;    } catch (Exception e) {  }}String value = m.invoke(obj, null).toString();HSSFCell textcell = textRow.createCell(j);sheet.setColumnWidth(j, letterCount(value,750,250));textcell.setCellValue(value);j++;}i++;}}catch (Exception e) {}}/*** 自動伸縮列(如非必要,請勿打開此方法,耗內存)* @param size 列數*/private static void autoSizeColumn(Integer size) { for (int j = 0; j < size; j++) {//			sheet.autoSizeColumn(j);sheet.setColumnWidth(j, 256*size+184);}}/**創建文件夾**/public static String createDir(String destDirName){File dir = new File(destDirName);  //        if (!dir.exists()) {  if (!destDirName.endsWith(File.separator)) {  destDirName = destDirName + File.separator;  }dir.mkdirs();//        }return destDirName;  }/**計算內容含有字體個數**/private static int letterCount(String message,int chinese_len,int other_len){if(message ==null){return 1;}Pattern p = Pattern.compile("[\u4E00-\u9FA5]+");  Matcher m = p.matcher(message);  int zm=0;int num=0;int chinese=0;int other=0;char [] ch = message.toCharArray();for(int i=0;i<ch.length;i++){if((ch[i]>='a' && ch[i]<='z') || (ch[i]>='A' && ch[i]<='Z')){zm=zm+1;}else if(ch[i]>47 && ch[i]<58){num=num+1;}if(m.find()){chinese=chinese+m.group(0).length()+1;}else{other=other+1;other=(other-chinese)<=0?1:(other-chinese);}}int totalcount=(chinese*chinese_len)+(zm+num+(other))*other_len;return totalcount;}}

轉載于:https://my.oschina.net/v512345/blog/842016

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

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

相關文章

css設置背景圖片大小_如何使用CSS設置背景圖片大小?

css設置背景圖片大小Introduction: 介紹&#xff1a; As we all know that the images are a very responsive yet very creative way to display your web page or website to the users. The images also play a major role in indulging users to websites or web pages. T…

java gc的特性_Java12新特性 -- 可中斷的G1 Mixed GC

Java 12 中增強了 G1 垃圾收集器關于混合收集集合的處理策略&#xff0c;這節主要介紹在 Java 12 中同時也對 G1垃圾回收器進行了改進&#xff0c;使其能夠在空閑時自動將 Java 堆內存返還給操作系統&#xff0c;這也是 Java 12 中的另外一項重大改進。目前 Java 11 版本中包含…

在Python3中將字符串轉換為字節的最佳方法

To convert a string to bytes, there are more than one way, 要將字符串轉換為字節&#xff0c;有多種方法&#xff0c; Approach 1: use encode() method 方法1&#xff1a;使用encode()方法 test_str "include_help"print(type(test_str))test_bytes test_st…

【Java】PMD規則學習(1) --字符串比較

PMD是一款采用BSD協議發布的Java程序代碼檢查工具。該工具可以做到檢查Java代碼中是否含有未使用的變量、是否含有空的抓取塊、是否含有不必要的對象等。該軟件功能強大&#xff0c;掃描效率高&#xff0c;是Java程序員debug的好幫手。 PMD支持的編輯器包括&#xff1a;JDevelo…

php定義object數據類型,PHP數據類型(4):對象object

//創建一個類class Student{//定義屬性public $name XuGZh;public $age 20;public $sex 男;//定義方法public function getInfo(){//當前對象中訪問自己屬性用偽變量$thisreturn my name:.$this->name..my age:.$this->age..my sex:.$this->sex;}}對象初始化:要創建…

avr計數_使用8位LCD創建計數器| AVR

avr計數This type of counter may be also used in the EVM machines. A counter can be used to count the number of times a button is pressed. It can have many applications. The most widely used counter application is in EVM and also in customer feedback machin…

php將字符變為數字,數字字符怎么轉化為數字 php 怎么將字符轉成數字

java中&#xff0c;String字符串轉化為數字我現在想把一個String字符串轉化為數字&#xff0c; String s"00000123" 我直接使java中String字符串轉化為數字&#xff1a; 轉換為浮點型&#xff1a; 使用Double或者Float的parseDouble或者parseFloat方法進行轉換 Strin…

用U盤作為啟動盤做系統步驟

步驟一&#xff1a;BIOS設置U盤啟動 制作好Win10 U盤系統安裝盤之后&#xff0c;我們需要在電腦的BIOS設置中把第一啟動設備設置為U盤&#xff0c;設置后就可以從我們制作的Win10 U盤系統安裝盤啟動&#xff0c;從而顯示系統安裝界面開始安裝系統。BIOS設置U盤啟動的方法如下&a…

使用tkinter模塊在Python中進行GUI編程

GUI (Graphical User Interface): GUI(圖形用戶界面)&#xff1a; GUI is a simple application which helps the user to interact with the computer or any other electronic device through a graphical icon. This used to perform different tasks on a desktop or lapt…

php輕博客社區視頻教程,輕博客主題 - SEO極致優化的ZBLOG輕博客主題

zblog自適應輕博客主題&#xff0c;簡潔、輕巧、極致優化~QQ群&#xff1a;457320274 (問題反饋以及其他鏈接交換等) 交流社區&#xff1a;https://www.bxiu.net/ (有問題可以求助交流)更新記錄&#xff1a;2021.02.22 v2.8 更新內容&#xff1a;1、新增分類自定義標題&#xf…

Composer學習之————Ubuntu14.04下安裝Composer

下載Composer&#xff1a; curl -sS https://getcomposer.org/installer | php 安裝Composer&#xff1a; /usr/bin/php composer.phar --version 設置全局命令&#xff1a; sudo mv composer.phar /usr/local/bin/composer 查看是否安裝與設置成功&#xff1a; composer -vers…

u盤啟動iso 開源_啟動和維護開源項目

u盤啟動iso 開源Lets talk about how to start an open-source project? The process can be classified as in three phases, 讓我們談談如何啟動一個開源項目&#xff1f; 該過程可以分為三個階段&#xff0c; Individual senses the need of the project: This is the pha…

java如何解決高并發癥,JAVA線上故障緊急處理詳細過程!

鏈接&#xff1a;https://fredal.xin/java-error-check?hmsrtoutiao.io&utm_mediumtoutiao.io&utm_sourcetoutiao.io線上故障主要會包括 CPU、磁盤、內存以及網絡問題&#xff0c;而大多數故障可能會包含不止一個層面的問題&#xff0c;所以進行排查時候盡量四個方面依…

程序員如何談加薪?

如果你對現在公司很滿意&#xff0c;只是覺得薪資太低&#xff0c;那么可以先和你的主管聊聊。 首先&#xff0c;講一講自己最近在工作上的成長&#xff0c;看主管是否認同&#xff1b; 然后&#xff0c;從能力提升角度&#xff0c;向主管要一個更大的發展空間和更大的業務挑戰…

php有多少魔術方法,PHP常用的幾個魔術方法

常用的魔術方法有&#xff1a;__Tostring () __Call() __autoLoad() __ clone() __GET() __SET() __isset() __unset()1.__Tostring()用于定義輸出對象引用時調用常用于打印一些對象的信息必須有返回值eg&#xff1a;有一個persion類Persion per new persion()Echo per; //直接…

python常用語法和示例_使用Python中的示例進行輸入和輸出操作

python常用語法和示例A Program needs to interact with the user to accomplish the desired task; this is done using Input-Output facility. Input means the data entered by the user of the program. In python, we have input() and raw_input ( ) function available…

關于node.js和npm 和nvm_byKL

關于node.js和npm 和nvm Node 是一個服務器端 JavaScript 解釋器&#xff0c;Node 本身運行 V8 JavaScript。V8 JavaScript 引擎是 Google 用于其 Chrome 瀏覽器的底層 JavaScript 引擎。 NPM是隨同NodeJS一起安裝的包管理工具&#xff0c;能解決NodeJS代碼部署上的很多問題&am…

php 查看擴展 代碼,[擴展推薦] 使用 PHP Insights 在終端查看 PHP 項目代碼質量

PHP Insights 是一個由 Nuno Maduro 發布的、可在控制臺進行 PHP 即時質量檢查的拓展包。在項目的 readme 文件中&#xff0c;可以發現 PHP Insights 的主要功能包含&#xff1a;代碼質量 與 代碼風格 分析一個針對于代碼 結構 和 復雜度 的漂亮的預覽界面在 Laravel、Symfon…

航空機票預訂c#代碼_航空公司座位預訂問題的C ++程序

航空機票預訂c#代碼Problem statement: Write a program to assign passengers seats in an airplane. Assume a small airplane with seat numbering as follows: 問題陳述&#xff1a;編寫一個程序來分配飛機上的乘客座位。 假設小型飛機的座位編號如下&#xff1a; 1 A B C…

linux命令之which

which這個命令可以說并不常用&#xff0c;它的作用是查看可執行文件的位置&#xff0c;并返回第一個搜索結果。可執行文件也就是指的某個系統命令&#xff0c;但是這個命令的位置必須是在PATH路徑里存在的。截圖中 &#xff0c;pwd的位置在/bin/pwd,當然&#xff0c;這個路徑是…