poi匯出資料(需要合併單元格)
import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.math.RoundingMode; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletResponse; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFDataFormat; import org.apache.poi.xssf.usermodel.XSSFRichTextString; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class CreateExcel<T> { public void expExcel(String title, String[] headers,String[] context,Collection<T> dataset, OutputStream out){ exportExcel(title,headers,context,dataset,out,"yyyy/mm/dd"); } public void expExcel(String title, String[] headers,String[] context, Collection<T> dataset, OutputStream out, String pattern){ exportExcel(title,headers,context,dataset,out,pattern); } public void setExcelResponse(HttpServletResponse response,String name,String[] headers,String[] context,Collection<T> dataset){ OutputStream out = null; try { out = response.getOutputStream(); response.reset();// 清空輸出流 response.setHeader("Content-disposition", "attachment; filename=" + new String(name.getBytes("GBK"), "ISO-8859-1") + ".xlsx");// 設定輸出檔案頭 response.setContentType("application/ms-excel;charset=UTF-8");// 定義輸出型別 expExcel(name, headers, context, dataset, out); } catch (IOException e) { e.printStackTrace(); } finally { try { out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void setExcelResponse(HttpServletResponse response,String name,XSSFWorkbook workbook){ OutputStream out = null; try { out = response.getOutputStream(); response.reset();// 清空輸出流 response.setHeader("Content-disposition", "attachment; filename=" + new String(name.getBytes("GBK"), "ISO-8859-1") + ".xlsx");// 設定輸出檔案頭 response.setContentType("application/ms-excel;charset=UTF-8");// 定義輸出型別 workbook.write(out); } catch (IOException e) { e.printStackTrace(); } finally { try { out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private void exportExcel(String title, String[] headers, String[] context, Collection<T> dataset, OutputStream out, String pattern) { // 宣告一個工作薄 XSSFWorkbook workbook = new XSSFWorkbook(); // 生成一個表格 XSSFSheet sheet = workbook.createSheet(title); // 生成一個樣式 XSSFCellStyle style = workbook.createCellStyle(); XSSFCellStyle style2 = workbook.createCellStyle(); XSSFDataFormat format = workbook.createDataFormat(); style2.setDataFormat(format.getFormat("@")); // 產生表格標題行 XSSFRow row = sheet.createRow(0); for (int i = 0; i < headers.length; i++) { XSSFCell cell = row.createCell(i); cell.setCellStyle(style); XSSFRichTextString text = new XSSFRichTextString(headers[i]); cell.setCellValue(text); } // 遍歷集合資料,產生資料行 Iterator<T> it = dataset.iterator(); int index = 0; while (it.hasNext()) { index++; row = sheet.createRow(index); T t = (T) it.next(); for (int i = 0; i < context.length; i++) { XSSFCell cell = row.createCell(i); String fieldName = context[i]; String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); try { Class tCls = t.getClass(); Method getMethod = tCls.getMethod(getMethodName, new Class[] {}); Object value = getMethod.invoke(t, new Object[] {}); // 判斷值的型別後進行強制型別轉換 if(value==null){ continue; }else { getValue(cell,value,pattern,style2); } } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } finally { // 清理資源 } } } try { workbook.write(out); } catch (IOException e) { e.printStackTrace(); } } /** * 獲取時間格式的值 * @param cell * @param value * @param style */ public static void getValue(XSSFCell cell,Object value,XSSFCellStyle style){ getValue(cell,value,"yyyy/MM/dd",style); } /** * 通過反射獲取值 * @param fieldName * @param obj * @param className * @return */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static Object getValueByReflect(String fieldName,Object obj,String className){ String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); try { Class tcls=Class.forName(className); Method getMethod = tcls.getMethod(getMethodName, new Class[] {}); Object value = getMethod.invoke(obj, new Object[] {}); return value; } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /** * 把值寫入excel * @param cell * @param value * @param pattern * @param style */ public static void getValue(XSSFCell cell,Object value,String pattern,XSSFCellStyle style){ String textValue=null; if (value instanceof Date) { Date date = (Date) value; SimpleDateFormat sdf = new SimpleDateFormat(pattern); textValue = sdf.format(date); }else if(value instanceof Double) { double dou=(Double)value; DecimalFormat decimalFormat = new DecimalFormat("#0.0000");//格式化設定 decimalFormat.setRoundingMode(RoundingMode.HALF_UP); textValue=decimalFormat.format(dou); }else { if(value!=null){ textValue = value.toString(); } } if(style!=null){ cell.setCellStyle(style); } if (textValue != null) { Pattern p = Pattern.compile("^\\d+(\\.\\d+)?$"); Matcher matcher = p.matcher(textValue); if (matcher.matches()) { // 是數字當作double處理 cell.setCellValue(Double.parseDouble(textValue)); } else { cell.setCellValue(textValue); } } cell.setCellValue(textValue); } /** * 根據實體欄位轉化對應的實際型別 * @param cell * @param value * @param pattern * @param style */ public static void getActualValue(XSSFCell cell,Object value,String pattern,XSSFCellStyle style){ String textValue=null; if (value instanceof Date) { Date date = (Date) value; SimpleDateFormat sdf = new SimpleDateFormat(pattern); textValue = sdf.format(date); }else if(value instanceof Double) { double dou=(Double)value; DecimalFormat decimalFormat = new DecimalFormat("#0.0000");//格式化設定 decimalFormat.setRoundingMode(RoundingMode.HALF_UP); textValue=decimalFormat.format(dou); }else { if(value!=null){ textValue = value.toString(); } } if(style!=null){ cell.setCellStyle(style); } cell.setCellValue(textValue); } /** * 填充資料(利用反射迴圈填充一行資料) * @param rowNum 行數 * @param sheet sheet頁 * @param style 樣式 * @param obj 資料物件 * @param keyBean 反射的熟悉名(按excel順序) * @param cla 反射的bean * @return */ public static int setValueForExcel(int rowNum, XSSFSheet sheet,XSSFCellStyle style,Object obj,String[] keyBean,@SuppressWarnings("rawtypes") Class cla){ if(obj==null){ return rowNum; } XSSFRow row = sheet.createRow(rowNum); for(int i=0;i<keyBean.length;i++){ Object value=getValueByReflect(keyBean[i], obj, cla.getName()); getValue(row.createCell(i), value, style); } return rowNum; } /** * 填充資料(利用反射迴圈填充一行資料) * @param rowNum 行數 * @param sheet sheet頁 * @param style 樣式 * @param obj 資料物件 * @param keyBean 反射的熟悉名(按excel順序) * @param cla 反射的bean * @return */ public static void setValueForExcel(XSSFRow row,int firCol, XSSFSheet sheet,XSSFCellStyle style,Object obj,String[] keyBean,@SuppressWarnings("rawtypes") Class cla){ for(int i=0;i<keyBean.length;i++){ Object value=getValueByReflect(keyBean[i], obj, cla.getName()); getValue(row.createCell(i+firCol), value, style); } } /** * 當值遇到-1時,變為-(此方法有待修改,可以封裝全面一些) * @param value * @return */ public static Object changeValueByMark(Object value){ try { int val = (int)Double.parseDouble(value.toString()); if (val==-1) { return "-"; } else { return value; } } catch (Exception e) { return value; } } }
對應的service:
@Override public void expExcelAll(String siteNo, String productType, String startDate, String endDate, HttpServletResponse response) { // 宣告一個工作薄 XSSFWorkbook workbook = new XSSFWorkbook(); // 生成一個表格 XSSFSheet sheet = workbook.createSheet("詳細資料"); sheet.setDefaultColumnWidth(20); XSSFCellStyle style = workbook.createCellStyle(); style.setAlignment(XSSFCellStyle.ALIGN_RIGHT); style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); int num=0; //單元格,createCell(i),這裡的i代表單元格是第幾列,CellRangeAddress(firstRow,lastRow,firstCol,lastCol)裡的引數分別表示需要合併的單元格起始行,起始列 XSSFRow firstRow = sheet.createRow(num); CreateExcel.getValue(firstRow.createCell(0),"放款日期",style); sheet.addMergedRegion(new CellRangeAddress(0, 2, 0, 0)); CreateExcel.getValue(firstRow.createCell(1),"合同資訊",style); sheet.addMergedRegion(new CellRangeAddress(0, 1, 1, 15)); CreateExcel.getValue(firstRow.createCell(16),"本次付款資訊",style); sheet.addMergedRegion(new CellRangeAddress(0, 0, 16, 31)); XSSFRow secondRow = sheet.createRow(++num); CreateExcel.getValue(secondRow.createCell(16),"其他收費",style); sheet.addMergedRegion(new CellRangeAddress(1, 1, 16, 30)); CreateExcel.getValue(secondRow.createCell(31),"費用合計",style); sheet.addMergedRegion(new CellRangeAddress(1, 2, 31, 31)); XSSFRow thirdRow = sheet.createRow(++num); CreateExcel.getValue(thirdRow.createCell(1),"借款人",style); CreateExcel.getValue(thirdRow.createCell(2),"合同號",style); CreateExcel.getValue(thirdRow.createCell(3),"分公司",style); CreateExcel.getValue(thirdRow.createCell(4),"是否直銷",style); CreateExcel.getValue(thirdRow.createCell(5),"合作機構",style); CreateExcel.getValue(thirdRow.createCell(6),"貸款型別",style); CreateExcel.getValue(thirdRow.createCell(7),"產品型別",style); CreateExcel.getValue(thirdRow.createCell(8),"還款方式",style); CreateExcel.getValue(thirdRow.createCell(9),"貸款期數",style); CreateExcel.getValue(thirdRow.createCell(10),"客戶主任",style); CreateExcel.getValue(thirdRow.createCell(11),"客戶經理",style); CreateExcel.getValue(thirdRow.createCell(12),"計息本金",style); CreateExcel.getValue(thirdRow.createCell(13),"付款型別",style); CreateExcel.getValue(thirdRow.createCell(14),"付款金額",style); CreateExcel.getValue(thirdRow.createCell(15),"履約保證金",style); CreateExcel.getValue(thirdRow.createCell(16),"考察費",style); CreateExcel.getValue(thirdRow.createCell(17),"GPS費",style); CreateExcel.getValue(thirdRow.createCell(18),"抵押登記費",style); CreateExcel.getValue(thirdRow.createCell(19),"停車費",style); CreateExcel.getValue(thirdRow.createCell(20),"盜搶險",style); CreateExcel.getValue(thirdRow.createCell(21),"刑偵費",style); CreateExcel.getValue(thirdRow.createCell(22),"評估費",style); CreateExcel.getValue(thirdRow.createCell(23),"律師簽證費",style); CreateExcel.getValue(thirdRow.createCell(24),"加急費",style); CreateExcel.getValue(thirdRow.createCell(25),"風險金",style); CreateExcel.getValue(thirdRow.createCell(26),"抵押登記",style); CreateExcel.getValue(thirdRow.createCell(27),"手續費",style); CreateExcel.getValue(thirdRow.createCell(28),"徵信費",style); CreateExcel.getValue(thirdRow.createCell(29),"快遞費",style); CreateExcel.getValue(thirdRow.createCell(30),"其他",style); //單元格里面的值對應的實體bean欄位 String[] keyBean = {"confirmDate","custName","contractNo","siteName","isDirect","cooperation","loanType","productTypeName","paymentTypeName", "totalPhases","customerDirector","customerManager","auditamt","payType","payAmt","lybzjFees","kcFeeS", "gpsFees","dydjFees","tcFees","dqxFees","xzFees","pgFees","lsjzFees","jjFees","kdFees","gzFees","sxFees","zxsxFees","shouldglf","qtdsFees","total"}; List<LoanCountVo> loanCountVos = this.getAllLoanCountsForExport(siteNo, productType, startDate, endDate); for(int i=0;i<loanCountVos.size();i++){ XSSFRow row = sheet.createRow(++num); for(int j=0;j<keyBean.length;j++){ Object value = CreateExcel.getValueByReflect(keyBean[j], loanCountVos.get(i), LoanCountVo.class.getName()); //設定單元格的值 CreateExcel.getActualValue(row.createCell(j), value,"yyyy/MM/dd", style); } } CreateExcel.setExcelResponse(response,"費用類科目自動對賬全部資料",workbook); }
相關推薦
poi匯出資料(需要合併單元格)
import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.Invocation
POI 匯出Excel實現合併單元格以及列自適應寬度
目錄 參考推薦: POI 匯出Excel 1. 合併單元格 POI是apache提供的一個讀寫Excel文件的開源元件,在操作excel時常要合併單元格,合併單元格的方法是: public CellRang
java將資料匯出,帶有合併單元格的excel--jxls技術
jxls技術可以生成各種樣式的報表,非常好用,深深地喜歡上了這個。說起用這個還是比較有意思的,當時專案有個匯出表格的功能,但是沒能合併單元格,客戶不是很滿意,當時專案中大家都說弄不了,我想著自己網上查查吧,就查到了這個,試了一下午完成了,很有成就感哪,哈哈。
apache POI匯出excel檔案 及單元格合併 、樣式的設定
客戶需要從完單物料資訊中到處excel 大概思路: 單擊某一按鈕,觸發請求至後臺,建立輸出流,匯出excel ^_^ 前臺程式碼: (此段程式碼 註釋部分存在一個問題,註釋部分的請求無效,後臺無法響應前臺請求, 引數傳過去了,後臺也接受了,但輸出流沒有輸出,木雞wh
Aspose.Cells 首次使用,用到模版填充資料,合併單元格,換行-https://www.cnblogs.com/gylspx/p/5961070.html
Aspose.Cells 首次使用,用到模版填充資料,合併單元格,換行 Aspose.Cells 首次使用,用到模版填充資料,合併單元格,換行 模版格式,圖格式是最簡單的格式,但實際效果不是這種,實際效果圖如圖2 圖2 ,注意看紅色部分,一對一是正常的,但是有一對多的訂單,就得把前
Java poi匯出設定 Excel某些單元格不可編輯
小白的總結,大神勿噴;需要轉載請說明出處,如果有什麼問題,歡迎留言 一、需求: 1、某一列 、某一行或某些單元格不可編輯,其他列可以編輯 二、期間遇到的問題 1、無法設定成不可編輯 2、設定為不可編輯,匯出後發現所有單元格均不可編輯; 原因:createCell();建立單元格後,單元
【POI框架實戰】——POI匯出Excel時設定單元格型別為數值型別
背 景 最近做的一個ITFIN的專案中,後臺需要用POI實現匯出功能,匯出的資料中有文字格式,也有貨幣格式,所以為了方便在將來匯出的表格中做計算,存放貨幣的單元格需要設定為數值型別。 匯出的Excel的單元格都是文字格式(單元格左上角有個小三
jxl匯出excel(合併單元格)
Demo import java.io.*; import jxl.*; import jxl.format.UnderlineStyle; import jxl.write.*; publicclass CreateXLS { public
Apache POI如何獲取Excel合併單元格的值
/** * 獲取合併單元格的值 * @param sheet * @param row * @param column * @return */ public String getMergedRegionValue(Sheet sheet ,in
PHPexcel匯出_帶合併單元格/邊框背景/_有效果圖_thinkphp
##供稿單位匯出 public function gonggao_excel(){ $color='0xCC000000'; //查詢所有供稿單位 $order='paixu asc,id desc';
Excel 檔案匯出 js-xlsx合併單元格的實現 (vue)
頁面資料如下圖: export default { data() { return { tableData: [],
Excel轉Html(八)--POI-解析獲取合併單元格-按照X-Y座標解析-與handsontable資料展示/儲存一致
public static List<DmFormMergedDto> getMergedCells(Sheet sheet, int rowIndex, int cellIndex, Long formId) { &nbs
POI匯出Excel設定單元格格式2--建立與設定Excel合併單元格
POI建立與設定Excel合併單元格 話不多說上栗子 //準備工作 XSSFWorkbook wb = new XSSFWorkbook(); Sheet sheet = wb.createSheet("sheet1"); XSSFCreationHelper creationHel
POI匯出Excel--合併單元格
package com.test.util; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io
Java匯出Excel表,POI 實現合併單元格以及列自適應寬度
//字型 HSSFFont font = workbook.createFont(); font.setFontName("仿宋_GB2312"); font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//粗體顯示
poi匯出excel時,合併單元格後,求和不正確,即“假”合併
excel中所謂“真假”合併單元格 真合併:我們選擇一段連續的單元格,點選合併,這時候,EXCEL會提示如果合併只會顯示第一個單元格的資料,而且其他單元的的資料也會沒掉. 假合併:如果我們用一個已經合併的單元格,格式刷要合併的單元格,這時候沒有提示資料丟失的.事實上,這時候
poi匯出Excel報表多表頭雙層表頭、合併單元格
效果圖: controller層方法: /** * * 匯出Excel報表 * @param request * @return * */ @RequestMapping("/export")
poi匯出excel 3.14版本合併單元格報錯
poi匯出excel合併單元格的時候 , 執行sheet.addMergedRegion(new CellRangeAddress(rowNumber, (short) rowNumber, 0, (
java poi匯出Excel表,合併單元格
其他參考文章: http://www.cnblogs.com/bmbm/archive/2011/12/08/2342261.html http://www.cnblogs.com/xuyuanjia/p/5886056.html 這是一個struts2的act
java poi 合併單元格
java poi 合併單元格 2017年03月29日 16:39:01 翠煙你懊惱 閱讀數:26561 poi 合併 單元格