1. 程式人生 > >java 使用POI框架進行Excel表格的匯出

java 使用POI框架進行Excel表格的匯出

首先附上程式碼,是對一個複雜集合進行遍歷匯出的,集合的型別是

Map<String,List<Attendance>> testMap = new LinkedHashMap<String,List<Attendance>>();

其中attendance是一個實體類,Map的key是拼接字串,下面直接上程式碼,套用這個模板可以解決大多數Excel匯出問題,且此程式碼的列數也是動態生成的,話不多說,程式碼如下

`package cn.test;
import java.io.FileOutputStream;
import java.text
.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.poi.hssf.usermodel.HSSFCell
; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFFont; 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.hssf.util.HSSFColor; public class Test1 { public static void main(String[] args) throws Exception { //建立測試集 Map<String,List<Attendance>> testMap = new LinkedHashMap<String,List<Attendance>>();
ArrayList<Attendance> list1= new ArrayList<Attendance>(); ArrayList<Attendance> list2= new ArrayList<Attendance>(); Person p1 =new Person(1,"大一","研發部"); Person p2 =new Person(2,"老二","門面部"); Person p3 =new Person(3,"老三","產品部"); Person p4 =new Person(4,"老四","事務部"); Person p5 =new Person(5,"老五","海外部"); Attendance kq1=new Attendance(1,timeFormat(),DayBefore(timeFormat()),"normal"); Attendance kq2=new Attendance(2,timeFormat(),DayAfter(timeFormat()),"normal"); Attendance kq3=new Attendance(3,DayBefore(timeFormat()),DayAfter(timeFormat()),"normal"); list1.add(kq1); list1.add(kq2); list1.add(kq3); list2.add(kq2); list2.add(kq3); testMap.put(p1.toString(),list1); testMap.put(p2.toString(),list2); testMap.put(p3.toString(),list2); testMap.put(p4.toString(),list1); testMap.put(p5.toString(),list1); FileOutputStream output = null; // 宣告一個工作薄 HSSFWorkbook workbook = new HSSFWorkbook(); // 生成一個表格 try{ //頁碼 HSSFSheet sheet = workbook.createSheet("測試統計"); // 設定表格預設列寬度為18個位元組 sheet.setDefaultColumnWidth((short) 18); // 生成一個樣式 HSSFCellStyle style = workbook.createCellStyle(); style.setWrapText(true); // 設定這些樣式 style.setFillForegroundColor(HSSFColor.SKY_BLUE.index); // 生成一個字型 HSSFFont font = workbook.createFont(); font.setColor(HSSFColor.VIOLET.index); font.setFontHeightInPoints((short) 12); font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 把字型應用到當前的樣式 style.setFont(font); HSSFRow row =sheet.createRow(0); //建立person類標題 (row.createCell(0)).setCellValue("姓名"); (row.createCell(1)).setCellValue("部門"); //取得list集合的最大值,建立attendance類標題 int listMaxSize=Math.max(list1.size(),list2.size()); for(int i=1;i<=listMaxSize;i++){ HSSFCell cell = row.createCell(i+1); cell.setCellValue(String.valueOf(i)); } int index=1; Iterator<Entry<String, List<Attendance>>> entries = testMap.entrySet().iterator(); while (entries.hasNext()) { row = sheet.createRow(index); Map.Entry<String, List<Attendance>> entry = entries.next(); //Person資料 String key[] = entry.getKey().split("-"); //由於key是id-name-department的拼接,所以要切分,並且id不用於顯示 (row.createCell(0)).setCellValue(key[1]); (row.createCell(1)).setCellValue(key[2]); //Attendance資料 List<Attendance> alist = entry.getValue(); //填充Attendance類中除AID以外的資料 for(int j=0;j<alist.size();j++){ //因為person的資訊已經佔了兩個cell,所以這裡的需要j+2 HSSFCell cell = row.createCell(j+2); cell.setCellStyle(style); cell.setCellValue("上午:"+alist.get(j).getStartTime() +"\n備註:"+alist.get(j).getNote() +"\n下午:"+alist.get(j).getEndTime()+"\n備註:"+alist.get(j).getNote()); } index++; } // 寫入資料並關閉檔案 output=new FileOutputStream("D:\\result.xls"); workbook.write(output); output.flush(); } catch (Exception e) { System.out.println(e); } finally { if (output != null|| workbook!=null) { try { output.close(); workbook.close(); System.out.println("#######匯出成功########"); } catch (Exception e) { e.printStackTrace(); } } } } /* 獲得現在日期 */ private static String timeFormat(){ return new SimpleDateFormat("HH:mm:ss").format(new Date()); } /* 獲得指定日期的前一天 */ public static String DayBefore(String specifiedDay) { Calendar c = Calendar.getInstance(); Date date = null; try { date = new SimpleDateFormat("HH:mm:ss").parse(specifiedDay); } catch (ParseException e) { e.printStackTrace(); } c.setTime(date); int day = c.get(Calendar.DATE); c.set(Calendar.DATE, day - 1); String dayAfter = new SimpleDateFormat("HH:mm:ss").format(c.getTime()); return dayAfter; } /* 獲得指定日期的後一天 */ public static String DayAfter(String specifiedDay) { Calendar c = Calendar.getInstance(); Date date = null; try { date = new SimpleDateFormat("HH:mm:ss").parse(specifiedDay); } catch (ParseException e) { e.printStackTrace(); } c.setTime(date); int day = c.get(Calendar.DATE); c.set(Calendar.DATE, day + 1); String dayAfter = new SimpleDateFormat("HH:mm:ss").format(c.getTime()); return dayAfter; } }

後來又做一個匯出涉及到表頭的行合併和列合併,下面再附上行列合併的程式碼,值得注意的是,在進行行列合併前,先注意表頭分為幾個層級,然後再進行行合併和列合併程式碼如下 //建立單元格,設定行合併列合併

            HSSFSheet sheet = workbook.createSheet("個人薪酬");//建立單元名
            sheet.addMergedRegion(new CellRangeAddress(0,0,4,9));//橫向合併5-9
            sheet.addMergedRegion(new CellRangeAddress(0,0,11,19));
            sheet.addMergedRegion(new CellRangeAddress(0,0,20,22));
            sheet.addMergedRegion(new CellRangeAddress(0,1,0,0));//縱向:合併第一列的第1行和第2行第
            sheet.addMergedRegion(new CellRangeAddress(0,1,1,1));//縱向:合併第二列的第1行和第2行第
            sheet.addMergedRegion(new CellRangeAddress(0,1,2,2));
            sheet.addMergedRegion(new CellRangeAddress(0,1,3,3));
            sheet.addMergedRegion(new CellRangeAddress(0,1,10,10));
            sheet.addMergedRegion(new CellRangeAddress(0,1,23,23));
            sheet.addMergedRegion(new CellRangeAddress(0,1,24,24));
            sheet.addMergedRegion(new CellRangeAddress(0,1,25,25));
            sheet.addMergedRegion(new CellRangeAddress(0,1,26,26));
            sheet.addMergedRegion(new CellRangeAddress(0,1,27,27));
            //首行
            HSSFRow row = sheet.createRow(0);

            row.createCell(4).setCellStyle(style);
            row.createCell(4).setCellValue("代扣專案");
            row.createCell(11).setCellStyle(style);
            row.createCell(11).setCellValue("福利");
            row.createCell(20).setCellStyle(style);
            row.createCell(20).setCellValue("其他");`

