使用Java 的封裝寫一個包括有read excel 的function 和write excel的 function的Class
时间: 2023-03-30 07:04:18 浏览: 36
好的,我可以回答这个问题。以下是一个使用 Java 封装的包括读取 Excel 和写入 Excel 的函数的类的示例:
```
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
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.xssf.usermodel.XSSFWorkbook;
public class ExcelUtils {
public static void readExcel(String filePath) throws IOException {
FileInputStream inputStream = new FileInputStream(new File(filePath));
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheetAt();
for (Row row : sheet) {
for (Cell cell : row) {
System.out.print(cell.toString() + "\t");
}
System.out.println();
}
workbook.close();
inputStream.close();
}
public static void writeExcel(String filePath, String[][] data) throws IOException {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet();
for (int i = ; i < data.length; i++) {
Row row = sheet.createRow(i);
for (int j = ; j < data[i].length; j++) {
Cell cell = row.createCell(j);
cell.setCellValue(data[i][j]);
}
}
FileOutputStream outputStream = new FileOutputStream(filePath);
workbook.write(outputStream);
workbook.close();
outputStream.close();
}
}
```
这个类包括了两个函数:`readExcel` 和 `writeExcel`。`readExcel` 函数可以读取 Excel 文件并将其内容打印到控制台上,`writeExcel` 函数可以将一个二维字符串数组写入到 Excel 文件中。你可以根据自己的需要修改这个类来满足你的具体需求。