java生成Excel例項程式碼
工具類程式碼PoiExcelExport如下:
package com.myssm.util.poi; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.Method; import java.net.URLEncoder; import java.text.DecimalFormat; import java.util.List; import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFPalette; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.util.CellRangeAddress; public class PoiExcelExport { HttpServletResponse response; // 檔名 private String fileName ; //檔案儲存路徑 private String fileDir; //sheet名 private String sheetName; //表頭字型 private String titleFontType = "Arial Unicode MS"; //表頭背景色 private String titleBackColor = "C1FBEE"; //表頭字號 private short titleFontSize = 12; //新增自動篩選的列 如 A:M private String address = ""; //正文字型 private String contentFontType = "Arial Unicode MS"; //正文字號 private short contentFontSize = 12; //Float型別資料小數位 private String floatDecimal = ".00"; //Double型別資料小數位 private String doubleDecimal = ".00"; //設定列的公式 private String colFormula[] = null; DecimalFormat floatDecimalFormat=new DecimalFormat(floatDecimal); DecimalFormat doubleDecimalFormat=new DecimalFormat(doubleDecimal); private HSSFWorkbook workbook = null; public PoiExcelExport(String fileDir,String sheetName){ this.fileDir = fileDir; this.sheetName = sheetName; workbook = new HSSFWorkbook(); } public PoiExcelExport(HttpServletResponse response,String fileName,String sheetName){ this.response = response; this.sheetName = sheetName; workbook = new HSSFWorkbook(); } /** * 設定表頭字型. * @param titleFontType */ public void setTitleFontType(String titleFontType) { this.titleFontType = titleFontType; } /** * 設定表頭背景色. * @param titleBackColor 十六進位制 */ public void setTitleBackColor(String titleBackColor) { this.titleBackColor = titleBackColor; } /** * 設定表頭字型大小. * @param titleFontSize */ public void setTitleFontSize(short titleFontSize) { this.titleFontSize = titleFontSize; } /** * 設定表頭自動篩選欄位,如A:AC. * @param address */ public void setAddress(String address) { this.address = address; } /** * 設定正文字型. * @param contentFontType */ public void setContentFontType(String contentFontType) { this.contentFontType = contentFontType; } /** * 設定正文字號. * @param contentFontSize */ public void setContentFontSize(short contentFontSize) { this.contentFontSize = contentFontSize; } /** * 設定float型別資料小數位 預設.00 * @param doubleDecimal 如 ".00" */ public void setDoubleDecimal(String doubleDecimal) { this.doubleDecimal = doubleDecimal; } /** * 設定doubel型別資料小數位 預設.00 * @param floatDecimalFormat 如 ".00 */ public void setFloatDecimalFormat(DecimalFormat floatDecimalFormat) { this.floatDecimalFormat = floatDecimalFormat; } /** * 設定列的公式 * @param colFormula 儲存i-1列的公式 涉及到的行號使用@替換 如
[email protected][email protected] */ public void setColFormula(String[] colFormula) { this.colFormula = colFormula; } /** * 寫excel. * @param titleColumn 對應bean的屬性名 * @param titleName excel要匯出的表名 * @param titleSize 列寬 * @param dataList 資料 */ public void wirteExcel(String titleColumn[],String titleName[],int titleSize[],List<?> dataList){ //新增Worksheet(不新增sheet時生成的xls檔案開啟時會報錯) Sheet sheet = workbook.createSheet(this.sheetName); //新建檔案 OutputStream out = null; try { if(fileDir!=null){ //有檔案路徑 out = new FileOutputStream(fileDir); }else{ //否則,直接寫到輸出流中 out = response.getOutputStream(); fileName = fileName+".xls"; response.setContentType("application/x-msdownload"); response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8")); } //寫入excel的表頭 Row titleNameRow = workbook.getSheet(sheetName).createRow(0); //設定樣式 HSSFCellStyle titleStyle = workbook.createCellStyle(); titleStyle = (HSSFCellStyle) setFontAndBorder(titleStyle, titleFontType, (short) titleFontSize); titleStyle = (HSSFCellStyle) setColor(titleStyle, titleBackColor, (short)10); for(int i = 0;i < titleName.length;i++){ sheet.setColumnWidth(i, titleSize[i]*256); //設定寬度 Cell cell = titleNameRow.createCell(i); cell.setCellStyle(titleStyle); cell.setCellValue(titleName[i].toString()); } //為表頭新增自動篩選 if(!"".equals(address)){ CellRangeAddress c = (CellRangeAddress) CellRangeAddress.valueOf(address); sheet.setAutoFilter(c); } //通過反射獲取資料並寫入到excel中 if(dataList!=null&&dataList.size()>0){ //設定樣式 HSSFCellStyle dataStyle = workbook.createCellStyle(); titleStyle = (HSSFCellStyle) setFontAndBorder(titleStyle, contentFontType, (short) contentFontSize); if(titleColumn.length>0){ for(int rowIndex = 1;rowIndex<=dataList.size();rowIndex++){ Object obj = dataList.get(rowIndex-1); //獲得該物件 Class clsss = obj.getClass(); //獲得該對物件的class例項 Row dataRow = workbook.getSheet(sheetName).createRow(rowIndex); for(int columnIndex = 0;columnIndex<titleColumn.length;columnIndex++){ String title = titleColumn[columnIndex].toString().trim(); if(!"".equals(title)){ //欄位不為空 //使首字母大寫 String UTitle = Character.toUpperCase(title.charAt(0))+ title.substring(1, title.length()); // 使其首字母大寫; String methodName = "get"+UTitle; // 設定要執行的方法 Method method = clsss.getDeclaredMethod(methodName); //獲取返回型別 String returnType = method.getReturnType().getName(); String data = method.invoke(obj)==null?"":method.invoke(obj).toString(); Cell cell = dataRow.createCell(columnIndex); if(data!=null&&!"".equals(data)){ if("int".equals(returnType)){ cell.setCellValue(Integer.parseInt(data)); }else if("long".equals(returnType)){ cell.setCellValue(Long.parseLong(data)); }else if("float".equals(returnType)){ cell.setCellValue(floatDecimalFormat.format(Float.parseFloat(data))); }else if("double".equals(returnType)){ cell.setCellValue(doubleDecimalFormat.format(Double.parseDouble(data))); }else{ cell.setCellValue(data); } } }else{ //欄位為空 檢查該列是否是公式 if(colFormula!=null){ String sixBuf = colFormula[columnIndex].replace("@", (rowIndex+1)+""); Cell cell = dataRow.createCell(columnIndex); cell.setCellFormula(sixBuf.toString()); } } } } } } workbook.write(out); } catch (Exception e) { e.printStackTrace(); } finally { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 將16進位制的顏色程式碼寫入樣式中來設定顏色 * @param style 保證style統一 * @param color 顏色:66FFDD * @param index 索引 8-64 使用時不可重複 * @return */ public CellStyle setColor(CellStyle style,String color,short index){ if(color!=""&&color!=null){ //轉為RGB碼 int r = Integer.parseInt((color.substring(0,2)),16); //轉為16進位制 int g = Integer.parseInt((color.substring(2,4)),16); int b = Integer.parseInt((color.substring(4,6)),16); //自定義cell顏色 HSSFPalette palette = workbook.getCustomPalette(); palette.setColorAtIndex((short)index, (byte) r, (byte) g, (byte) b); style.setFillPattern(CellStyle.SOLID_FOREGROUND); style.setFillForegroundColor(index); } return style; } /** * 設定字型並加外邊框 * @param style 樣式 * @param style 字型名 * @param style 大小 * @return */ public CellStyle setFontAndBorder(CellStyle style,String fontName,short size){ HSSFFont font = workbook.createFont(); font.setFontHeightInPoints(size); font.setFontName(fontName); font.setBold(true); style.setFont(font); style.setBorderBottom(CellStyle.BORDER_THIN); //下邊框 style.setBorderLeft(CellStyle.BORDER_THIN);//左邊框 style.setBorderTop(CellStyle.BORDER_THIN);//上邊框 style.setBorderRight(CellStyle.BORDER_THIN);//右邊框 return style; } /** * 刪除檔案 * @param fileDir * @return */ public boolean deleteExcel(){ boolean flag = false; File file = new File(this.fileDir); // 判斷目錄或檔案是否存在 if (!file.exists()) { // 不存在返回 false return flag; } else { // 判斷是否為檔案 if (file.isFile()) { // 為檔案時呼叫刪除檔案方法 file.delete(); flag = true; } } return flag; } /** * 刪除檔案 * @param fileDir * @return */ public boolean deleteExcel(String path){ boolean flag = false; File file = new File(path); // 判斷目錄或檔案是否存在 if (!file.exists()) { // 不存在返回 false return flag; } else { // 判斷是否為檔案 if (file.isFile()) { // 為檔案時呼叫刪除檔案方法 file.delete(); flag = true; } } return flag; } }
測試如下:
實體bean:
測試類:package com.myssm.util.poi; public class Man { private String name; private int sex; private String idCard; private float salary; public Man(String name, int sex, String idCard, float salary) { super(); this.name = name; this.sex = sex; this.idCard = idCard; this.salary = salary; } public Man() { super(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getSex() { return sex; } public void setSex(int sex) { this.sex = sex; } public String getIdCard() { return idCard; } public void setIdCard(String idCard) { this.idCard = idCard; } public float getSalary() { return salary; } public void setSalary(float salary) { this.salary = salary; } }
package com.myssm.util.poi;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
PoiExcelExport pee = new PoiExcelExport("E:/test.xls","sheet1");
//資料
List<Man> dataList = new ArrayList();
Man man1 = new Man("張三",20,"男",(float)10000.8);
Man man2 = new Man("李四",21,"男",(float)11000.8);
Man man3 = new Man("王五",22,"女",(float)1200.8);
Man man4 = new Man("趙六",23,"男",(float)13000.8);
Man man5 = new Man("田七",24,"男",(float)14000.8);
Man man6 = new Man();
man6.setName("老八");
dataList.add(man1);dataList.add(man2);dataList.add(man3);dataList.add(man4);dataList.add(man5);
dataList.add(man6);
//呼叫
String titleColumn[] = {"name","sex","idCard","salary",""};
String titleName[] = {"姓名","性別","身份證號","月薪","年薪"};
int titleSize[] = {13,13,13,13,13};
//其他設定 set方法可全不呼叫
String colFormula[] = new String[5];
colFormula[4] = "[email protected]*12"; //設定第5列的公式
pee.setColFormula(colFormula);
pee.setAddress("A:D"); //自動篩選
pee.wirteExcel(titleColumn, titleName, titleSize, dataList);
}
}
相關推薦
java生成Excel例項程式碼
工具類程式碼PoiExcelExport如下: package com.myssm.util.poi; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; i
java生成excel表格
1.需求 將從資料庫查詢出來的資料,以報表生成到本地 2實現 import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Date; impo
java生成excel
//判斷程式執行的作業系統String rootPath="";if("\\".equals(File.separator)){//windosFile directory = new File("");//設定為當前資料夾rootPath = directory.getCanonicalP
java生成Excel並存到指定路徑(簡化版本)
之前寫過java生成Excel,然後感覺還不夠方便使用,就重新寫了下方法, 現在只需要呼叫傳參就ok啦, 是不是很方便呢 ? 需要引入的jar包: import java.io.File; import java.io.FileOutputStr
Java生成excel報表檔案
此次簡單的操作將資料從資料庫匯出生成excel報表以及將excel資料匯入資料庫 首先建立資料庫的連線池: package jdbc; import java.io.FileInputStream; import java.sql.Connection; i
java生成excel存放到web-inf
java生成excel存放到web-inf package cn.gov.customs.xls; import java.io.File; import java.io.FileOutputStream; import java.text.SimpleDateFormat; im
JAVA -- 生成Excel 並上傳到 FTP 不生成本地檔案
直接上程式碼 POM.XML 這裡只是主要的jar <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml --> <dependency> <groupId>
java生成Excel時,為某列(單元格)建立下拉框
在做專案時,有時需要批量匯入的功能,通過Excel來進行批量匯入.... 遇到個小問題,希望在Java生成Excel中,有個模板,對於某些單元格,如性別等列,可以通過下拉框的方式來進行為使用者提示。 這樣既讓使用者覺得方便了,而且Excel會自動進行檢查,一旦不是下拉框中的
Java NIO 經典例項程式碼
SelectionKey.OP_ACCEPT —— 接收連線繼續事件,表示伺服器監聽到了客戶連線,伺服器可以接收這個連線了SelectionKey.OP_CONNECT —— 連線就緒事件,表示客戶與伺服器的連線已經建立成功SelectionKey.OP_READ —— 讀就緒事件,表示通道中已經有了可讀的
java 生成excel表傳給前端下載
js部分: var jsonstr=getSearchSel(os); var str = "";//傳引數 for(var i in jsonstr){ if(jsonstr[i]!=""){
java生成excel表格傳給前臺並下載
pom.xml(可根據自己的需要進行依賴的刪減,樓主的依賴有點雜)<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instanc
Java 生成excel筆記
參考 https://blog.csdn.net/u014621859/article/details/54944059 相關jar包下載 連結:https://pan.baidu.com/s/1mIJgRQeXNAVwMBFsOVvNCQ 密碼:3nap &
Java解析Excel例項解析
最近有些配置APN的工作,需要將Excel中的資訊,配置成Android apns-conf.xml中的樣式。 作為一個程式設計師,我怎麼可能一行行的用眼睛看,然後用手去配置了! 於是,我決定利用Apache POI的支援庫,用java程式解析Excel表,
java生成excel圖表
使用java編寫生成excel當中的圖表圖片。 編寫之前需要引入jar包,所需要的jar包:jfreechart-1.0.13.jar jcommon-1.0.16.jar package com.yuanhe.calculator.util;
java 生成excel 支援 xls、xlsx
java小工具專案 最近由於工作需要寫了個小工具專案,用來生產excel,其中參考了poi官網的demo,以及網路上的一些資料。: 引入jar <poi.version>3.17</poi.version> <!--
JAVA POI 應用系列(1)--生成Excel
需要 void system 版本 stream 邊框 模式 格式 字體 POI簡介(官網:http://poi.apache.org/) Apache POI是Apache軟件基金會的開放源碼函式庫,POI提供API給Java程序對Microsoft Office
java 導入json生成excel
導入json到excel 這裏我們使用的是maven項目,給出POM文件作為參考:<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId>
Java通過POI生成Excel
size stat name put work ali short 居中 center import java.io.FileOutputStream; import java.text.SimpleDateFormat; import java.util.ArrayLi
轉帖 Java生成和操作Excel文件
head instance AC 單元格 content 類型 eid 網站 hang JAVA EXCEL API:是一開放源碼項目,通過它Java開發人員可以讀取Excel文件的內容、創建新的Excel文件、更新已經存在的Excel文件。使用該API非Windows操作
Java RMI特性及例項程式碼
RMI (Remote Method Invocation) 1,RMI 採用stubs 和 skeletons 來進行遠端物件(remote object)的通訊。stub 充當遠端物件的客戶端代理,有著和遠端物件相同的遠端介面,遠端物件的呼叫實際是通過呼叫該物件的客戶端代理物件stub來