Apache POI是一个java的开源库,用来读写微软的offic系列文件。项目官网特意指出,现在最高只支持office 2008。代码很简单,算是一个小demo吧,主要借鉴了这篇博客的代码,感谢原作者。好了,下面贴代码。
public class Test {
public static final String readPath = "C:\\Users\\lenovo\\Desktop\\ex03_demo.xls";
public static final String outPath = "C:\\Users\\lenovo\\Desktop\\1.txt";
public static final StringBuilder sb = new StringBuilder();
public static void main(String[] args) {
Test.read();
}
public static void read(){
try {
//用来将内容写到文件中
BufferedWriter out = new BufferedWriter (new FileWriter(outPath));
//读取excel文件
HSSFWorkbook hwb = new HSSFWorkbook(new FileInputStream(readPath));
for (int numSheet=0;numSheet<hwb.getNumberOfSheets();numSheet++){
//读取所有的sheet,即表
HSSFSheet sheet = hwb.getSheetAt(numSheet);
if (sheet!=null){
for (int i=0;i<sheet.getLastRowNum()+1;i++){
//读取所有的row,即行
HSSFRow row = sheet.getRow(i);
if (row!=null){
for (int j=0;j<row.getLastCellNum();j++){
//读取所有的单元格
HSSFCell cell = row.getCell(j);
if(j == row.getLastCellNum()-1){
//每行读到最后一列时,插入换行符,使输出格式更美观
sb.append(" "+cell+"\r\n");
}else{
sb.append(cell+" ");
}
}
}
}
}
}
System.out.println(sb.toString());
out.write(sb.toString());
out.close();
}catch (Exception e) {
throw new RuntimeException(e);
}
}
}
运行截图: