POI 把java项目中的数据信息导入到Excel中,详细操作

来源:互联网 发布:centos mysql启动失败 编辑:程序博客网 时间:2024/06/15 12:34

1

引入两个依赖

<dependency>
 <groupId>org.apache.poi</groupId>
 <artifactId>poi-ooxml</artifactId>
 <version>3.8</version>
</dependency>
<dependency>
 <groupId>org.apache.poi</groupId>
 <artifactId>poi</artifactId>
 <version>3.8</version>
</dependency>

2

//创建Excel工作簿
Workbook wb = new HSSFWorkbook();

//存放Excel的地址
String path = "D://wallet.xls";

//os
OutputStream os = null;
try {
os = new FileOutputStream(path);
// 创建工作表
Sheet sheet = wb.createSheet("获取充值的数据");
sheet.autoSizeColumn(1);
// 创建行
Row row = sheet.createRow(0);
// 设置标题行
String[] header ={ "用户名", "手机号", “吕美贺”};
Cell c = row.createCell(i);
c.setCellValue(header[i]);
}

for (int i = 0; i < list.size(); i++) {
row =sheet.createRow(i+1);
Map<String, Object> map = list.get(i);
Cell cell = row.createCell(0);
           cell.setCellValue(map.get("userName")==null?"":map.get("userName").toString());
           cell = row.createCell(1);
           cell.setCellValue(map.get("userAccount")==null?"":map.get("userAccount").toString());
           cell = row.createCell(2);
           cell.setCellValue(map.get("type")=="0"?"支付宝":(map.get("publicKey")=="1"?"微信":"银行卡");
   
}
// 写到输出流
wb.write(os);
JOptionPane.showMessageDialog(null, "导出数据完成了"+path);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(os != null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}else{
System.out.println("os is null!!!");
}
 }