Apache POI使用
1.导入坐标
<!-- poi --><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>${poi}</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>${poi}</version></dependency>
2. 测试类
说明:在D盘生成excel文件
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.FileOutputStream;/** 使用POI操作Excel文件* */
public class POITest {public static void write () throws Exception {// 通过POI创建Excel文件XSSFWorkbook excel = new XSSFWorkbook();//excel文件创建一个sheet页XSSFSheet sheet = excel.createSheet("info");//在sheet创建一个行对象,rownum表示从第零行开始XSSFRow row = sheet.createRow(0);//创建单元格并且写入文件内容row.createCell(1).setCellValue("姓名");row.createCell(2).setCellValue("城市");
// 创建一个新行row = sheet.createRow(1);row.createCell(1).setCellValue("张飒");row.createCell(2).setCellValue("成都");
// 创建一个新行row = sheet.createRow(2);row.createCell(1).setCellValue("李四");row.createCell(2).setCellValue("重庆市");// 输出流将内存的excel文件写入到磁盘FileOutputStream out = new FileOutputStream(new File("D:\\mm.xlsx"));excel.write(out);
// 关闭资源out.close();excel.close();}public static void main(String[] args) throws Exception {write();}
}
说明:在D盘读取文件
/*通过POI读取Excel文件中的内容* @throws Exception* */public static void read() throws Exception{FileInputStream in = new FileInputStream(new File("D:\\mm.xlsx"));//读取磁盘上存在excel文件XSSFWorkbook excel = new XSSFWorkbook(in);//读取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);}//关闭资源in.close();excel.close();}public static void main(String[] args) throws Exception {
// write();read();}
3.展示