1.引入POI依赖
2.
package com.cowcow.poi;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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.XSSFWorkbook;
public class MainClass {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
//MainClass.writeExcel("student.xlsx");
MainClass.readExcel("student.xlsx");
}
public static void writeExcel(String url) throws IOException {
Workbook workbook = null;
if (url.endsWith("xls")) {
workbook = new HSSFWorkbook();
} else if (url.endsWith("xlsx")) {
workbook = new XSSFWorkbook();
} else {
System.out.println("文件格式错误,请检查文件格式!");
}
Sheet sheet = workbook.createSheet("测试");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("姓名");
cell = row.createCell(1);
cell.setCellValue("年龄");
cell = row.createCell(2);
cell.setCellValue("性别");
cell = row.createCell(3);
cell.setCellValue("住址");
for (int i = 1; i <= 10; i++) {
Row rowI = sheet.createRow(i);
for (int j = 0; j < 4; j++) {
rowI.createCell(j).setCellValue(j);
}
}
FileOutputStream fos = new FileOutputStream(url);
workbook.write(fos);
workbook.close();
fos.close();
}
public static void readExcel(String url) throws IOException {
Workbook workbook = null;
FileInputStream fis = new FileInputStream(url);
if (url.endsWith("xls")) {
workbook = new HSSFWorkbook(fis);
} else if (url.endsWith("xlsx")) {
workbook = new XSSFWorkbook(fis);
} else {
System.out.println("文件格式错误,请检查文件格式!");
}
Sheet sheet = workbook.getSheetAt(0);
Row row = sheet.getRow(0);
int start = row.getFirstCellNum();
int end = row.getLastCellNum();
System.out.println(start + "------" + end);
for (int i = start; i < end; i++) {
System.out.println(row.getCell(i).getStringCellValue());
}
workbook.close();
fis.close();
}
}
以上为简单读写Excel