java office 怎樣讀寫Excel文件

小樊
82
2024-08-05 22:17:13

在Java中,可以使用Apache POI庫(kù)來讀寫Excel文件。以下是一個(gè)簡(jiǎn)單的示例代碼,演示如何讀取和寫入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();
        }
    }
}

以上是一個(gè)簡(jiǎn)單的示例,你可以根據(jù)自己的需求修改代碼以滿足具體的需求。希望對(duì)你有幫助。

0