POIエクスポートツールクラス(反射実装)

6342 ワード

POIエクスポートツールクラスは、この間の作業でPOIを利用してExcelエクスポートを実現した機能コードを以下にまとめます.
1.ツールクラスのエクスポート
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse;
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.Font; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook;
import com.gcx_pm.model.ScientificResearch;/**
  • @author shilei
  • @version作成時間:2017年12月28日午後4:53:29
  • クラス説明:POIエクスポートツールクラス*/public class ExportPOIUtils{//パラメータ説明:fileName:ファイル名projects:オブジェクトセットcolumnName:列名keys:mapのkey public static void start_download(HttpServeretResponse response,String fileName,List>projects,String[]columnName,String[]keys)throws IOException{
     //                List>
     List> list=createExcelRecord(projects, keys);
    
     ByteArrayOutputStream os = new ByteArrayOutputStream();
     try {
     	//     Workbook         
     	createWorkBook(list,keys,columnNames).write(os);
     } catch (IOException e) {
     	e.printStackTrace();
     }
     byte[] content = os.toByteArray();
     InputStream is = new ByteArrayInputStream(content);
     //   response  ,        
     response.reset();
     response.setContentType("application/vnd.ms-excel;charset=utf-8");
     response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName + ".xls").getBytes(), "iso-8859-1"));
     ServletOutputStream out = response.getOutputStream();
     BufferedInputStream bis = null;
     BufferedOutputStream bos = null;
     try {
     	bis = new BufferedInputStream(is);
     	bos = new BufferedOutputStream(out);
     	byte[] buff = new byte[2048];
     	int bytesRead;
     	while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
     		bos.write(buff, 0, bytesRead);
     	}
     } catch (final IOException e) {
     	throw e;
     } finally {
     	if (bis != null)
     		bis.close();
     	if (bos != null)
     		bos.close();
     }
    
    } private static List> createExcelRecord(List> projects, String[] keys) { List> listmap = new ArrayList>(); Map map = new HashMap(); map.put(“sheetName”, “sheet”); listmap.add(map); Object project=null; for (int j = 0; j < projects.size(); j++) { project=projects.get(j); Map mapValue = new HashMap(); for(int i=0; i mapValue.put(keys[i], getFieldValueByName(keys[i], project)); }
     	listmap.add(mapValue);
     }
     return listmap;
    
    }/**
  • 反射により属性名から属性値
  • を取得する.
  • /private static Object getFieldValueByName(String fieldName, Object o) { try { String firstLetter = fieldName.substring(0, 1).toUpperCase(); String getter = “get” + firstLetter + fieldName.substring(1); Method method = o.getClass().getMethod(getter, new Class[] {}); Object value = method.invoke(o, new Object[] {}); return value; } catch (Exception e) { e.printStackTrace(); return null; } }/*
  • excelドキュメントオブジェクト
  • を作成する
  • @param keys listにおけるmapのkey配列集合
  • @param columnName excelのカラム名
  • */private static Workbook createWorkBook(List>list,String[]keys,String columnName[])/excelワークブックWorkbook wb=new HSSFWorkbook()//最初のshet(ページ)を作成し、Sheet sheet=wb.createSheet(list.get(0).get("sheetName").toString()と命名);//列幅を手動で設定します.最初のパラメータは、何列目に設定するかを示します.2番目のパラメータは列の幅を表し、nは列の高い画素数である.for(int i=0;i sheet.setColumnWidth((short) i, (short) (35.7 * 150)); }//最初の行Row row=sheetを作成します.createRow((short) 0);//2つのセルフォーマットCellStyle cs=wbを作成します.createCellStyle(); CellStyle cs2 = wb.createCellStyle();//2種類のフォントFont f=wbを作成する.createFont(); Font f2 = wb.createFont();//最初のフォントスタイル(カラム名用)f.setFontHeightInPoints(short)10)を作成します.f.setColor(IndexedColors.BLACK.getIndex()); f.setBoldweight(Font.BOLDWEIGHT_BOLD);//2番目のフォントスタイル(値用)f 2.setFontHeightInPoints(short)10)を作成します.f2.setColor(IndexedColors.BLACK.getIndex());//最初のセルのスタイル(カラム名用)cs.setFont(f)を設定します.cs.setBorderLeft(CellStyle.BORDER_THIN); cs.setBorderRight(CellStyle.BORDER_THIN); cs.setBorderTop(CellStyle.BORDER_THIN); cs.setBorderBottom(CellStyle.BORDER_THIN); cs.setAlignment(CellStyle.ALIGN_CENTER);//2番目のセルのスタイル(値用)cs 2.setFont(f 2)を設定します.cs2.setBorderLeft(CellStyle.BORDER_THIN); cs2.setBorderRight(CellStyle.BORDER_THIN); cs2.setBorderTop(CellStyle.BORDER_THIN); cs2.setBorderBottom(CellStyle.BORDER_THIN); cs2.setAlignment(CellStyle.ALIGN_CENTER);//列名for(int i=0;i Cell cell=row.createCell(i);cell.setCellValue(columnNames[i]); cell.setCellStyle(cs); }//各行の各列の値for(short i=1;i

  • } 2.コントローラ受信
    @RequestMapping(“exportList”) public void exportList(HttpServletResponse response, String ids) {
    String file Name=「個人ファイルリスト」
    List users = sRPService.exportList(ids);
    //列名String columnName[]={"ID"、"名前"、"性別"、"所属部門"、"所属部門"、"メールボックス"、"電話"、"携帯電話"、"学歴/学位"、"専門/専門方向"、"直属上司"、"アカウントロック"};//mapのkey String keys[]={"id"、"userName"、"gender"、"dept"、"unit"、"email"、"tel"、"phone"、"degree"、"major"、"parentName"、"isLocked"};try { ExportPOIUtils.start_download(response, fileName, users,columnNames, keys); } catch (IOException e) { e.printStackTrace(); } } 3.JS//locationを使用する必要があります.href location.href = basePath+"/sRPController/exportList.do?ids="+ids;
    作者:目に見える待合の出所:CSDN原文:https://blog.csdn.net/qq_39028580/article/details/78928219本文は博主のオリジナルの文章で、転載して博文のリンクを添付してください!