您的位置:首页 > 编程语言 > Java开发

java解析excel

2017-01-11 00:00 113 查看
//jar包下载地址:http://download.csdn.net/detail/ayearlater/3896587

import java.io.File;
import java.io.IOException;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

public class ReadExcel {
/**
* 读取Excel文件的内容
*
* @param file
*            待读取的文件
* @return
*/
public static String readExcel(File file) {
StringBuffer sb = new StringBuffer();

Workbook wb = null;
try {
// 构造Workbook(工作薄)对象
wb = Workbook.getWorkbook(file);
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

if (wb == null)
return null;

// 获得了Workbook对象之后,就可以通过它得到Sheet(工作表)对象了
Sheet[] sheet = wb.getSheets();

if (sheet != null && sheet.length > 0) {
// 对每个工作表进行循环
for (int i = 0; i < sheet.length; i++) {
// 得到当前工作表的行数
int rowNum = sheet[i].getRows();
for (int j = 0; j < rowNum; j++) {
// 得到当前行的所有单元格
Cell[] cells = sheet[i].getRow(j);
if (cells != null && cells.length > 0) {
// 对每个单元格进行循环
for (int k = 0; k < cells.length; k++) {
// 读取当前单元格的值
String cellValue = cells[k].getContents();
sb.append(cellValue + "\t");
}
}
sb.append("\r\n");
}
sb.append("\r\n");
}
}
// 最后关闭资源,释放内存
wb.close();
return sb.toString();
}

public static void main(String[] args) {
String pathname = "";//放入excel名字
String str = ReadExcel.readExcel(new File(
pathname));
System.out.println(str);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: