java生成excel单元格_Java导出数据到excel表格

如果使用POI从Java中导出数据到excel表格只需要非常简单的步骤:

创建一个workbook

我的理解就是新建一个工作空间,即excel文件。

创建一个sheet

这个就是excel中的sheet

创建一个row

顾名思义,一个新的列

创建一个cell

每列中的单元格

往cell里面填充数据

重复3-5

在做这些之前你可能还需要导入相应的依赖

org.apache.poi

poi-ooxml

3.9

Demo

奉上一个简单的Demo,注释里面写的很清楚,相信可以做到一看就懂。

public class ExportDemo {

private static final List userInformationList = Arrays

.asList(new UserInformation("张飞", "三哥@sg.com", 14),

new UserInformation("刘备", "大弟@sg.com", 28),

new UserInformation("关羽", "二哥@sg.com", 27));

private static final String[] titles = {"序号", "用户名", "邮箱", "年龄"};

public static void main(String[] args) {

//创建一个workbook

XSSFWorkbook workbook = new XSSFWorkbook();

//创建一个sheet

XSSFSheet sheet = workbook.createSheet("sheet");

//创建一列

XSSFRow row = null;

//创建一个单元格

XSSFCell cell = null;

try {

//设置标题

row = sheet.createRow(0);

for (int i = 0; i < titles.length; i++) {

//创建单元格

cell = row.createCell(i);

cell.setCellValue(titles[i]);

}

//设置内容

for (int i = 0; i < userInformationList.size(); i++) {

//获取实例

UserInformation userInformation = userInformationList.get(i);

//设置序号

int index = i + 1;

row = sheet.createRow(index);

//将序号内容存入单元格

row.createCell(0).setCellValue(index);

//将用户名内容存入单元格

if (StringUtils.isNotBlank(userInformation.getUsername())) {

row.createCell(1).setCellValue(userInformation.getUsername());

}

//将邮箱内容存入单元格

if (StringUtils.isNotBlank(userInformation.getEmail())) {

row.createCell(2).setCellValue(userInformation.getEmail());

}

//将年龄内容存入单元格

if (null != userInformation.getAge()) {

row.createCell(3).setCellValue(userInformation.getAge());

}

}

FileOutputStream out = new FileOutputStream("h:\\workbook.xls");

try {

workbook.write(out);

out.flush();

out.close();

} catch (IOException e) {

e.printStackTrace();

}

} catch (FileNotFoundException e) {

e.printStackTrace();

}

}

}

结果:

f9e1205b61a4e18205b71a9ae676a672.png

工具类

市面上有很多开源的工具类,非常的方便,虽然不提倡反复的造轮子,但是再造轮子的过程中,可以让自己提升,下面的链接时笔者自己开发的一个工具类,非常简单,也做了很多注释。希望可以帮到大家。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值