导出数据到Excel表中--用Apache的POI实现简单封装

使用Apache的POI 实现对数据导出到EXCEL表中进行了一个简单的封装,可以通过XML配置文件配置你想导出的信息,以下是这个小工具的代码:

DataImportAndExportTool.java 代码:


package nhu.drugstore.uitl;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
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.hssf.util.HSSFColor;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class DataImportAndExportTool
{
private class Entiy
{
String name;
String text;
String type;
}
private static DataImportAndExportTool tool=new DataImportAndExportTool();
/**
* 空的构造方法
*/
private DataImportAndExportTool()
{
//do nothing
}
/**
*
* 以一个数组方式创建一个标题行 
* @param row
* @param title
*/
private void createTitleRow(HSSFWorkbook workbook,HSSFRow row,String[] title)
{
int length=title.length;
HSSFCellStyle style=workbook.createCellStyle();
HSSFFont font=workbook.createFont();
font.setColor(HSSFColor.BLUE.index);
font.setFontHeightInPoints((short)14);
font.setBoldweight((short)24);
style.setFont(font);
style.setFillBackgroundColor(HSSFColor.YELLOW.index);
for(int i=0;i<length;i++)
{
HSSFCell cell=row.createCell(i);
cell.setCellValue(title);
cell.setCellStyle(style);
}
}
/**
* 解析XML文件
* @param className
* @return
* @throws ParserConfigurationException
* @throws IOException
* @throws SAXException
*/
private List<Entiy> parseXML(String className) throws Exception
{
List<Entiy> list=new ArrayList<Entiy>();
Document doc=DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(this.getClass().getClassLoader().getResourceAsStream("/"+className+".xml"));
NodeList nodeList=doc.getElementsByTagName("property");
Element element;
for(int i=0;i<nodeList.getLength();i++)
{
element=(Element)nodeList.item(i);
Entiy e=new Entiy();
e.name=element.getAttribute("name");
e.text=element.getAttribute("text");
e.type=element.getAttribute("type");
list.add(e);
}
return list;
}
/**
* 创建工作表的标题行
* @param workbook
* @param row
* @param list
*/
private void createTitleRow(HSSFWorkbook workbook,HSSFRow row,List<Entiy> list)
{
HSSFCellStyle style=workbook.createCellStyle();
HSSFFont font=workbook.createFont();
font.setColor(HSSFColor.BLUE.index);
font.setFontHeightInPoints((short)14);
font.setBoldweight((short)24);
style.setFont(font);
style.setFillBackgroundColor(HSSFColor.YELLOW.index);
int i=0;
for(Entiy e:list)
{
HSSFCell cell=row.createCell(i++);
cell.setCellValue(e.text);
cell.setCellStyle(style);
}
}
/**
* 从一个列表中创建出一个工作空间
* @param list
* @param sheetName
* @return
* @throws Exception
*/
public static HSSFWorkbook ExportToExcel(List list,String sheetName) throws Exception
{
Class c=list.get(0).getClass();
String className=c.getSimpleName();
//解析XML文件中的信息到一个列表中
List<Entiy> entiyList=tool.parseXML(className);
//创建一个空工作空间
HSSFWorkbook workbook=new HSSFWorkbook();
//创建一个表
HSSFSheet sheet=workbook.createSheet(sheetName);
//创建标题行
HSSFRow titleRow=sheet.createRow(0);
tool.createTitleRow(workbook, titleRow,entiyList);
/*
* 创建表中的信息
*/
int rowNum=1;
for(int i=0;i<list.size();i++)
{
HSSFRow row=sheet.createRow(rowNum++);
int colNum=0;
for(Entiy e:entiyList)
{
if(e.type.endsWith("String"))
{
row.createCell(colNum++).setCellValue((String)MethodTool.excuteMethod(list.get(i),MethodTool.returnGetMethodName(e.name)));
}
else if("int".equals(e.type)||"java.lang.Integer".equals(e.type))
{
row.createCell(colNum++).setCellValue((Integer)MethodTool.excuteMethod(list.get(i),MethodTool.returnGetMethodName(e.name)));
}
else if("double".equals(e.type)||"java.lang.Double".equals(e.type))
{
row.createCell(colNum++).setCellValue((Double)MethodTool.excuteMethod(list.get(i),MethodTool.returnGetMethodName(e.name)));
}
else if(e.type.endsWith("Date"))
{
row.createCell(colNum++).setCellValue((Date)MethodTool.excuteMethod(list.get(i),MethodTool.returnGetMethodName(e.name)));
}
else if(e.type.endsWith("Calendar"))
{
row.createCell(colNum++).setCellValue((Calendar)MethodTool.excuteMethod(list.get(i),MethodTool.returnGetMethodName(e.name)));
}
else if("boolean".equals(e.type)||"java.lang.Boolean".equals(e.type))
{
row.createCell(colNum++).setCellValue((Double)MethodTool.excuteMethod(list.get(i),MethodTool.returnGetMethodName(e.name)));
}
else
{
throw new Exception("数据类型错误");
}
}
}
return workbook;
}

}


MethodTool.java 代码:

