java office 怎样读写Excel文件

avatar
作者
筋斗云
阅读量:0

在Java中,可以使用Apache POI库来读写Excel文件。以下是一个简单的示例代码,演示如何读取和写入Excel文件:

  1. 读取Excel文件:
import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException;  public class ReadExcelFile {      public static void main(String[] args) {         try {             FileInputStream file = new FileInputStream("example.xlsx");              Workbook workbook = new XSSFWorkbook(file);             Sheet sheet = workbook.getSheetAt(0);              for (Row row : sheet) {                 for (Cell cell : row) {                     switch (cell.getCellType()) {                         case STRING:                             System.out.print(cell.getStringCellValue() + "\t");                             break;                         case NUMERIC:                             System.out.print(cell.getNumericCellValue() + "\t");                             break;                         case BOOLEAN:                             System.out.print(cell.getBooleanCellValue() + "\t");                             break;                         default:                             System.out.print(" \t");                     }                 }                 System.out.println();             }              workbook.close();             file.close();          } catch (FileNotFoundException e) {             e.printStackTrace();         } catch (IOException e) {             e.printStackTrace();         }     } } 
  1. 写入Excel文件:
import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileOutputStream; import java.io.IOException;  public class WriteExcelFile {      public static void main(String[] args) {         try {             Workbook workbook = new XSSFWorkbook();             Sheet sheet = workbook.createSheet("Sheet1");              Row row = sheet.createRow(0);             Cell cell = row.createCell(0);             cell.setCellValue("Hello");              FileOutputStream fileOut = new FileOutputStream("output.xlsx");             workbook.write(fileOut);              workbook.close();             fileOut.close();          } catch (IOException e) {             e.printStackTrace();         }     } } 

以上是一个简单的示例,你可以根据自己的需求修改代码以满足具体的需求。希望对你有帮助。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!