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;
/**
-
Excel 相蜈ウ操作邀サ(小数据量写入<=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);
// 声明一个工作薄
Workbook workBook;
if (file.exists()) {
// 声明一个工作薄
workBook = new HSSFWorkbook(new FileInputStream(file));
} else {
workBook = new HSSFWorkbook();
}
// 生成一个表格
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();
}
}
}