
将二维数组写入excel
问题:如何通过java代码将二维数组写入一个excel文件单元格区域中?
解决方案:
可以使用apache poi组件实现:
立即学习“Java免费学习笔记(深入)”;
- 引入maven依赖
org.apache.poi poi 3.17 org.apache.poi poi-ooxml 3.17
- 封装方法
// 创建sheet页
public static void setsheet(string sheetname) {
workbook = new xssfworkbook();
sheet = workbook.createsheet(sheetname);
}
// 创建表头
public static void createhead(list headlist) {
// 创建表头,也就是第一行
row = sheet.createrow(0);
for (int i = 0; i < headlist.size(); i++) {
cell = row.createcell(i);
cell.setcellvalue(headlist.get(i));
}
}
// 创建表内容
public static void createcontent(list> contentlist) {
// 创建表内容,从第二行开始
for (int i = 0; i < contentlist.size(); i++) {
row = sheet.createrow(i + 1);
for (int j = 0; j < contentlist.get(i).size(); j++) {
row.createcell(j).setcellvalue(contentlist.get(i).get(j));
}
}
}
// 写入文件
public static void writetofile(string filepath) {
file = new file(filepath);
// 将文件保存到指定的位置
try {
workbook.write(new fileoutputstream(file));
system.out.println("写入成功");
workbook.close();
} catch (ioexception e) {
e.printstacktrace();
}
}
- 示例代码
// ... 省略内容 ... // 表头测试数据 ListheadList = new ArrayList<>(); headList.add("昵称"); headList.add("年龄"); List > contentList = getContent();// 内容测试数据 setSheet("WorkSheet"); // 创建sheet页 createHead(headList); // 设置表头 createContent(contentList); // 设置内容 writeToFile("D://work.xls"); // 写入文件










