poi.jar包
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
public class SaveExlse {
static public String importData() throws IOException, ClassNotFoundException{
File file = new File("E:/student.xls");
if(!file.getName().endsWith(".xls")){
System.out.println("本导入支持excel文件导入");
return "本导入只支持excel文件导入";
}
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(file));
HSSFSheet sheet = workbook.getSheetAt(0);
/**
* 验证表头
*
*/
String[] headers={"学号","姓名","年龄","班级"};
for(int heads=0;heads<headers.length;heads++){
HSSFRow row = sheet.getRow(0);//第一行
HSSFCell cell = row.getCell((short)heads);
if(!cell.getStringCellValue().equals(headers[heads])){
System.out.println("表头不一样");
return "表头不一样";
}
}
/**
* 读取数据
*
*/
int row1 = sheet.getLastRowNum();
System.out.println("**************总共"+row1+"***********行");
for(int i=1;i<row1;i++)
{
HSSFRow row = sheet.getRow(i);//第二行
for(int j=0;j<headers.length;j++){
HSSFCell cell = row.getCell((short)j);
if(!(cell == null) && !cell.equals(""))
{
cell.setCellType(Cell.CELL_TYPE_STRING);//将每一个表格数据转化成String型
System.out.print("第"+i+"行"+"第"+j+"列,");
String fullname = cell.getStringCellValue();
System.out.println(fullname);
}
}
}
return "sucess";
}
public static void main(String[] args) {
try {
SaveExlse.importData();
} catch (Exception e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
}
}
poi excel导入