java 将数据导出至指定模板
时间: 2024-04-29 17:24:20 浏览: 6
Java可以使用POI库来将数据导出至指定模板。以下是一个示例代码,假设我们有一个Excel模板文件template.xlsx,其中第一行为标题,第二行开始为数据,我们需要将数据填充进去并保存为新的Excel文件。
```
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExportDataToTemplate {
public static void main(String[] args) throws IOException {
// 读取模板文件
File templateFile = new File("template.xlsx");
FileInputStream templateInput = new FileInputStream(templateFile);
Workbook templateWorkbook = WorkbookFactory.create(templateInput);
// 获取第一个工作表
Sheet sheet = templateWorkbook.getSheetAt(0);
// 假设我们有一些数据需要填充
Map<String, Object> data = new HashMap<>();
data.put("name", "Tom");
data.put("age", 25);
data.put("gender", "Male");
// 将数据填充到模板中
Row dataRow = sheet.getRow(1);
Cell nameCell = dataRow.getCell(0);
nameCell.setCellValue((String)data.get("name"));
Cell ageCell = dataRow.getCell(1);
ageCell.setCellValue((int)data.get("age"));
Cell genderCell = dataRow.getCell(2);
genderCell.setCellValue((String)data.get("gender"));
// 创建新的Excel文件并保存
File outputFile = new File("output.xlsx");
FileOutputStream output = new FileOutputStream(outputFile);
templateWorkbook.write(output);
// 关闭流
output.close();
templateInput.close();
}
}
```
这个示例只是一个简单的例子,实际上我们可以使用更复杂的模板和数据结构,以及更多的POI API来实现更丰富的导出功能。