java使用poi将excel模板写入数据并保存本地的工具类
时间: 2023-09-16 18:13:10 浏览: 148
以下是一个使用POI将Excel模板写入数据并保存本地的工具类示例:
```java
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.CellType;
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;
public class ExcelWriter {
private File file;
private Workbook workbook;
public ExcelWriter(String filePath) throws IOException {
file = new File(filePath);
workbook = WorkbookFactory.create(new FileInputStream(file));
}
public void writeData(String[] sheetNames, Map<String, Object[][]> data) throws IOException {
for (String sheetName : sheetNames) {
Sheet sheet = workbook.getSheet(sheetName);
Object[][] sheetData = data.get(sheetName);
if (sheetData != null) {
int rowIndex = 0;
for (Object[] rowData : sheetData) {
Row row = sheet.getRow(rowIndex);
if (row == null) {
row = sheet.createRow(rowIndex);
}
int columnIndex = 0;
for (Object cellData : rowData) {
Cell cell = row.getCell(columnIndex);
if (cell == null) {
cell = row.createCell(columnIndex);
}
if (cellData != null) {
if (cellData instanceof Number) {
cell.setCellValue(((Number) cellData).doubleValue());
} else if (cellData instanceof String) {
cell.setCellValue((String) cellData);
} else if (cellData instanceof Boolean) {
cell.setCellValue((Boolean) cellData);
} else {
cell.setCellValue(cellData.toString());
}
}
columnIndex++;
}
rowIndex++;
}
}
}
}
public void save() throws IOException {
workbook.write(new FileOutputStream(file));
workbook.close();
}
public static void main(String[] args) throws IOException {
ExcelWriter writer = new ExcelWriter("template.xlsx");
Map<String, Object[][]> data = new HashMap<String, Object[][]>();
data.put("Sheet1", new Object[][] { { "A1", "B1", "C1" }, { "A2", "B2", "C2" } });
data.put("Sheet2", new Object[][] { { "X1", "Y1", "Z1" }, { "X2", "Y2", "Z2" } });
writer.writeData(new String[] { "Sheet1", "Sheet2" }, data);
writer.save();
}
}
```
使用示例:
1. 创建Excel文件"template.xlsx",在Sheet1和Sheet2中分别添加3列数据;
2. 在Java中使用ExcelWriter类读取"template.xlsx"文件;
3. 调用writeData方法向Sheet1和Sheet2中写入新数据;
4. 调用save方法保存更新后的Excel文件。
注意:ExcelWriter类中的写入数据方法是覆盖式写入,即会清空原有数据,再写入新数据。如果需要追加数据,需要修改方法实现。
阅读全文