Java是一種面向?qū)ο蟮木幊陶Z(yǔ)言,非常流行和強(qiáng)大。它提供了許多工具和庫(kù),使得它能夠輕松地讀取和寫入Excel文件(.xls和.xlsx)
讀取Excel文件非常簡(jiǎn)單,只需要使用一些Java類庫(kù),如POI等。
import java.io.File; import java.io.FileInputStream; 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 ReadExcel { public static void main(String[] args) { try { FileInputStream excelFile = new FileInputStream(new File("example.xlsx")); Workbook workbook = new XSSFWorkbook(excelFile); //創(chuàng)建輸入流 Sheet datatypeSheet = workbook.getSheetAt(0); for (Row currentRow : datatypeSheet) { for (Cell currentCell : currentRow) { System.out.print(currentCell.getStringCellValue() + " "); //獲取單元格內(nèi)容并輸出 } System.out.println(); } } catch (IOException e) { e.printStackTrace(); } } }
寫入Excel文件也很容易,只是稍微有些不同。以下是一個(gè)例子:
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 WriteExcel { public static void main(String[] args) { try { Workbook workbook = new XSSFWorkbook(); //創(chuàng)建Workbook對(duì)象 Sheet sheet = workbook.createSheet("New Sheet"); // 創(chuàng)建工作表 Row row = sheet.createRow(0); // 創(chuàng)建行 Cell cell1 = row.createCell(0); // 創(chuàng)建單元格 cell1.setCellValue("Hello"); Cell cell2 = row.createCell(1); cell2.setCellValue("World"); FileOutputStream outputStream = new FileOutputStream("example.xlsx"); workbook.write(outputStream); // 將數(shù)據(jù)寫入文件 workbook.close(); } catch (IOException e) { e.printStackTrace(); } } }
以上代碼可以在Java中讀取和寫入Excel文件(.xls和.xlsx)。請(qǐng)確保導(dǎo)入正確的庫(kù)來(lái)使這些代碼工作。