
将二维数组写入excel
问题:如何通过java代码将二维数组写入一个excel文件单元格区域中?
解决方案:
可以使用apache poi组件实现:
立即学习“Java免费学习笔记(深入)”;
<dependency>
<groupid>org.apache.poi</groupid>
<artifactid>poi</artifactid>
<version>3.17</version>
</dependency>
<dependency>
<groupid>org.apache.poi</groupid>
<artifactid>poi-ooxml</artifactid>
<version>3.17</version>
</dependency>// 创建sheet页
public static void setsheet(string sheetname) {
workbook = new xssfworkbook();
sheet = workbook.createsheet(sheetname);
}
// 创建表头
public static void createhead(list<string> 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<list<string>> 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();
}
}// ... 省略内容 ...
// 表头测试数据
List<String> headList = new ArrayList<>();
headList.add("昵称");
headList.add("年龄");
List<List<String>> contentList = getContent();// 内容测试数据
setSheet("WorkSheet"); // 创建sheet页
createHead(headList); // 设置表头
createContent(contentList); // 设置内容
writeToFile("D://work.xls"); // 写入文件
以上就是Java如何将二维数组写入Excel单元格区域?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号