import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;
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.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelUtil {
/**
* 读取Excel
*/
public static void readExcel(File file){
try {
InputStream inputStream = new FileInputStream(file);
Workbook wb = new XSSFWorkbook(inputStream);
//第一个工作表 ,第二个则为1,以此类推...
Sheet sheet = wb.getSheetAt(0);
//得到Excel的总行数
int rowCount = sheet.getPhysicalNumberOfRows();
Row row = null;
for(int rIndex = 0; rIndex <= rowCount; rIndex ++){
//取得这一行
row = sheet.getRow(rIndex);
if(row != null){
int i = 0;
while (true) {
Cell cell = row.getCell(i);
if(cell == null){
break;
}
String value = row.getCell(i)+"";
System.out.print(value+"\t");
i++;
}
System.out.println();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 写入一个Excel文件
*/
public static void write(File file,List<List<String>> listAll){
try {
//新建一个workbook对象
XSSFWorkbook wb = new XSSFWorkbook();
//创建一个sheet表
XSSFSheet sheet = wb.createSheet("sheet");
//创建行
XSSFRow row = sheet.createRow((int) 0);
//解析行标签
for (int i = 0; i < listAll.size(); i++) {
//第几行
row = sheet.createRow(i);
for (int j = 0; j < listAll.get(i).size(); j++) {
//第几列
row.createCell((short) j).setCellValue(listAll.get(i).get(j));
}
}
//输出流
FileOutputStream fout = new FileOutputStream(file);
//写入
wb.write(fout);
//关闭输出流
fout.close();
}catch(Exception e){
e.printStackTrace();
}
}
}