最近工作中要用到从ftp上解析Excel,记录一下当前进度
应用jar包 jxl.jar
主要分三步 连接服务器、将目标文件下载到本地、Excel解析
1.连接服务器
// 连接ftp服务器
private boolean connectServer(String ip, String user, String password,
String path) throws IOException {
// server:FTP服务器的IP地址;
//user:登录FTP服务器的用户名;
//password:登录FTP服务器的用户名的口令;
//path:FTP服务器上的 路径
try {
ftpClient = new FtpClient();
ftpClient.openServer(ip);
ftpClient.login(user, password);
if (path.length() != 0) { // path是ftp服务下主目录的子目录
ftpClient.cd(path);
}
ftpClient.binary(); // 用2进制上传
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
2.将目标文件下载到本地,要注意ftp的路径和文件名乱码以及本地地址必须存在,另外java project和web project的默认地址也不一致,打成war包放在服务器上的路径和eclipse的路径也不同
// FTP文件下载
public void download() throws IOException {
TelnetInputStream ftpIn = null;
FileOutputStream ftpOut = null;
try {
boolean b = connectServer(ip, userName, password, savePath);
// ftpClient.binary();
if (b) {
ftpIn = ftpClient.get(fileName); // fileName为FTP服务器上要下载的文件名
byte[] buf = new byte[204800];
int bufsize = 0;
ftpOut = new FileOutputStream("D:" + "temp" + "/" + fileName); // 存放在本地硬盘的物理位置
while ((bufsize = ftpIn.read(buf, 0, buf.length)) != -1) {
ftpOut.write(buf, 0, bufsize);
}
System.out.println("download success");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ftpIn != null) {
ftpIn.close();
}
if (ftpOut != null) {
ftpOut.close();
}
if (ftpClient != null) {
ftpClient.closeServer();
}
}
}
3.Excel解析,循环按sheet、column、row、cell由大到小解析
public void read() {
Workbook workbook = null;
try {
workbook = Workbook.getWorkbook(new File("D:" + "temp" + "/"
+ fileName));
Sheet[] sheets =workbook.getSheets();
// for(Sheet sheet :sheets){
// System.out.println(sheet.getRows());
// }
Sheet sheet = workbook.getSheet(0);
System.out.println(sheet.getName());
System.out.println(sheet.getColumns());
System.out.println(sheet.getRows());
// }
List<String> list = new ArrayList<String>();
Cell cell = null;// 就是单个单元格
// for (int j = 0; j < sheet.getColumns(); j++) {
// StringBuffer sb = new StringBuffer();
// for (int i = 0; i < sheet.getRows(); i++) {
// cell = sheet.getCell(j, i);
// sb.append(cell.getContents());
// sb.append(",");// 将单元格的每行内容用逗号隔开
// }
// list.add(sb.toString());// 将每行的字符串用一个String类型的集合保存。
// }
for (int j = 0; j < sheet.getRows(); j++) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < sheet.getColumns(); i++) {
cell = sheet.getCell(i, j);
sb.append(cell.getContents());
sb.append(",");// 将单元格的每行内容用逗号隔开
}
list.add(sb.toString());// 将每行的字符串用一个String类型的集合保存。
}
// 迭代集合查看每行的数据
for (String ss : list) {
System.out.println(ss);
}
} catch (BiffException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
workbook.close();
}
}