
将二维数组导出为 excel
为了将二维数组写入 excel 文件,可以使用 apache poi 库。以下步骤展示如何实现:
引入 maven 依赖
org.apache.poi poi 3.17 org.apache.poi poi-ooxml 3.17
创建工作簿和工作表
xssfworkbook workbook = new xssfworkbook();
xssfsheet sheet = workbook.createsheet("worksheet");创建表头
xssfrow row = sheet.createrow(0);
for (int i = 0; i < headlist.size(); i++) {
xssfcell cell = row.createcell(i);
cell.setcellvalue(headlist.get(i));
}写入数据
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));
}
}保存文件
xssfworkbook workbook = new xssfworkbook(); workbook.write(new fileoutputstream(file)); workbook.close();
示例代码
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class WriteToExcel {
public static void main(String[] args) {
// 表头测试数据
List headList = new ArrayList<>();
headList.add("昵称");
headList.add("年龄");
// 内容测试数据
List> contentList = getContent();
// 创建工作簿和工作表
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("WorkSheet");
// 设置表头
XSSFRow row = sheet.createRow(0);
for (int i = 0; i < headList.size(); i++) {
XSSFCell cell = row.createCell(i);
cell.setCellValue(headList.get(i));
}
// 设置内容
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));
}
}
// 保存文件
try {
workbook.write(new FileOutputStream("D://work.xls"));
workbook.close();
System.out.println("写入成功");
} catch (IOException e) {
e.printStackTrace();
}
}
protected static List> getContent() {
List> contentList = new ArrayList<>();
List content1 = new ArrayList<>();
content1.add("张三");
content1.add("18");
List content2 = new ArrayList<>();
content2.add("李四");
content2.add("20");
contentList.add(content1);
contentList.add(content2);
return contentList;
}
}










