如果使用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();
}
}
}
结果:
工具类
市面上有很多开源的工具类,非常的方便,虽然不提倡反复的造轮子,但是再造轮子的过程中,可以让自己提升,下面的链接时笔者自己开发的一个工具类,非常简单,也做了很多注释。希望可以帮到大家。