java 操作excel基本都是jxl和poi工具,poi是阿帕奇组织开发的,jxl我表示不知道具体公司是那个公司或组织开发的。 我在项目中所做功能操作excel,导入和导出excel,以小案例的形式在此记录,方便日后查找和需要的童鞋。 案例:导出excel.
1.搭建环境:导入log4j(日志)、commons.lang(操作字符串工具类)、jxl-report-1.0.jar(jxl导出)、jxl-2.6.10.jar(jxl主jar包)
2.创建模板文件
3.创建类:此案例是javase project,所以在main方法中操作,如果是javaweb,我会在下面给出.
package jps.test; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import jxl.report.ReportEnginer; public class ExcelExportDemo { public static void main(String[] args) { String templateFile ="D://apache-tomcat-7.0.68//wtpwebapps//iKnowledge//demo//test.xls"; String destFile ="D://apache-tomcat-7.0.68//wtpwebapps//iKnowledge//upload//"+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+ ".xls"; Map<String,Object> context = new HashMap<String,Object>(); context.put("alibaba", "阿里巴巴"); context.put("baidu", "百度"); context.put("centen","腾讯"); context.put("aname", "马云"); context.put("bname", "李宏彦"); context.put("tname", "马化腾"); ReportEnginer enginer = new ReportEnginer(); try { //templateFile excel模版,context内容,destfiel生成文件 enginer.excute(templateFile, context, destFile); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
注意,模板必须是.xls文件,否则会报:jxl.read.biff.BiffException: Unable to recognize OLE stream,原因是jxl不支持读取 excel 2007 以上文件(*.xlsx)。只支持 excel 2003 (*.xls)。反正office是向下兼容的,所以改下后缀即可。
4.如果是javaweb项目,我们一般通过配置文件进行配置来读取模板和文件的生成路径。
#excel模板路径 excel_demo.url=D:/apache-tomcat-7.0.68/wtpwebapps/iKnowledge/demo/excel_demo.xls utilization_excel_demo.url=D:/apache-tomcat-7.0.68/wtpwebapps/iKnowledge/demo/utilization_excel_demo.xls classify_demo.url=D:/apache-tomcat-7.0.68/wtpwebapps/iKnowledge/demo/classify_demo.xls #excel生成路径 #excel.url=D:/apache-tomcat-7.0.68/wtpwebapps/iKnowledge/upload/ excel.url=D:/Eclipse/apache-tomcat-7.0.68/wtpwebapps/iKnowledge/upload/
类读取文件:(部分代码略,java如何读取配置文件,百度一下,你就知道了)
/** * 根据模板导出 * @param map * @param response * @param excelname * @return * @throws Exception */ public static String modelexport(Map<String, Object> map,HttpServletResponse response,String excelname,String demoUrl ) throws Exception { String reslut=null; try { ReportEnginer enginer = new ReportEnginer(); enginer.excute(readconfigure.getPropertiesVal(Constant.CONFIGUREURL, demoUrl), map, readconfigure.getPropertiesVal(Constant.CONFIGUREURL, Constant.EXCELURL)+excelname); reslut=Constant.SUCCESS; } catch (Exception e) { Zte_robot_log.error(e); reslut=Constant.FAIL; } return reslut; }