如何将多个不同类型的集合数据写入到一个sheet中,并且显示各自的表头?
wfauudbj1#
import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class WriteToExcel { public static void main(String[] args) throws IOException { // 创建工作簿 Workbook workbook = new XSSFWorkbook(); // 创建一个新的工作表 Sheet sheet = workbook.createSheet("Data"); // 创建数据 List<List<Object>> data = new ArrayList<>(); data.add(Arrays.asList("Name", "Age", "City")); data.add(Arrays.asList("John", 30, "New York")); data.add(Arrays.asList("Alice", 25, "London")); // 写入数据 writeData(sheet, data, 0, 0); // 创建另一个数据集合 List<List<Object>> anotherData = new ArrayList<>(); anotherData.add(Arrays.asList("ID", "Product", "Price")); anotherData.add(Arrays.asList(1, "Laptop", 1200)); anotherData.add(Arrays.asList(2, "Phone", 800)); // 写入另一个数据集合 writeData(sheet, anotherData, 0, 4); // 保存工作簿到文件 try (FileOutputStream fileOut = new FileOutputStream("data.xlsx")) { workbook.write(fileOut); } // 关闭工作簿 workbook.close(); } // 写入数据到工作表 private static void writeData(Sheet sheet, List<List<Object>> data, int startRow, int startColumn) { for (int i = 0; i < data.size(); i++) { Row row = sheet.getRow(i + startRow); if (row == null) { row = sheet.createRow(i + startRow); } List<Object> rowData = data.get(i); for (int j = 0; j < rowData.size(); j++) { Cell cell = row.getCell(j + startColumn); if (cell == null) { cell = row.createCell(j + startColumn); } cell.setCellValue(rowData.get(j).toString()); } } } }
1条答案
按热度按时间wfauudbj1#