java excel 导入

/**
* 导入和导出Excel文件类
* 支持2003(xls)和2007(xlsx)版本的Excel文件
*
* @author yxm
*/
public class OperationExcelForPOI {

public static void main(String[] args) {
// 文件所在路径
String execelFile = "D:\\Download\\公司员工履历表5.xls" ;
//String execelFile = "C:/Book2003.xls" ;
// 导入Excel
new OperationExcelForPOI().impExcel(execelFile) ;
// 导出Excel
// String expFilePath = "C:/testBook.xls" ;
// new OperationExcelForPOI().expExcel(expFilePath);
}

/**
* 导入Excel
* @param execelFile
*/
public void impExcel(String execelFile){
try {
// 构造 Workbook 对象,execelFile 是传入文件路径(获得Excel工作区)
Workbook book = null;
try {
// Excel 2007获取方法
book = new XSSFWorkbook(new FileInputStream(execelFile));
} catch (Exception ex) {
// Excel 2003获取方法
book = new HSSFWorkbook(new FileInputStream(execelFile));
}

// 读取表格的第一个sheet页
Sheet sheet = book.getSheetAt(0);
// 定义 row、cell
Row row;
String cell= "";
// 总共有多少行,从0开始
int totalRows = sheet.getLastRowNum() ;
// 循环输出表格中的内容,首先循环取出行,再根据行循环取出列
for (int i = 1; i <= totalRows; i++) {

  

if(row == null){
// continue ;
// }
// 总共有多少列,从0开始
int totalCells = row.getLastCellNum() ;
for (int j = row.getFirstCellNum(); j < totalCells; j++) {
// 处理空列
if(row.getCell(j) == null || ){
continue ;
}
// 通过 row.getCell(j).toString() 获取单元格内容
cell = row.getCell(j).toString();
if("".equals(cell))continue;
System.out.print(cell +"\t");
}
System.out.println("");
//插入SQL

}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

 

 

//action 

String realpath = ServletActionContext.getServletContext().getRealPath("/images");
//D:\apache-tomcat-6.0.18\webapps\struts2_upload\images
System.out.println("realpath: "+realpath);
if (image != null) {
File savefile = new File(new File(realpath), imageFileName);
if (!savefile.getParentFile().exists())
savefile.getParentFile().mkdirs();
FileUtils.copyFile(image, savefile);
ActionContext.getContext().put("message", "文件上传成功");
}

 

posted @ 2014-12-04 10:39  溜溜达达  阅读(277)  评论(0编辑  收藏  举报