在Java中,读取Excel文件与读取Word文件不同,因为Excel文件中有单元格。JDK不提供从Excel文件中读取数据的直接API,因此我们必须切换到第三方库,即ApachePOI。 阿帕奇波伊 是一个开源java库,用于读取和写入Microsoft文档,以便基于Microsoft Office创建和操作各种文件格式。使用POI,用户应该能够对以下文件格式执行创建、修改和显示/读取操作。
例如 ,Java不提供使用excel文件的内置支持,因此我们需要为该工作寻找开源API。ApachePOI提供了Java API,用于根据Office Open XML(OOXML)标准和微软的OLE2标准操作各种文件格式。Apache POI版本在Apache许可证(V2.0)下提供。
编写Excel文件
早些时候,我们介绍了ApachePOI——一种用于与Microsoft Office文档交互的Java API。现在我们将了解如何使用API读取和写入excel文件。
程序: 使用POI编写文件非常简单,包括以下步骤:
- 创建工作簿
- 在工作簿中创建工作表
- 在图纸中创建一行
- 在工作表中添加单元格
- 重复步骤3和4以写入更多数据。
- 关闭输出流。
例子:
JAVA
// Java Program to Illustrate Writing // Data to Excel File using Apache POI // Import statements 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.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; // Main class public class GFG { // Main driver method public static void main(String[] args) { // Blank workbook XSSFWorkbook workbook = new XSSFWorkbook(); // Creating a blank Excel sheet XSSFSheet sheet = workbook.createSheet( "student Details" ); // Creating an empty TreeMap of string and Object][] // type Map<String, Object[]> data = new TreeMap<String, Object[]>(); // Writing data to Object[] // using put() method data.put( "1" , new Object[] { "ID" , "NAME" , "LASTNAME" }); data.put( "2" , new Object[] { 1 , "Pankaj" , "Kumar" }); data.put( "3" , new Object[] { 2 , "Prakashni" , "Yadav" }); data.put( "4" , new Object[] { 3 , "Ayan" , "Mondal" }); data.put( "5" , new Object[] { 4 , "Virat" , "kohli" }); // Iterating over data and writing it to sheet Set<String> keyset = data.keySet(); int rownum = 0 ; for (String key : keyset) { // Creating a new row in the sheet Row row = sheet.createRow(rownum++); Object[] objArr = data.get(key); int cellnum = 0 ; for (Object obj : objArr) { // This line creates a cell in the next // column of that row Cell cell = row.createCell(cellnum++); if (obj instanceof String) cell.setCellValue((String)obj); else if (obj instanceof Integer) cell.setCellValue((Integer)obj); } } // Try block to check for exceptions try { // Writing the workbook FileOutputStream out = new FileOutputStream( new File( "gfgcontribute.xlsx" )); workbook.write(out); // Closing file output connections out.close(); // Console message for successful execution of // program System.out.println( "gfgcontribute.xlsx written successfully on disk." ); } // Catch block to handle exceptions catch (Exception e) { // Display exceptions along with line number // using printStackTrace() method e.printStackTrace(); } } } |
读取Excel文件
程序: 如果我们将excel文件分成几个步骤,那么读取它也非常简单。
- 从excel工作表创建工作簿实例
- 找到想要的床单
- 增量行数
- 迭代一行中的所有单元格
- 重复步骤3和4,直到读取所有数据。
- 关闭输出流。
例子:
JAVA
// Java Program to Illustrate Reading // Data to Excel File Using Apache POI // Import statements import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.FormulaEvaluator; import org.apache.poi.ss.usermodel.Row; // Main class public class GFG { // Main driver method public static void main(String[] args) { // Try block to check fo exceptions try { // Reading file fro local directory FileInputStream file = new FileInputStream( new File( "gfgcontribute.xlsx" )); // Create Workbook instance holding reference to // .xlsx file XSSFWorkbook workbook = new XSSFWorkbook(file); // Get first/desired sheet from the workbook XSSFSheet sheet = workbook.getSheetAt( 0 ); // Iterate through each rows one by one Iterator<Row> rowIterator = sheet.iterator(); // Till there is an element condition holds true 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(); // Checking the cell type and format // accordingly switch (cell.getCellType()) { // Case 1 case Cell.CELL_TYPE_NUMERIC: System.out.print( cell.getNumericCellValue() + "t" ); break ; // Case 2 case Cell.CELL_TYPE_STRING: System.out.print( cell.getStringCellValue() + "t" ); break ; } } System.out.println( "" ); } // Closing file output streams file.close(); } // Catch block to handle exceptions catch (Exception e) { // Display the exception along with line number // using printStackTrace() method e.printStackTrace(); } } } |
输出:
极客们,现在你们一定想知道,如果我们需要在不同的位置读取一个文件,该怎么办,下面的例子解释了这一切。
例1-A:
// Java Program to Read a File From Different Location// Getting file from local directoryprivate static final String FILE_NAME = "C:\Users\pankaj\Desktop\projectOutput\mobilitymodel.xlsx";// Methodpublic static void write() throws IOException, InvalidFormatException { InputStream inp = new FileInputStream(FILE_NAME); Workbook wb = WorkbookFactory.create(inp); Sheet sheet = wb.getSheetAt(0); ........}
例1-B:
// Reading and Writing data to excel file using Apache POI// Via Appending to the Existing File// Getting the path from the local directoryprivate static final String FILE_NAME = "C:\Users\pankaj\Desktop\projectOutput\blo.xlsx";// Methodpublic static void write() throws IOException, InvalidFormatException { InputStream inp = new FileInputStream(FILE_NAME); Workbook wb = WorkbookFactory.create(inp); Sheet sheet = wb.getSheetAt(0); int num = sheet.getLastRowNum(); Row row = sheet.createRow(++num); row.createCell(0).setCellValue("xyz"); ..... .. // Now it will write the output to a file FileOutputStream fileOut = new FileOutputStream(FILE_NAME); wb.write(fileOut); // Closing the file connections fileOut.close();}
本文由 潘卡吉·库马尔 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。