1.到网上下载有关的jar包
poi-3.7-20101029.jar
2.代码如下:
package util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class ExcelUtil {
/**
* 自动生成excel
* @param <T> //存放的文件路径
* @param source //要显示的数据
* @param col_names 生成的表名
* @param propertys //属性名
*/
public static <T> void generation(String dest,List<T> source,String[] col_names,String[] propertys){
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("应聘人员统计");
//生成第0行,表眉
HSSFRow row0=sheet.createRow(0);
int m=0;
for(String col_name:col_names){
row0.createCell(m++).setCellValue(col_name);
}
//生成数据内容
int i=1;
for (T t:source) {
HSSFRow row1 = sheet.createRow(i++); //相关Index索引都是从0开始算起
int j=0;
for(String p:propertys){
try {
row1.createCell(j++).setCellValue(PropertyUtils.getSimpleProperty(t,p).toString());
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
//生成excel文件
FileOutputStream fOut;
try {
fOut = new FileOutputStream(new File(dest));
workbook.write(fOut);
fOut.flush();
fOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
这样就可以数据库的数据放入到excel中了。