parent
a760ae27f1
commit
8cb7a001bf
@ -0,0 +1,73 @@
|
|||||||
|
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.FileInputStream;
|
||||||
|
import java.io.FileOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
/*
|
||||||
|
* 使用POI操作excel文件
|
||||||
|
* */
|
||||||
|
public class POITest {
|
||||||
|
|
||||||
|
/*
|
||||||
|
* 通过POI创建excel文件并且写入文件内容
|
||||||
|
* */
|
||||||
|
public static void write() throws IOException {
|
||||||
|
//在内存中创建一个excel文件
|
||||||
|
XSSFWorkbook excel = new XSSFWorkbook();
|
||||||
|
//在excel文件中创建一个sheet页
|
||||||
|
XSSFSheet sheet = excel.createSheet("info");
|
||||||
|
//在sheet页中创建行对象,rownum从0开始
|
||||||
|
XSSFRow row = sheet.createRow(1);
|
||||||
|
//创建单元格,写入文件内容
|
||||||
|
row.createCell(1).setCellValue("姓名");
|
||||||
|
row.createCell(2).setCellValue("城市");
|
||||||
|
|
||||||
|
//创建一个新行
|
||||||
|
row = sheet.createRow(2);
|
||||||
|
row.createCell(1).setCellValue("aiming");
|
||||||
|
row.createCell(2).setCellValue("北京");
|
||||||
|
|
||||||
|
//通过输出流将内存中的excel文件写入磁盘中
|
||||||
|
FileOutputStream out = new FileOutputStream(new File("D:\\info.xlsx"));
|
||||||
|
excel.write(out);
|
||||||
|
|
||||||
|
//关闭资源
|
||||||
|
out.close();
|
||||||
|
excel.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* 通过POI读入excel文件中的内容
|
||||||
|
* */
|
||||||
|
public static void read() throws Exception{
|
||||||
|
FileInputStream in = new FileInputStream(new File("D:\\info.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);
|
||||||
|
}
|
||||||
|
//关闭资源
|
||||||
|
excel.close();
|
||||||
|
in.close();
|
||||||
|
}
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
// write();
|
||||||
|
read();
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in new issue