package com.sql.main; import org.apache.poi.hssf.usermodel.; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.usermodel.; import org.apache.poi.ss.util.CellRangeAddress;
import java.io.*; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map;
/**
Écran d'opération Excel (entrée fractionnaire <= 65536) */ public class Excel2003Utils {
private static final int DEFAULT_COLUMN_SIZE =30;
public static void exportExcel(Class cls,String sheetName, List contents,String filePath) { try { File file=new File(filePath); // Déclaration une pièce travail mince Workbook workBook; if (file.exists()) { // Déclaration une pièce travail mince workBook = new HSSFWorkbook(new FileInputStream(file)); } else { workBook = new HSSFWorkbook(); } // Table individuelle générée Sheet sheet = workBook.getSheet(sheetName); if (sheet == null) { sheet = workBook.createSheet(sheetName); }else { // workBook.removeSheetAt(workBook.getSheetIndex(sheetName)); }
//最新Excel列索引, // int lastRowIndex = sheet.getLastRowNum(); // if (lastRowIndex > 0) { // lastRowIndex++; // } int cellCount =0; Row titleRow = sheet.createRow(0); for(Field f : cls.getDeclaredFields()){ String cellName = f.getName(); Cell cell =titleRow.createCell(cellCount); cell.setCellValue(cellName.toUpperCase()); cellCount++; } int lastRowIndex=1; // sheet.setDefaultColumnWidth(DEFAULT_COLUMN_SIZE); for (Object dataRow : contents) { Row row = sheet.createRow(lastRowIndex); Object bean =cls.newInstance(); int cellIndex =0; for(Field f : cls.getDeclaredFields()){ String getMethodName = "get"+f.getName().substring(0, 1).toUpperCase()+f.getName().substring(1); Method getMethod =cls.getMethod(getMethodName, null ); String value = getMethod.invoke(dataRow)==null ? "NULL":getMethod.invoke(dataRow).toString(); Cell cell =row.createCell(cellIndex); cell.setCellValue(value); cellIndex++; } lastRowIndex++; } OutputStream ops = new FileOutputStream(file); workBook.write(ops); ops.flush(); ops.close(); System.out.println("sheet:"+sheetName+" write "+lastRowIndex+" success!"); } catch (Exception e) { e.printStackTrace(); } }
}
Recommended Posts