java读写excel_java Workbook 读写excel

packagecom.royan.weakey.platform.common.excel;importcom.google.common.collect.Lists;importcom.sun.xml.internal.ws.api.streaming.XMLStreamReaderFactory;importlombok.extern.slf4j.Slf4j;importorg.apache.poi.hssf.usermodel.HSSFWorkbook;importorg.apache.poi.ss.usermodel.Cell;importorg.apache.poi.ss.usermodel.Row;importorg.apache.poi.ss.usermodel.Sheet;importorg.apache.poi.ss.usermodel.Workbook;importorg.apache.poi.xssf.usermodel.XSSFWorkbook;import java.io.*;import java.util.*;/*** writeExcel*/@Slf4jpublic classWriteExcel {private static final String EXEL_XLS = "xls";private static final String EXEL_XLSX = "xlsx";public static void writeExcel(List dataList, String filePath, Listheader) {

OutputStream out= null;try{/**read excel document*/File file= newFile(filePath);

Workbook workbook= null;if(file.isDirectory()) {//default create .xls

workbook = newHSSFWorkbook();

}else if (file.getName().endsWith(".xls")) {

workbook= newHSSFWorkbook();

}else if (file.getName().endsWith(".xlsx")) {

workbook= newXSSFWorkbook();

}else

throw new Exception("please get .xls .xlsx end or directory,[" + filePath + "]");//if only support single sheet

Sheet sheet = workbook.createSheet("data");//set excel header

Row fisrtRow = sheet.createRow(0);int columnCount =header.size();for (int h = 0; h < columnCount; h++) {

fisrtRow.createCell(h).setCellValue(header.get(h));

}/*** fill up data in excel*/

int i = 1;for(Map data : dataList) {

Row row=sheet.createRow(i);

Object[] arrays=data.values().toArray();for (int j = 0; j < columnCount; j++) {

Object obj=arrays[j];

row.createCell(j).setCellValue(obj!= null ? obj.toString() : "");

}

i++;

}

out= new FileOutputStream(file.isDirectory() ? filePath + "/" + header.get(0) + ".xls": filePath);

workbook.write(out);

}catch(Exception e) {

log.info("exception {}", e);

}finally{try{if (out != null) {

out.flush();

out.close();

}

}catch(IOException o) {

log.info("exception {}", o);

}

log.info("data output success");

}

}public static voidmain(String[] args) {

Map dataMap = new HashMap<>();

dataMap.put("BankName", "BankName");

dataMap.put("Addr", "Addr");

dataMap.put("Phone", "Phone");

Map dataMap1 = new HashMap<>();

dataMap1.put("BankName", "BankName1");

dataMap1.put("Addr", "Addr1");

dataMap1.put("Phone", "Phone1");

List header = new LinkedList<>();

header.add("BankName");

header.add("Addr");

header.add("Phone");

List list = new ArrayList<>();

list.add(dataMap);

list.add(dataMap1);

writeExcel(list,"/Users/caibixiang/workSoftware/log", header);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值