合併後效果大致如圖這裡寫圖片描述
再貼上完整的設定樣式程式碼

HSSFWorkbook workbook = new HSSFWorkbook();//建立一個工作表格
            //設定樣式
            HSSFCellStyle style = workbook.createCellStyle();
            style.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下邊框
            style.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左邊框
            style.setBorderTop(HSSFCellStyle.BORDER_THIN);//上邊框
            style.setBorderRight(HSSFCellStyle.BORDER_THIN);//右邊框
            //style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            //style.setWrapText(true);
            //style.setFillForegroundColor((short) 5);
            style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中
            //設定字型
            HSSFFont font = workbook.createFont();//建立字型格式
            //font.setColor(HSSFColor.VIOLET.index);
            //font.setFontHeightInPoints((short) 6);//設定字型大小
            font.setFontHeight((short) 10);//大小
            font.setFontName("仿宋_GB2312");//字型
            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//粗體顯示

            style.setFont(font);
            //建立單元格,設定行合併列合併
            HSSFSheet sheet = workbook.createSheet("個人薪酬");//建立單元名
            sheet.addMergedRegion(new CellRangeAddress(0,0,4,9));//橫向合併5-9
            sheet.addMergedRegion(new CellRangeAddress(0,0,11,19));
            sheet.addMergedRegion(new CellRangeAddress(0,0,20,22));
            sheet.addMergedRegion(new CellRangeAddress(0,1,0,0));//縱向:合併第一列的第1行和第2行第
            sheet.addMergedRegion(new CellRangeAddress(0,1,1,1));//縱向:合併第二列的第1行和第2行第
            sheet.addMergedRegion(new CellRangeAddress(0,1,2,2));
            sheet.addMergedRegion(new CellRangeAddress(0,1,3,3));
            sheet.addMergedRegion(new CellRangeAddress(0,1,10,10));
            sheet.addMergedRegion(new CellRangeAddress(0,1,23,23));
            sheet.addMergedRegion(new CellRangeAddress(0,1,24,24));
            sheet.addMergedRegion(new CellRangeAddress(0,1,25,25));
            sheet.addMergedRegion(new CellRangeAddress(0,1,26,26));
            sheet.addMergedRegion(new CellRangeAddress(0,1,27,27));
            //首行
            HSSFRow row = sheet.createRow(0);

            row.createCell(4).setCellStyle(style);
            row.createCell(4).setCellValue("代扣專案");
            row.createCell(11).setCellStyle(style);
            row.createCell(11).setCellValue("福利");
            row.createCell(20).setCellStyle(style);
            row.createCell(20).setCellValue("其他");
            //第二行
            HSSFRow row1 = sheet.createRow(1);
            row1.setHeight((short) 800);