赞
踩
简介:Apache POI 是一个处理Miscrosoft Office各种文件格式的开源项目。简单来说就是,我们可以使用POI在Java程序中对Miscrosoft Office各种文件进行读写操作。
目录
图 1-1 Apache POI应用场景 |
---|
Apache POI应用场景:
|
- package com.sky.test;
-
- import org.apache.poi.xssf.usermodel.XSSFRow;
- import org.apache.poi.xssf.usermodel.XSSFSheet;
- import org.apache.poi.xssf.usermodel.XSSFWorkbook;
-
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
-
- public class POITest {
- public static void main(String[] args) throws IOException {
- write();
- }
-
- /**
- * 通过POI创建Excel文件并且写入文件内容
- */
- public static void write() throws IOException {
- //创建一个Excel文件
- XSSFWorkbook excel = new XSSFWorkbook();
- //创建Excel中的单元测
- XSSFSheet sheet = excel.createSheet("info");
- //在sheet中创建行对象,rownum编号从零开始
- XSSFRow row = sheet.createRow(1);
- //创建单元格并且写入文件内容
- row.createCell(1).setCellValue("姓名");
- row.createCell(2).setCellValue("城市");
- //创建一个新行
- XSSFRow row1 = sheet.createRow(2);
- row1.createCell(1).setCellValue("王宁");
- row1.createCell(2).setCellValue("亳州");
- //创建一个新行
- XSSFRow row2 = sheet.createRow(2);
- row2.createCell(1).setCellValue("王宁");
- row2.createCell(2).setCellValue("亳州");
- //将内存中的Excel表格存储到指定的盘符下面
- FileOutputStream fileOutputStream = new FileOutputStream(new File("D:\\info.xlsx"));
- excel.write(fileOutputStream);
- //关闭资源
- excel.close();
- fileOutputStream.close();
- }
- }

- package com.sky.test;
-
- import org.apache.poi.xssf.usermodel.XSSFRow;
- import org.apache.poi.xssf.usermodel.XSSFSheet;
- import org.apache.poi.xssf.usermodel.XSSFWorkbook;
-
- import java.io.*;
-
- public class POITest {
- public static void main(String[] args) throws IOException {
- read();
- }
-
- /**
- * 通过POI读取Excel文件
- */
- public static void read() throws IOException{
- FileInputStream fileInputStream = new FileInputStream(new File("D:\\info.xlsx"));
- //创建一个Excel对象,用于读取Excle数据
- XSSFWorkbook excel = new XSSFWorkbook(fileInputStream);
- //读取Excel文件中的第一个Sheet页
- XSSFSheet sheet = excel.getSheetAt(0);
- //获取Sheet页中有数据的最后一行
- int lastRowNum = sheet.getLastRowNum();
- for (int i = 1; i <= lastRowNum; i++) {
- //获取某一行
- XSSFRow row = sheet.getRow(i);
- //获取当前行的单元格对象
- String cellValue1 = row.getCell(1).getStringCellValue();
- String cellValue2 = row.getCell(2).getStringCellValue();
- System.out.println(cellValue1 + " " + cellValue2);
- }
- //关闭资源
- excel.close();
- fileInputStream.close();
- }
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。