经常接到好多导出excel文件的需求,各式各样。
之前一直用原生的poi来进行操作,每次都要写很多重复的代码,基于此,所以就想简单的封装一下,不至于每次都需要重复定义很多XSSFWorkbook,XSSFSheet之类的变量
本人菜鸟,命名基本是乱来的,囧。
由于我用到的导出通常都是一个List<Map>导成列表,所以做的比较简单,适用性不广。
基本抽象模板类:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FileExistsException;
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.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public abstract class ExportModel {
private String[] tital;
private String[] content;
private Integer[] wides;
private String xlsname;
private String sheetname;
private String dirname;
private Workbook book;
public ExportModel() {
setTital();
setContent();
setWides();
}
/**
* 设置文档首行标题名称
*/
public abstract void setTital();
/**
* 设置文档内容所对应的Map中的key值
*/
public abstract void setContent();
/**
* 设置文档每一列的宽度
*/
public abstract void setWides();
public String[] getTital() {
return tital;
}
public String[] getContent() {
return content;
}
public Integer[] getWides() {
return wides;
}
public void setTital(String[] tital) {
this.tital = tital;
}
public void setContent(String[] content) {
this.content = content;
}
public void setWides(Integer[] wides) {
this.wides = wides;
}
public String getXlsname() {
return xlsname;
}
public void setXlsname(String xlsname) {
this.xlsname = xlsname;
}
public String getSheetname() {
return sheetname;
}
public void setSheetname(String sheetname) {
this.sheetname = sheetname;
}
public String getDirname() {
return dirname;
}
public void setDirname(String dirname) {
this.dirname = dirname;
}
/**
* 获取导出文件地址
* @param type 文件类型
* @return 文件名称
* @throws IOException
*/
private String getExportFile(int type) throws IOException {
assertNotNull(dirname, "导出文件出错,未指定导出文件夹!出现此错误可能是您没有使用setDirname的方法导致.");
assertNotNull(xlsname, "导出文件出错,未指定xls文件名称!出现此错误可能是您没有使用setXlsname的方法导致.");
if(type == EXPORT_XLSX && !xlsname.endsWith(".xlsx")) {
xlsname += ".xlsx";
} else if(type == EXPORT_XLS && !xlsname.endsWith(".xls")) {
xlsname += ".xls";
}
String rootPath = getRootPath();
String dirpath = rootPath + BASE_EXPORT_PATH + File.separator + dirname + File.separator;
File dir = new File(dirpath);
if(!dir.isDirectory())
if(!dir.mkdir()) {
throw new IOException("创建目录失败:"+dir.getAbsolutePath());
}
String path = rootPath + BASE_EXPORT_PATH + File.separator + dirname + File.separator + xlsname;
//path = "D:\\"+xlsname;
return path;
}
/**
* 检查基本的内容设置是否正确
*/
public void checkContent() {
assertNotNull(tital, "导出文件出错,标题不能为空!出现此错误可能是您没有使用setTital的方法导致.");
assertNotNull(content, "导出文件出错,内容不能为空!出现此错误可能是您没有使用setContent的方法导致.");
if(sheetname == null) {
sheetname = "sheet1";
}
}
/**
* 按excel2007格式生成一个sheet
* @param array 需要导出的内容
*/
public void generateSheetXSSF(List<Map<String, Object>> array) {
checkContent();
if(book == null)
book = new XSSFWorkbook();
if(!(book instanceof XSSFWorkbook))
throw new IllegalArgumentException("错误的导出模式。");
XSSFSheet sheet = (XSSFSheet)book.createSheet(sheetname);
XSSFRow curRow = null;
int titalLen = tital.length;
int contentLen = content.length;
int size = array.size();
int loop = 0;
curRow = sheet.createRow(loop++);
CellStyle titalStyle = generateTitalStyle();
for(int i = 0; i < titalLen; i++) {
String val = tital[i];
curRow.createCell(i).setCellValue(val);
curRow.getCell(i).setCellStyle(titalStyle);
}
if(wides != null) {
int wlen = wides.length;
for(int i = 0; i < wlen; i++) {
sheet.setColumnWidth(i, wides[i].shortValue());
}
}
for(int i = 0; i < size; i++) {
Map<String, Object> map = array.get(i);
curRow = sheet.createRow(loop++);
for(int j = 0; j < contentLen; j++) {
curRow.createCell(j).setCellValue(convertStr(map.get(content[j])));
}
}
}
/**
* 按excel2003格式生成一个sheet
* @param array 需要导出的内容
*/
public void generateSheetHSSF(List<Map<String, Object>> array) {
checkContent();
if(book == null)
book = new HSSFWorkbook();
if(!(book instanceof HSSFWorkbook))
throw new IllegalArgumentException("错误的导出模式。");
HSSFSheet sheet = (HSSFSheet)book.createSheet(sheetname);
HSSFRow curRow = null;
int titalLen = tital.length;
int contentLen = content.length;
int size = array.size();
int loop = 0;
curRow = sheet.createRow(loop++);
CellStyle titalStyle = generateTitalStyle();
for(int i = 0; i < titalLen; i++) {
String val = tital[i];
curRow.createCell(i).setCellValue(val);
// 设置字体为粗体
curRow.getCell(i).setCellStyle(titalStyle);
}
if(wides != null) {
int wlen = wides.length;
for(int i = 0; i < wlen; i++) {
sheet.setColumnWidth(i, wides[i].shortValue());
}
}
for(int i = 0; i < size; i++) {
Map<String, Object> map = array.get(i);
curRow = sheet.createRow(loop++);
for(int j = 0; j < contentLen; j++) {
curRow.createCell(j).setCellValue(convertStr(map.get(content[j])));
}
}
}
/**
* 使用默认导出类型(如果文件已存在则删除)将文件持久化至硬盘
* @throws IOException
*/
public void exportToFile() throws IOException {
exportToFile(EXPORT_UPDATE);
}
/**
* 将文件持久化至硬盘
* @param export_type 导出类型
* @throws IOException
*/
public void exportToFile(int export_type) throws IOException {
assertNotNull(book, "导出失败,原因:内容为空。");
String filename = getExportFile(export_type);
File exportFile = new File(filename);
if(exportFile.exists())
if(export_type == EXPORT_RETURN) {
throw new FileExistsException(exportFile);
} else if(export_type == EXPORT_UPDATE) {
if(!exportFile.delete()) {
throw new FileExistsException(exportFile);
}
}
exportFile.createNewFile();
FileOutputStream out = new FileOutputStream(exportFile);
out.flush();
book.write(out);
out.close();
}
/**
* Object 转 String 型
* @param target
*/
private static String convertStr(Object target) {
if(target == null)
return "";
return target + "";
}
/**
* 判断变量是否为空
* @param target 目标变量
* @param message 如果为空则抛出异常的内容
* @throws IllegalArgumentException
*/
private static void assertNotNull(Object target, String message) {
if(target == null)
throw new IllegalArgumentException(message);
}
/**
* 获取导出文件的根目录,这里我选的根目录为/WebRoot/
*/
private static String getRootPath() {
String path = ExportModel.class.getClassLoader().getResource("").getPath();
return path.substring(0, path.indexOf("WEB-INF"));
}
/**
* 使用默认的导出方式(文件存在则删除原文件)导出至excel2003
* @param array 需要导出的数据
* @return 文件名
* @throws IOException
*/
public String exportToXls(List<Map<String, Object>> array) throws IOException {
exportToXls(array, EXPORT_UPDATE);
return xlsname;
}
/**
* 导出至excel2003
* @param array 需要导出的数据
* @param export_type 导出方式
* @return 文件名
* @throws IOException
*/
public String exportToXls(List<Map<String, Object>> array, int export_type) throws IOException {
generateSheetHSSF(array);
exportToFile(export_type);
return xlsname;
}
/**
* 使用默认的导出方式(文件存在则删除原文件)导出至excel2007
* @param array 需要导出的数据
* @return 文件名
* @throws IOException
*/
public String exportToXlsx(List<Map<String, Object>> array) throws IOException {
exportToXlsx(array, EXPORT_UPDATE);
return xlsname;
}
/**
* 导出至excel2007
* @param array 需要导出的数据
* @param export_type 导出方式
* @return 文件名
* @throws IOException
*/
public String exportToXlsx(List<Map<String, Object>> array, int export_type) throws IOException {
generateSheetXSSF(array);
exportToFile(export_type);
return xlsname;
}
/**
* 获取标题格式
*/
private CellStyle generateTitalStyle() {
CellStyle style = book.createCellStyle();
Font font = book.createFont();
font.setBoldweight(Font.BOLDWEIGHT_BOLD);
style.setFont(font); // 设置粗体
style.setAlignment(CellStyle.ALIGN_CENTER);// 设置居中
return style;
}
// 导出的文件夹的根目录:WebRoot/export/
private static final String BASE_EXPORT_PATH = "export";
/**
* 如果文件存在,则删除原文件,重新生成
*/
public static final int EXPORT_UPDATE = 0;
/**
* 如果文件存在,则不生成
*/
public static final int EXPORT_RETURN = 1;
/**
* 导出为excel2007文件(.xlsx)
*/
private static final int EXPORT_XLSX = 2;
/**
* 导出为excel2003文件(.xls)
*/
private static final int EXPORT_XLS = 3;
}
使用时可以创建一个模板类继承抽象模板类,并设置标题,内容,以及每行的宽度等,如:
public class DefaultExportModel extends ExportModel{
public DefaultExportModel() {
super();
this.setDirname("default");
}
@Override
public void setTital() {
// 设置标题
// String tital[] = {"tital1", "tital2", "tital3"};
// setTital(tital);
}
@Override
public void setContent() {
// 设置内容
// String content[] = {"content1", "content2", "content3"};
// setContent(content);
}
@Override
public void setWides() {
Integer wides[] = {3500,3500,3500};
setWides(wides);
}
}
下面是测试:
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ExportTest {
/**
* @param args
*/
public static void main(String[] args) {
String tital[] = {"tital1", "tital2", "tital3"};
String content[] = {"content1", "content2", "content3"};
List<Map<String, Object>> array = new ArrayList<Map<String,Object>>();
for(int i=1;i<10;i++){
Map<String, Object> data = new HashMap<String, Object>();
for(String value : content) {
data.put(value, value + "-" + i);
}
array.add(data);
}
ExportModel model = new DefaultExportModel();
model.setTital(tital);// setTital可以在DefaultExportModel中设置
model.setContent(content);// setContent可以在DefaultExportModel中设置
model.setXlsname(System.currentTimeMillis()/1000+".xls");
try {
String xlsname = model.exportToXls(array);
System.out.println(xlsname);
} catch (IOException e) {
e.printStackTrace();
}
}
}