Poi 导入或者导出Excel打的方法。
1、导入Excel
2、 Poi导出Excel
public static void main(String[] args) throws IOException {
// 文件所在路径
String filePath = "C:\\Users\\Administrator\\Desktop\\1234.xls" ;
// 导入Excel
new uploadExcelAction().impExcel(filePath);
// // 导出Excel
// String expFilePath = "C:/testBook.xls" ;
// new uploadExcelAction().expExcel(expFilePath);
}
1、导入Excel
public void impExcel(String filePath) throws FileNotFoundException, IOException{
// 构造 Workbook 对象,execelFile 是传入文件路径(获得Excel工作区)
Workbook book = null;
FileInputStream path=new FileInputStream (filePath);
try {
// Excel 2003获取方法
book = new HSSFWorkbook(path);
} catch (Exception ex) {
// Excel 2007获取方法
book = new XSSFWorkbook(path);
}
// 读取表格的第一个sheet页
Sheet sheet = book.getSheetAt(0);
// 定义 row、cell
Row row;
String cell;
// 总共有多少行,从0开始
int totalRows = sheet.getLastRowNum() ;
//总共多少列
int totalCells = sheet.getRow(0).getLastCellNum();
// 循环输出表格中的内容,首先循环取出行,再根据行循环取出列
for (int i = 1; i <= totalRows; i++) {
row = sheet.getRow(i);
// 处理空行
if(row == null){
continue ;
}
for (int j = row.getFirstCellNum(); j < totalCells; j++) {
// 处理空列
if(row.getCell(j) == null){
continue ;
}
// 通过 row.getCell(j).toString() 获取单元格内容
cell = row.getCell(j).toString();
System.out.print(cell + "\t");
}
}
}
2、 Poi导出Excel
public void expExcel(String expFilePath){
OutputStream os = null ;
Workbook book = null;
try {
// 输出流
os = new FileOutputStream(expFilePath);
// 创建工作区(97-2003)
book = new HSSFWorkbook();
// 创建第一个sheet页
Sheet sheet= book.createSheet("test");
// 生成第一行
Row row = sheet.createRow(0);
// 给第一行的第一列赋值
row.createCell(0).setCellValue("column1");
// 给第一行的第二列赋值
row.createCell(1).setCellValue("column2");
// 写文件
book.write(os);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭输出流
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}