用Java写一个Excel的读取和写入,其中Excel表格已存在,用代码实现
时间: 2024-05-10 18:19:45 浏览: 8
好的,这是一个技术问题,我可以回答。您可以使用Apache的POI库来访问和更新Excel文件。以下是一个简单的Java代码示例,用于读取Excel文件中的数据并将其写入新文件。
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
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.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelReaderWriter {
public static void main(String[] args) {
try (FileInputStream file = new FileInputStream(new File("existing_excel.xlsx"));
XSSFWorkbook workbook = (XSSFWorkbook) WorkbookFactory.create(file);
FileOutputStream out = new FileOutputStream(new File("new_excel.xlsx"))) {
// Get first/desired sheet from the workbook
Sheet sheet = workbook.getSheetAt(0);
// Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
// For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
// Check the cell type and format accordingly
switch (cell.getCellType()) {
case NUMERIC:
System.out.print(cell.getNumericCellValue() + "t");
break;
case STRING:
System.out.print(cell.getStringCellValue() + "t");
break;
}
}
System.out.println("");
}
// Write the output to a file
workbook.write(out);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在这个例子中,我们首先打开一个已经存在的Excel文件,然后使用POI库获取第一个Sheet。我们遍历每一行和每个单元格,并根据单元格的类型进行格式化。最后,我们将更新后的数据写入一个新的Excel文件中。