在用Java开发企业项目或者网站时,我们经常对excel进行数据操作,主要有导入导出操作。
这里是使用了excel的工具包,实现对excel操作的抽象化,大大减少编码量:
1、导入excel数据操作:
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
// importXlsx();
importXls();
}
public static void importXlsx() throws FileNotFoundException {
File f = new File("src/resources/test.xlsx");
InputStream inputStream = new FileInputStream(f);
ExcelLogs logs = new ExcelLogs();
Collection<Map> importExcel = ExcelUtil.importExcel(Map.class, inputStream, "yyyy/MM/dd HH:mm:ss", logs, 0);
for (Map m : importExcel) {
System.out.println(m);
}
}
public static void importXls() throws FileNotFoundException {
File f = new File("src/resources/test.xls");
InputStream inputStream = new FileInputStream(f);
ExcelLogs logs = new ExcelLogs();
Collection<Map> importExcel = ExcelUtil.importExcel(Map.class, inputStream, null, logs, 0);
for (Map m : importExcel) {
System.out.println(m);
}
}
我们可以看到只需要通过传递文件流,日志类就可以从excel中读取数据,数据保存在Map中。
2、导出excel操作
@param <T>
* @param headers 表格属性列名数组
* @param dataset 需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的
* javabean属性的数据类型有基本数据类型及String,Date,String[],Double[]
* @param out 与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
*/
public static <T> void exportExcel(Map<String,String> headers, Collection<T> dataset, OutputStream out)