package nhu.drugstore.uitl;
import java.lang.reflect.Method;
/**
* 这是一个用于方法反射的工具类
* 这将运用JDK的反射机制
* @author strive
*
*/
public class MethodTool
{
/**
* 反转一个有返回值的无参方法
* @param object
* @param methodName
* @return
* @throws Exception
*/
public static Object excuteMethod(Object object,String methodName) throws Exception
{
Class c=object.getClass();
Method m=c.getMethod(methodName);
return m.invoke(object);
}
/**
* 反转一个没有返回值的有一个参数的方法
* @param object
* @param methodName
* @param parameter
* @throws Exception
*/
public static void excuteMethod(Object object,String methodName,Object parameter) throws Exception
{
Class c=object.getClass();
Method m=c.getDeclaredMethod(methodName, parameter.getClass());
m.invoke(object,parameter);
}
/**
* 执行一个参数为boolean类型的方法
* @param object
* @param methodName
* @param parameter
* @throws Exception
*/
public static void excuteBoolMethod(Object object,String methodName,boolean parameter) throws Exception
{
Class c=object.getClass();
Method m=c.getDeclaredMethod(methodName,boolean.class);
m.invoke(object,parameter);
}
/**
* 获得一个属性的set方法名
* @param property
* @return
*/
public static String returnSetMethodName(String property)
{
return "set"+Character.toUpperCase(property.charAt(0))+property.substring(1);
}
/**
* 获得一个属性的get方法名
* @param property
* @return
*/
public static String returnGetMethodName(String property)
{
return "get"+Character.toUpperCase(property.charAt(0))+property.substring(1);
}
}



现在做一个测试:


下面是一个hibernate 实体映射类


/

package nhu.drugstore.bean;

/**
* this is a class description a model of Medicine
* only some geter and seter method
* @author strive
* @hibernate.class
*/
public class Medicine
{
/**
* 主键
* @hibernate.id generator-class="native"
*/
private int id;
/**
* 药品名称
* @hibernate.property
* unique="true"
*/
private String name;
/**
* 放药药框
* @hibernate.property
*/
private String ark;
/**
* 条形码
* @hibernate.property
*
*/
private String barCode;
/**
* 功效描述
* @hibernate.property
*/
private String efficacy;
/**
* 进货价格
* @hibernate.property
*/
private double buyPrice;
/**
* 出售价格
* @hibernate.property
*/
private double sellPrice;
/**
* 库存量
* @hibernate.property
*/
private double stockpile;
/**
* 库存不足提示数量
* @hibernate.property
*/
private double cueNumber;
/**
* 打折百分比
* @hibernate.property
*/
private double rebate;
/**
* 提成百分比
* @hibernate.property
*/
private double rakeOff;
/**
* 拼音简查码
* @hibernate.property
*/
private String spellShort;
/**
* 数字简查码
* @hibernate.property
*/
private String numberShort;
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getArk()
{
return ark;
}
public void setArk(String ark)
{
this.ark = ark;
}
public String getBarCode()
{
return barCode;
}
public void setBarCode(String barCode)
{
this.barCode = barCode;
}
public String getEfficacy()
{
return efficacy;
}
public void setEfficacy(String efficacy)
{
this.efficacy = efficacy;
}
public double getBuyPrice()
{
return buyPrice;
}
public void setBuyPrice(double buyPrice)
{
this.buyPrice = buyPrice;
}
public double getSellPrice()
{
return sellPrice;
}
public void setSellPrice(double sellPrice)
{
this.sellPrice = sellPrice;
}
public double getStockpile()
{
return stockpile;
}
public void setStockpile(double stockpile)
{
this.stockpile = stockpile;
}
public double getCueNumber()
{
return cueNumber;
}
public void setCueNumber(double cueNumber)
{
this.cueNumber = cueNumber;
}
public double getRebate()
{
return rebate;
}
public void setRebate(double rebate)
{
this.rebate = rebate;
}
public double getRakeOff()
{
return rakeOff;
}
public void setRakeOff(double rakeOff)
{
this.rakeOff = rakeOff;
}
public String getSpellShort()
{
return spellShort;
}
public void setSpellShort(String spellShort)
{
this.spellShort = spellShort;
}
public String getNumberShort()
{
return numberShort;
}
public void setNumberShort(String numberShort)
{
this.numberShort = numberShort;
}
}



只要在classPath下建一个文件:
里面配置你想导出的字段


Medicine.xml

<?xml version="1.0" encoding="UTF-8"?>
<bean class="nhu.drugstore.bean.Medicine">
<property name="name" text="药品名称" type="String"/>
<property name="ark" text="放药药框" type="String"/>
<property name="barCode" text="条形码" type="String"/>
<property name="buyPrice" text="进货价格" type="double"/>
<property name="stockpile" text="库存量" type="double"/>
<property name="sellPrice" text="出售价格" type="double"/>
<property name="rebate" text="打折百分比" type="double"/>
<property name="efficacy" text="功效描述" type="String"/>
</bean>



就可以导出数据了:

以下是导出数据到EXCEL的应用;
File outputFile=new File("C:/");
OutputStream fOut = new PrintStream(outputFile);
// 把相应的Excel 工作簿存盘
DataImportAndExportTool.ExportToExcel(medicineDao.getAllMedicine(),"药材信息表").write(fOut);
fOut.flush();
// 操作结束,关闭文件
fOut.close();


这样就可以一个Excel表了
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值